Algorithm Search⌘K

Algorithmintro

Open reading frame finding

Also called six-frame ORF scan.

Scan the three frames of each strand once, codon by codon, and report every open reading frame that reaches a length cutoff. It takes O(G) time for a sequence of length G.

Time
Θ(G + R log R) worst · averageΘ(G) best
Space
Θ(G + R) extra
Where
G = the length of the DNA sequence; R = the number of ORFs reported
Properties
deterministicexactofflineiterative

ORF finding lists the open reading frames of a DNA sequence. It reads the sequence in each of the three frames of each strand, one codon at a time, and keeps one number per frame: where the current ORF began. When it meets a stop codon, the run from that position to the stop is an ORF, and it is reported if it reaches a length cutoff. The scan reads each codon of the six frames once, so it takes O(G)O(G) time for a sequence of GG bases. It is the first step of most bacterial gene finders: the ORFs are the candidates, and a codon model such as a three-periodic Markov chain or an interpolated Markov model then decides which of them are genes.

In plain words

A gene of a bacterium is read three letters at a time, from a start word (usually ATG) to one of three stop words (TAA, TAG or TGA). We do not know where the reading begins, so there are three ways to cut the sequence into words of three letters, and three more on the other strand. For each of the six ways, walk along the words. Remember the first start word you see. When a stop word comes, the stretch from the remembered start to the stop is a candidate gene; write it down if it is long enough, and forget the start. Long stretches without a stop are rare by chance, so the long candidates are worth a closer look.

The problem

Input. A DNA sequence ss of length GG over {A,C,G,T}\{A, C, G, T\}, a minimum length ℓ\ell in sense codons, a set START\mathrm{START} of start codons (by default {ATG}\{\mathrm{ATG}\}), the stop codons STOP={TAA,TAG,TGA}\mathrm{STOP} = \{\mathrm{TAA}, \mathrm{TAG}, \mathrm{TGA}\} of the standard code, and one of the two definitions of an ORF.

Output. Every ORF of ss in the six frames with at least ℓ\ell sense codons, each as a strand, a frame, an interval of ss and a number of codons. With the start-stop definition, an ORF runs from a start codon to the next in-frame stop codon, and for each stop codon only the longest ORF is kept, the one from the first start codon after the previous stop. With the stop-stop definition, an ORF runs from right after a stop codon (or from the first codon of the frame) to the next stop codon. The definition page gives both in full. A run of codons with no stop codon before the end of the sequence is not reported.

The page and the code use 0-based, half-open intervals [a,b)[a, b) in the pseudocode, as Python does, and 1-based positions in the text. An ORF on the minus strand is given by its interval on ss; its bases are rc(s[a,b))\mathrm{rc}(s[a, b)).

The algorithm

For each frame, the scan keeps the position open where the current ORF began, or none if no ORF is open. In start-stop mode, open is set at the first start codon after a stop. In stop-stop mode, open is set right after each stop, and at the first codon of the frame.

  1. FIND-ORFS(s, ℓ, START, mode)
  2. 1for each strand (t, sign) in ((s, +), (rc(s), -)) do
  3. 2for each offset f in 0, 1, 2 do ▷ open ← none in start-stop mode, f in stop-stop mode
  4. 3for i ← f, f + 3, f + 6, ... while i + 3 ≤ G do
  5. 4if c = t[i, i + 3) is in STOP then
  6. 5if open ≠ none and (i - open) / 3 ≥ ℓ then
  7. 6add the ORF [open, i + 3) with (i - open) / 3 sense codons
  8. 7open ← none in start-stop mode, i + 3 in stop-stop mode
  9. 8else if open = none and c is in START then
  10. 9open ← i
  11. 10map each ORF [a, b) of the minus strand to the interval [G - b, G - a) of s
  12. 11return the ORFs, sorted by start, end, strand and frame

Line L8 sets open only when no ORF is open, so a second ATG inside an open ORF does not move its start; this keeps the longest ORF for each stop. Line L10 converts coordinates: base pp of rc(s)\mathrm{rc}(s) (from 0) is the complement of base G−1−pG - 1 - p of ss, so the interval [a,b)[a, b) of rc(s)\mathrm{rc}(s) covers [G−b,G−a)[G - b, G - a) of ss. The test for STOP and START is a look-up of one codon among 64, which takes constant time.

Example

Take the 30 bases s=GATGAAAATGTTTTGACTAGGGCATCCATGs = \mathrm{GATGAAAATGTTTTGACTAGGGCATCCATG}, with ℓ=0\ell = 0 and the start-stop definition. The reverse complement is CATGGATGCCCTAGTCAAAACATTTTCATC\mathrm{CATGGATGCCCTAGTCAAAACATTTTCATC}. The translations of the six frames, with ∗* for a stop, are:

frame offset ff translation
+1+1 0 D E N V L T R A S M
+2+2 1 M K M F * L G H P
+3+3 2 * K C F D * G I H
−1-1 0 H G C P S Q N I F I
−2-2 1 M D A L V K T F S
−3-3 2 W M P * S K H F H

The scan of frame +2+2 (offset 1) goes as follows; the positions ii are from 0.

ii codon line action open
1 ATG L8, L9 a start, no ORF open 1
4 AAA sense codon 1
7 ATG L8 a start, but an ORF is open: no change 1
10 TTT sense codon 1
13 TGA L4 to L7 a stop: report [1,16)[1, 16) with (13−1)/3=4(13 - 1)/3 = 4 codons none
16, 19, 22, 25 CTA, GGG, CAT, CCA no start none

Then i=28i = 28 fails the test i+3≤30i + 3 \le 30, and the frame ends. Frames +1+1 and −1-1 have no stop codon. Frame +3+3 has stops but no ATG. Frame −2-2 has a start but no stop. In frame −3-3, ATG at offsets 5 to 7 of rc(s)\mathrm{rc}(s) is followed by CCC and the stop TAG at 11 to 13, which gives the interval [5,14)[5, 14) of rc(s)\mathrm{rc}(s) with 2 codons. Line L10 maps it to [30−14,30−5)=[16,25)[30 - 14, 30 - 5) = [16, 25) of ss. So the output is:

strand frame interval of ss (from 0) bases 1-based codons peptide
+ +2+2 [1,16)[1, 16) 2 to 16 4 MKMF
- −3-3 [16,25)[16, 25) 17 to 25 2 MP

With ℓ=3\ell = 3 only the first remains. In stop-stop mode the output has four ORFs: [1,16)[1, 16) in frame +2+2 (it starts at the first codon of the frame), the empty run [2,5)[2, 5) that ends at the TGA at the start of frame +3+3, the run [5,20)[5, 20) with the 4 codons KCFD in frame +3+3, and [16,28)[16, 28) with the 3 codons WMP in frame −3-3. The test file checks all these values.

Correctness

Fix one frame of one strand, with codons c0,c1,…c_0, c_1, \ldots at positions f,f+3,…f, f + 3, \ldots. In start-stop mode, the invariant at the top of line L4 for codon cjc_j is: open is the position of the first start codon after the last stop codon before cjc_j (after the beginning of the frame if there is none), or none if there is no such start codon. In stop-stop mode, open is the position right after the last stop codon before cjc_j, or ff. Lines L7 and L9 keep the invariant, and no other line changes open. When cjc_j is a stop, every ORF that ends at cjc_j begins after the previous stop, so by the invariant the run [open,i+3)[\mathit{open}, i + 3) is the longest start-stop ORF ending at cjc_j, or the stop-stop ORF ending at cjc_j. Every ORF ends at a stop codon, and each stop codon is visited once, so line L6 reports each ORF of the frame with at least ℓ\ell codons exactly once. A run with no stop after it is never reported. Line L10 is correct by the identity rc(s)p=sG−1−p‾\mathrm{rc}(s)_p = \overline{s_{G - 1 - p}}. The full proof is in the proofs folder.

Proof: The six-frame scan reports exactly the ORFs of the sequencefull

Let ss be a sequence of length GG, let ℓ≥0\ell \ge 0, and let START and STOP be disjoint sets of codons. Positions are from 0, and t[i,j)t[i, j) is the part of tt from position ii up to but not including jj.

Fix a strand tt (either ss or rc(s)\mathrm{rc}(s)) and an offset f∈{0,1,2}f \in \{0, 1, 2\}. The codons of the frame are cj=t[f+3j,f+3j+3)c_j = t[f + 3j, f + 3j + 3) for j=0,1,…,J−1j = 0, 1, \ldots, J - 1, where JJ is the largest number with f+3J≤Gf + 3J \le G. Line L3 visits them in the order j=0,1,…,J−1j = 0, 1, \ldots, J - 1, with i=f+3ji = f + 3j. For a codon index jj, let p(j)p(j) be the largest index p<jp < j with cp∈STOPc_p \in \mathrm{STOP}, or −1-1 if there is none. So the codons cp(j)+1,…,cj−1c_{p(j) + 1}, \ldots, c_{j - 1} hold no stop codon.

The ORFs of the frame are as follows (see the definition page). A stop-stop ORF is cp(b)+1,…,cbc_{p(b) + 1}, \ldots, c_b for each bb with cb∈STOPc_b \in \mathrm{STOP}. A start-stop ORF, in the form with the longest ORF for each stop, is ca,…,cbc_a, \ldots, c_b for each bb with cb∈STOPc_b \in \mathrm{STOP} such that some codon among cp(b)+1,…,cb−1c_{p(b) + 1}, \ldots, c_{b - 1} is in START, where aa is the smallest such index. In both cases the ORF covers the interval [f+3a,f+3b+3)[f + 3a, f + 3b + 3) of tt and has b−ab - a sense codons, with a=p(b)+1a = p(b) + 1 for a stop-stop ORF.

Lemma 1 (invariant). Each time line L4 is reached for the codon cjc_j:

  • in start-stop mode, open =f+3a= f + 3a, where aa is the smallest index in {p(j)+1,…,j−1}\{p(j) + 1, \ldots, j - 1\} with ca∈STARTc_a \in \mathrm{START}, and open is none if there is no such index;
  • in stop-stop mode, open =f+3(p(j)+1)= f + 3(p(j) + 1).

Proof. By induction on jj. For j=0j = 0, p(0)=−1p(0) = -1 and the set {0,…,−1}\{0, \ldots, -1\} is empty. Line L2 sets open to none in start-stop mode and to f=f+3⋅0f = f + 3 \cdot 0 in stop-stop mode, as claimed.

Assume the claim for jj, and look at what the loop body does with cjc_j.

Case cj∈STOPc_j \in \mathrm{STOP}. Then p(j+1)=jp(j + 1) = j. Line L7 sets open to none in start-stop mode, which is right because the set {j+1,…,j}\{j + 1, \ldots, j\} is empty. In stop-stop mode it sets open to i+3=f+3(j+1)=f+3(p(j+1)+1)i + 3 = f + 3(j + 1) = f + 3(p(j + 1) + 1). Line L8 is not reached, because START and STOP are disjoint.

Case cj∉STOPc_j \notin \mathrm{STOP}. Then p(j+1)=p(j)p(j + 1) = p(j), and the new set of candidate indices is the old one with jj added. In start-stop mode: if open was set, the smallest start index of the new set is the old one, and line L8 does not change open. If open was none and cj∈STARTc_j \in \mathrm{START}, then jj is the only start index of the new set, and line L9 sets open to i=f+3ji = f + 3j. If open was none and cj∉STARTc_j \notin \mathrm{START}, there is still no start index, and open stays none. In stop-stop mode, open does not change, and p(j+1)=p(j)p(j + 1) = p(j). In all cases the claim holds for j+1j + 1. □\square

Lemma 2. For one frame, lines L3 to L9 add, for each stop codon cbc_b of the frame, the ORF that ends at cbc_b if it exists and has at least ℓ\ell sense codons, and they add nothing else.

Proof. An ORF is added only at line L6, so only when the codon cjc_j is a stop, with i=f+3ji = f + 3j. By Lemma 1, open at that moment is f+3af + 3a for the index aa of the definition of the ORF that ends at cjc_j, in either mode, and open is none exactly when no start-stop ORF ends at cjc_j (in stop-stop mode it is never none). The added interval is [open,i+3)=[f+3a,f+3j+3)[\mathit{open}, i + 3) = [f + 3a, f + 3j + 3), the interval of that ORF, and the count (i−open)/3=j−a(i - \mathit{open})/3 = j - a is its number of sense codons. Line L5 adds it if and only if this count is at least ℓ\ell. Each codon is visited once, so each stop codon gives at most one ORF. Every ORF ends at a stop codon of the frame, so no ORF is missed. □\square

A run of codons after the last stop codon of the frame is not followed by a stop, so it is not an ORF, and it is not added: the loop ends without a stop for it.

Lemma 3 (coordinates of the minus strand). For 0≤p<G0 \le p < G, base pp of rc(s)\mathrm{rc}(s) is the complement of base G−1−pG - 1 - p of ss. So the interval [a,b)[a, b) of rc(s)\mathrm{rc}(s) consists of the complements of the bases of ss in [G−b,G−a)[G - b, G - a), in reverse order, and rc(s[G−b,G−a))=rc(s)[a,b)\mathrm{rc}(s[G - b, G - a)) = \mathrm{rc}(s)[a, b).

Proof. rc(s)\mathrm{rc}(s) is ss reversed and complemented, so its base pp is the complement of base G−1−pG - 1 - p of ss. As pp runs over a,…,b−1a, \ldots, b - 1, the index G−1−pG - 1 - p runs over G−1−aG - 1 - a down to G−bG - b, which is the interval [G−b,G−a)[G - b, G - a) read backward. □\square

Theorem. FIND-ORFS returns every ORF of ss in the six frames with at least ℓ\ell sense codons, each once, with its correct interval on ss, and nothing else.

Proof. Lines L1 and L2 visit the six frames: offsets 0, 1 and 2 of ss and of rc(s)\mathrm{rc}(s). By Lemma 2, the scan of each frame adds exactly the ORFs of that frame with at least ℓ\ell codons, in the coordinates of its strand. Line L10 leaves the plus strand intervals as they are, and by Lemma 3 it maps each minus strand interval [a,b)[a, b) to the interval of ss whose reverse complement is the ORF. ORFs of different frames are different objects, so no ORF is listed twice. Line L11 only sorts. □\square

Running time. Building rc(s)\mathrm{rc}(s) takes Θ(G)\Theta(G) steps. Frame (t,f)(t, f) has Jf=⌊(G−f)/3⌋J_f = \lfloor (G - f)/3 \rfloor codons, and J0+J1+J2≤GJ_0 + J_1 + J_2 \le G, so lines L3 to L9 run at most 2G2G times in total, each in O(1)O(1) time on a word RAM: a codon is a 6-bit key, and the tests of lines L4 and L8 are look-ups in tables of 64 entries. Line L10 costs O(1)O(1) per ORF. Each stop codon gives at most one ORF, so the number RR of ORFs is at most J0+J1+J2≤GJ_0 + J_1 + J_2 \le G per strand, and R≤2GR \le 2G. The sort of line L11 costs O(Rlog⁡R)O(R \log R). The total is Θ(G+Rlog⁡R)\Theta(G + R \log R), and Θ(G)\Theta(G) without the sort.

Complexity

  • Time. Line L1 builds rc(s)\mathrm{rc}(s) in Θ(G)\Theta(G) time. For each strand, the three frames together read ⌊G/3⌋+⌊(G−1)/3⌋+⌊(G−2)/3⌋≤G\lfloor G/3 \rfloor + \lfloor (G-1)/3 \rfloor + \lfloor (G-2)/3 \rfloor \le G codons, and each codon costs O(1)O(1) on a word RAM: it is a 6-bit number, and the start and stop tests are table look-ups. So the scan costs Θ(G)\Theta(G) in every case. With RR ORFs reported, the sort of line L11 adds O(Rlog⁡R)O(R \log R). The sort can be dropped: a merge of the six lists, each already sorted, costs O(Rlog⁡6)=O(R)O(R \log 6) = O(R), and many uses need no order.
  • Number of ORFs. Each stop codon ends at most one reported ORF, and each strand has at most GG codon positions over its three frames, so R≤2GR \le 2G. In random DNA with uniform bases, a codon is a stop with probability 3/643/64 and the chance of at least 100 sense codons before a stop is (61/64)100≈0.0082(61/64)^{100} \approx 0.0082, so a cutoff of 100 codons keeps about 771 ORFs per megabase over the six frames.
  • Space. Θ(G)\Theta(G) for rc(s)\mathrm{rc}(s) and Θ(R)\Theta(R) for the output. A scan of the minus strand that reads ss backward and complements each codon on the fly needs no copy, and then the extra space is O(1)O(1) beyond the output.

Properties

  • Exact and deterministic. It returns exactly the ORFs of the definition; there is no scoring and no randomness.
  • One pass per frame, online in each frame. Each frame is read left to right with one variable of state, so a stream of bases can be scanned as it arrives, for the plus strand. The minus strand needs the stop codons to its right, so it waits for the end of a run or reads the sequence backward.
  • Independent frames. The six scans share nothing, so they run in parallel.
  • Nested ORFs. For each stop codon, start-stop mode gives the longest ORF. The other start-stop ORFs that end at the same stop begin at the later in-frame start codons inside it; listing them all costs O(G)O(G) more, one per start codon.
  • Code dependent. STOP and START come from the genetic code. Table 11 adds GTG, TTG and other starts for bacteria, and table 2 (vertebrate mitochondria) has the stops TAA, TAG, AGA and AGG.

Variants and improvements

  • Alternative start codons. For bacteria, pass START ={ATG,GTG,TTG}= \{\mathrm{ATG}, \mathrm{GTG}, \mathrm{TTG}\}. The ORF is then longer or equal, and the true start is decided later from a ribosome binding site or a start model.
  • Circular genomes. A bacterial chromosome or a plasmid is circular. An ORF can cross the origin. Scan the sequence sss s, written twice, and keep each ORF that starts in the first copy and is not longer than GG. EMBOSS getorf has a -circular option for this.
  • Partial ORFs. On contigs and reads, the ends of the sequence cut genes. A tool for these reports the open run at each end as a partial ORF.
  • Six-frame translation. Translate all six frames and split at the stops. This is the same scan with the protein written out, and it is how a protein database is searched with DNA.
  • Training sets for gene models. Glimmer takes the long ORFs that do not overlap other long ORFs as its first training set for the interpolated Markov model. Later gene finders score every start-stop ORF with a codon model and choose the start codon and the set of genes by dynamic programming.
  • Coding statistics in the scan. A score that is a sum over the codons, such as the log-likelihood ratio of a codon model or the log of the codon adaptation index, can be added up during the scan with a prefix sum per frame. Then the score of any ORF is one subtraction.

When to use it

Use it as the first step of gene finding in bacteria, archaea and viruses, where most genes are one uninterrupted ORF; to translate a sequence before a protein search; to check a cloned or synthetic gene for an intact reading frame; and to list candidates for small proteins. Do not use the ORF list alone as a gene list. A cutoff of 100 codons is a rule of thumb: it misses short genes, and in GC-rich genomes it keeps many chance ORFs, often on the strand opposite a real gene. For eukaryotic genes with introns, use gene prediction with a GHMM, or align a protein or a transcript to the genome with spliced alignment.

Pitfalls

  • Coordinates of the minus strand. The frame number of a minus strand ORF depends on whether the offset is counted on rc(s)\mathrm{rc}(s) or from the start of ss. An ORF at offset ff of rc(s)\mathrm{rc}(s) has its codon boundaries at offset (G−f) mod 3(G - f) \bmod 3 of ss, and the two numbers agree only when G≡2f(mod3)G \equiv 2f \pmod 3. Say which. The code counts it on rc(s)\mathrm{rc}(s).
  • Off by one at the stop. Say whether the stop codon is part of the ORF interval and whether it counts in the length. Here the interval holds the stop, and the length counts sense codons only.
  • Moving the start. Line L8 must not move open when an ORF is already open, or the scan reports the shortest ORF for each stop instead of the longest.
  • Runs to the end. A run with no stop codon is not an ORF. Reporting it as one makes the last ORF of each frame wrong.
  • Lower case and N. Upper-case the sequence first, and decide what a codon with N means; here it is neither a start nor a stop, which can join two ORFs across an unknown stop.
  • The wrong genetic code. A mitochondrial sequence scanned with table 1 breaks its genes at each TGA, which codes for tryptophan there.

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)
orf_finding.py 83 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/orf-finding/. The authors are listed in prov/1C4YKG.jsonl.
"""Six-frame open reading frame finding.

An ORF is reported as Orf(strand, frame, start, end, codons):
- strand is "+" or "-";
- frame is 0, 1 or 2, the offset of the first codon on that strand (on the
  minus strand the offset is counted on the reverse complement);
- start and end are 0-based, half-open coordinates on the forward strand, so
  seq[start:end] is the ORF for "+" and revcomp(seq[start:end]) for "-";
- codons is the number of sense codons, so the stop codon is not counted.

Two definitions are supported:
- mode="start-stop": from a start codon to the next in-frame stop codon, the
  stop included. For each stop only the longest ORF is kept, the one that
  begins at the first start codon after the previous in-frame stop.
- mode="stop-stop": the codons after an in-frame stop (or from the first full
  codon of the frame) up to and including the next in-frame stop.

A reading frame that reaches the end of the sequence without a stop is not
reported; it has no defined end.
"""

from __future__ import annotations

from collections import namedtuple
from typing import Iterable, List

from bioseq import STOPS, revcomp

Orf = namedtuple("Orf", ["strand", "frame", "start", "end", "codons"])


def _scan_frame(t: str, f: int, min_codons: int, starts: frozenset, mode: str):
    """ORFs of one frame of one strand, as (start, end, codons) on that strand."""
    out = []
    opened = None if mode == "start-stop" else f
    for i in range(f, len(t) - 2, 3):  # @line L3
        c = t[i:i + 3]
        if c in STOPS:  # @line L4
            if opened is not None and (i - opened) // 3 >= min_codons:  # @line L5
                out.append((opened, i + 3, (i - opened) // 3))  # @line L6
            opened = None if mode == "start-stop" else i + 3  # @line L7
        elif opened is None and c in starts:  # @line L8
            opened = i  # @line L9
    return out


def find_orfs(seq: str, min_codons: int = 100, mode: str = "start-stop",
              starts: Iterable[str] = ("ATG",)) -> List[Orf]:
    """All ORFs of seq in the six frames with at least min_codons sense codons.

    The result is sorted by (start, end, strand, frame).
    """
    if mode not in ("start-stop", "stop-stop"):
        raise ValueError("mode must be 'start-stop' or 'stop-stop'")
    s = seq.upper()
    G = len(s)
    start_set = frozenset(c.upper() for c in starts)
    found = []
    for strand, t in (("+", s), ("-", revcomp(s))):  # @line L1
        for f in range(3):  # @line L2
            for a, b, n in _scan_frame(t, f, min_codons, start_set, mode):
                if strand == "+":  # @line L10
                    found.append(Orf("+", f, a, b, n))
                else:
                    found.append(Orf("-", f, G - b, G - a, n))
    found.sort(key=lambda o: (o.start, o.end, o.strand, o.frame))
    return found  # @line L11


def orf_sequence(seq: str, orf: Orf) -> str:
    """The bases of an ORF, 5' to 3' on its own strand."""
    part = seq.upper()[orf.start:orf.end]
    return part if orf.strand == "+" else revcomp(part)


def longest_orf(seq: str, mode: str = "start-stop") -> Orf:
    """The ORF with the most codons (any length), or None if there is none."""
    orfs = find_orfs(seq, 0, mode)
    if not orfs:
        return None
    return max(orfs, key=lambda o: (o.codons, -o.start))
test_orf_finding.py 268 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/orf-finding/. The authors are listed in prov/1C4YKG.jsonl.
"""Tests of the ORF finder and of the shared helper bioseq.py."""

import itertools
import math
import random
import unittest

import bioseq
from bioseq import (CODON_TABLE, DNA, STOPS, gc_content, global_align, hamming, kmers,
                    mutate, phred_to_prob, prob_to_phred, random_dna, revcomp,
                    semiglobal_align, simulate_reads, translate)
from orf_finding import Orf, find_orfs, longest_orf, orf_sequence


# ---------------------------------------------------------------- bioseq


def all_alignments(a, b):
    """Every alignment of a and b as a list of ops in M, I, D (brute force)."""
    if not a and not b:
        yield []
        return
    if a and b:
        for rest in all_alignments(a[1:], b[1:]):
            yield ["M"] + rest
    if a:
        for rest in all_alignments(a[1:], b):
            yield ["I"] + rest
    if b:
        for rest in all_alignments(a, b[1:]):
            yield ["D"] + rest


def score_ops(a, b, ops, match, mismatch, gap):
    i = j = 0
    total = 0
    for op in ops:
        if op == "M":
            total += match if a[i] == b[j] else mismatch
            i, j = i + 1, j + 1
        elif op == "I":
            total += gap
            i += 1
        else:
            total += gap
            j += 1
    assert i == len(a) and j == len(b)
    return total


def expand(cigar):
    ops, num = [], ""
    for ch in cigar:
        if ch.isdigit():
            num += ch
        else:
            ops.extend(ch * int(num))
            num = ""
    return ops


class TestBioseq(unittest.TestCase):
    def test_genetic_code(self):
        self.assertEqual(len(CODON_TABLE), 64)
        self.assertEqual(sum(1 for aa in CODON_TABLE.values() if aa != "*"), 61)
        self.assertEqual(STOPS, frozenset({"TAA", "TAG", "TGA"}))
        self.assertEqual(CODON_TABLE["ATG"], "M")
        self.assertEqual(CODON_TABLE["TGG"], "W")
        self.assertEqual(CODON_TABLE["TTT"], "F")
        self.assertEqual(CODON_TABLE["GGG"], "G")
        self.assertEqual(CODON_TABLE["AGA"], "R")
        self.assertEqual(len(set(CODON_TABLE.values()) - {"*"}), 20)
        # the number of codons of each amino acid (degeneracy) in table 1
        counts = {}
        for aa in CODON_TABLE.values():
            counts[aa] = counts.get(aa, 0) + 1
        self.assertEqual((counts["L"], counts["S"], counts["R"]), (6, 6, 6))
        self.assertEqual((counts["M"], counts["W"], counts["I"]), (1, 1, 3))

    def test_translate(self):
        self.assertEqual(translate("ATGGCCTAA"), "MA*")
        self.assertEqual(translate("CATGGCCTAAG", 1), "MA*")
        self.assertEqual(translate("ATGNNN"), "MX")
        self.assertEqual(translate("ATGGC"), "M")
        with self.assertRaises(ValueError):
            translate("ATG", 3)

    def test_revcomp(self):
        rng = random.Random(1)
        self.assertEqual(revcomp("AACGTT"), "AACGTT")
        self.assertEqual(revcomp("ATGC"), "GCAT")
        for _ in range(50):
            s = random_dna(rng, rng.randrange(0, 40))
            self.assertEqual(revcomp(revcomp(s)), s)

    def test_phred(self):
        self.assertAlmostEqual(phred_to_prob(20), 0.01, places=15)
        self.assertAlmostEqual(phred_to_prob(30), 0.001, places=15)
        self.assertAlmostEqual(prob_to_phred(0.05), 13.0103, places=4)
        for q in (0, 10, 20, 30, 40):
            self.assertAlmostEqual(prob_to_phred(phred_to_prob(q)), q, places=9)

    def test_small_functions(self):
        self.assertEqual(hamming("ACGT", "ACCA"), 2)
        with self.assertRaises(ValueError):
            hamming("A", "AC")
        self.assertEqual(kmers("ACGTA", 3), ["ACG", "CGT", "GTA"])
        self.assertEqual(kmers("AC", 3), [])
        self.assertEqual(gc_content("GGCA"), 0.75)
        self.assertEqual(gc_content(""), 0.0)

    def test_random_dna_and_mutate(self):
        rng = random.Random(7)
        n = 10000
        s = random_dna(rng, n, gc=0.6)
        self.assertEqual(set(s) <= set(DNA), True)
        # GC count is Binomial(n, 0.6): mean n p, variance n p (1 - p)
        p = 0.6
        self.assertLessEqual(abs(gc_content(s) * n - n * p), 4 * math.sqrt(n * p * (1 - p)))
        self.assertEqual(random_dna(random.Random(3), 50), random_dna(random.Random(3), 50))
        m = mutate(rng, s, 0.1)
        d = hamming(s, m)
        self.assertLessEqual(abs(d - n * 0.1), 4 * math.sqrt(n * 0.1 * 0.9))
        self.assertEqual(mutate(rng, s, 0.0), s)
        self.assertEqual(hamming(s, mutate(rng, s, 1.0)), n)

    def test_simulate_reads(self):
        rng = random.Random(11)
        genome = random_dna(rng, 2000)
        reads = simulate_reads(rng, genome, 300, 50, 0.0)
        strands = set()
        for r in reads:
            read, pos, strand, true_seq = r
            frag = genome[pos:pos + 50]
            self.assertEqual(true_seq, frag if strand == "+" else revcomp(frag))
            self.assertEqual(read, true_seq)
            strands.add(strand)
        self.assertEqual(strands, {"+", "-"})
        noisy = simulate_reads(rng, genome, 200, 50, 0.05)
        errors = sum(hamming(r.read, r.true_seq) for r in noisy)
        total = 200 * 50
        self.assertLessEqual(abs(errors - total * 0.05), 4 * math.sqrt(total * 0.05 * 0.95))

    def test_alignment_against_brute_force(self):
        rng = random.Random(5)
        for match, mismatch, gap in ((1, -1, -1), (2, -1, -2), (1, 0, -1)):
            for _ in range(60):
                a = random_dna(rng, rng.randrange(0, 6))
                b = random_dna(rng, rng.randrange(0, 6))
                best = max(score_ops(a, b, ops, match, mismatch, gap) for ops in all_alignments(a, b))
                score, cigar = global_align(a, b, match, mismatch, gap)
                self.assertEqual(score, best)
                self.assertEqual(score_ops(a, b, expand(cigar), match, mismatch, gap), score)
                # semiglobal: all of a against the best substring of b
                best_sg = max(
                    max(score_ops(a, b[s:e], ops, match, mismatch, gap) for ops in all_alignments(a, b[s:e]))
                    for s in range(len(b) + 1) for e in range(s, len(b) + 1))
                sc, cg, start = semiglobal_align(a, b, match, mismatch, gap, with_start=True)
                self.assertEqual(sc, best_sg)
                self.assertEqual(semiglobal_align(a, b, match, mismatch, gap), (sc, cg))
                ops = expand(cg)
                used = sum(1 for op in ops if op != "I")
                self.assertEqual(score_ops(a, b[start:start + used], ops, match, mismatch, gap), sc)

    def test_alignment_cases(self):
        self.assertEqual(global_align("ACGT", "ACGT"), (4, "4M"))
        self.assertEqual(global_align("ACGT", "AGT"), (2, "1M1I2M"))
        self.assertEqual(global_align("", "AC"), (-2, "2D"))
        self.assertEqual(semiglobal_align("CGT", "AACGTAA", with_start=True), (3, "3M", 2))


# ---------------------------------------------------------------- ORF finding


def naive_orfs(seq, min_codons, mode="start-stop", starts=("ATG",)):
    """All ORFs by a direct check of every pair of codon positions in the six frames."""
    s = seq.upper()
    G = len(s)
    out = set()
    for strand, t in (("+", s), ("-", revcomp(s))):
        stops = [j for j in range(G - 2) if t[j:j + 3] in STOPS]
        for j in stops:
            f = j % 3
            # the previous in-frame stop, or None
            prev = max((k for k in stops if k < j and k % 3 == f), default=None)
            lo = f if prev is None else prev + 3
            if mode == "start-stop":
                cands = [i for i in range(lo, j, 3) if t[i:i + 3] in starts]
                if not cands:
                    continue
                i = min(cands)
            else:
                i = lo
            n = (j - i) // 3
            if n >= min_codons:
                a, b = i, j + 3
                if strand == "-":
                    a, b = G - b, G - a
                out.add(Orf(strand, f, a, b, n))
    return sorted(out, key=lambda o: (o.start, o.end, o.strand, o.frame))


class TestOrfFinding(unittest.TestCase):
    def test_example_of_the_page(self):
        seq = "GATGAAAATGTTTTGACTAGGGCATCCATG"
        self.assertEqual(revcomp(seq), "CATGGATGCCCTAGTCAAAACATTTTCATC")
        self.assertEqual([translate(seq, f) for f in range(3)], ["DENVLTRASM", "MKMF*LGHP", "*KCFD*GIH"])
        self.assertEqual([translate(revcomp(seq), f) for f in range(3)], ["HGCPSQNIFI", "MDALVKTFS", "WMP*SKHFH"])
        orfs = find_orfs(seq, 0)
        self.assertEqual(orfs, [Orf("+", 1, 1, 16, 4), Orf("-", 2, 16, 25, 2)])
        self.assertEqual(orf_sequence(seq, orfs[0]), "ATGAAAATGTTTTGA")
        self.assertEqual(orf_sequence(seq, orfs[1]), "ATGCCCTAG")
        self.assertEqual(translate(orf_sequence(seq, orfs[1])), "MP*")
        self.assertEqual(find_orfs(seq, 3), [Orf("+", 1, 1, 16, 4)])
        self.assertEqual(longest_orf(seq), Orf("+", 1, 1, 16, 4))
        ss = find_orfs(seq, 0, mode="stop-stop")
        self.assertEqual(ss, [Orf("+", 1, 1, 16, 4), Orf("+", 2, 2, 5, 0), Orf("+", 2, 5, 20, 4),
                              Orf("-", 2, 16, 28, 3)])

    def test_against_naive_scan(self):
        rng = random.Random(2024)
        for trial in range(200):
            seq = random_dna(rng, rng.randrange(0, 120), gc=rng.choice((0.3, 0.5, 0.7)))
            for mode in ("start-stop", "stop-stop"):
                for k in (0, 3, 10):
                    self.assertEqual(find_orfs(seq, k, mode), naive_orfs(seq, k, mode))
        seq = random_dna(rng, 300)
        alt = ("ATG", "GTG", "TTG")
        self.assertEqual(find_orfs(seq, 5, starts=alt), naive_orfs(seq, 5, starts=alt))

    def test_orf_properties(self):
        rng = random.Random(99)
        seq = random_dna(rng, 3000)
        for o in find_orfs(seq, 20):
            protein = translate(orf_sequence(seq, o))
            self.assertEqual(protein[0], "M")
            self.assertEqual(protein[-1], "*")
            self.assertEqual(protein.count("*"), 1)
            self.assertEqual(len(protein) - 1, o.codons)
            self.assertEqual((o.end - o.start) % 3, 0)

    def test_planted_gene_is_found(self):
        rng = random.Random(3)
        sense = [c for c, aa in CODON_TABLE.items() if aa != "*" and c != "ATG"]
        gene = "ATG" + "".join(rng.choice(sense) for _ in range(149)) + "TAA"
        seq = random_dna(rng, 500) + revcomp(gene) + random_dna(rng, 500)
        hits = [o for o in find_orfs(seq, 100) if o.strand == "-" and o.start == 500]
        self.assertEqual(len(hits), 1)
        o = hits[0]
        # the frame on the minus strand is the offset of the ORF in revcomp(seq)
        self.assertEqual((o.end, o.codons, o.frame), (500 + len(gene), 150, (len(seq) - o.end) % 3))
        self.assertEqual(orf_sequence(seq, o), gene)

    def test_edge_cases(self):
        self.assertEqual(find_orfs("", 0), [])
        self.assertEqual(find_orfs("ATGAAA", 0), [])  # no stop: not an ORF
        self.assertEqual(find_orfs("ATGTAA", 0), [Orf("+", 0, 0, 6, 1)])  # revcomp TTACAT has no ATG
        self.assertEqual(find_orfs("TTACAT", 0), [Orf("-", 0, 0, 6, 1)])
        self.assertEqual(find_orfs("TAA", 0, mode="stop-stop"), [Orf("+", 0, 0, 3, 0)])
        self.assertIsNone(longest_orf("AAAAAA"))
        with self.assertRaises(ValueError):
            find_orfs("ATG", 0, mode="other")


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

History

Programs that search the six frames of a sequence for long stretches without stop codons are a standard part of sequence analysis toolkits such as EMBOSS, whose getorf program (Rice, Longden and Bleasby 2000) reports both the regions between stop codons and the regions from a start codon to a stop codon. Glimmer (Salzberg, Delcher, Kasif and White 1998) used the long ORFs of a new genome to train its interpolated Markov model, and later bacterial gene finders score every ORF with codon statistics. The textbook treatment of ORFs as the first step of gene prediction is in Chapter 6 of Jones and Pevzner (2004).

References

  1. Neil C. Jones and Pavel A. Pevzner, An Introduction to Bioinformatics Algorithms, MIT Press, 2004, Chapter 6, the sections on gene prediction (open reading frames and statistical approaches)
  2. EMBOSS getorf manual (Peter Rice, Ian Longden and Alan Bleasby, EMBOSS, Trends in Genetics 16(6), 2000), the -find option (regions between STOP codons, or between START and STOP codons), -minsize, -circular and -reverse
  3. NCBI, The Genetic Codes, table 1 (the standard code) and table 11 (bacterial starts GTG and TTG)
  4. Steven L. Salzberg, Arthur L. Delcher, Simon Kasif and Owen White, Microbial gene identification using interpolated Markov models, Nucleic Acids Research 26(2), 1998, pp. 544 to 548, the use of long ORFs that do not overlap other long ORFs as the training set of Glimmer

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