Algorithm Search⌘K

Algorithmadvanced

Maximal dependence decomposition

Also called MDD splice model.

Build a tree of weight matrices for a signal by splitting the sites on the position with the strongest dependence by chi-squared test.

Time
O(p^3 N) worst · averageΘ(p^2 N) best
Space
O(p N + p^2) extra
Where
N = the number of training sites; p = the length of a site
Properties
deterministicexactofflinerecursive

Maximal dependence decomposition (MDD) is a model of a short signal in DNA, such as the donor (5') splice site at the start of an intron. A position weight matrix treats the positions of a site as independent. In real donor sites they are not, and Burge and Karlin found significant dependences between their positions. MDD finds such dependence in a set of aligned training sites and builds a binary tree from it. At each node it measures, with a chi-squared test, how strongly "the base at position ii is the consensus base" is linked to the base at each other position jj. It splits the sites on the position ii with the largest total and repeats the work in both parts. Each leaf is a weight matrix. Burge and Karlin (1997) introduced MDD for the donor site model of the GENSCAN gene finder, a generalized HMM.

In plain words

You have a few thousand real splice sites, all aligned. Ask, for each position: if I know whether this position shows its usual base, how much does that tell me about the other positions? Take the position that tells the most and sort the sites into two piles: the ones that show the usual base there and the ones that do not. Then ask the same question in each pile, with that position removed. Stop when a pile is small, or when no position tells much any more. In the end, each pile has its own simple table of base frequencies. To score a new site, follow its bases down the tree to one pile, and multiply the frequencies along the way and in the table of that pile.

The problem

Input. A list DD of NN aligned sites x=x0⋯xp−1x = x_0 \cdots x_{p-1} over Σ={A,C,G,T}\Sigma = \{A, C, G, T\}, a consensus string cc (by default the most frequent base at each position), a cutoff κ\kappa for the chi-squared statistic, a minimum subset size mm, and a pseudocount α>0\alpha > 0.

Output. A probability model PP on Σp\Sigma^p that captures the strongest dependences of the training sites, and a way to compute ln⁡P(x)\ln P(x) for a new site. In a gene finder, the score of a candidate site is the log-likelihood ratio ln⁡P(x)−ln⁡Pbg(x)\ln P(x) - \ln P_{\text{bg}}(x) against a background model.

For positions i≠ji \ne j, let CiC_i be the indicator of xi=cix_i = c_i. The statistic χ2(Ci,Xj)\chi^2(C_i, X_j) is Pearson's statistic of the 2×42 \times 4 table of counts that crosses CiC_i with the base xjx_j over the sites of a node. With 3 degrees of freedom, the 0.001 critical value is about 16.27, so a cutoff of 16.3 marks the pairs that are clearly dependent. The sum Si=∑j≠iχ2(Ci,Xj)S_i = \sum_{j \ne i} \chi^2(C_i, X_j) is the total dependence of the other positions on CiC_i.

The algorithm

  1. MDD-BUILD(D, R, c)
  2. 1if |R| ≤ 1 then return a leaf with the weight matrix of D on R
  3. 2for each pair i ≠ j in R: χ²[i][j] ← the chi-squared statistic of C_i against X_j over D
  4. 3if no χ²[i][j] is above the cutoff κ then return a leaf with the weight matrix of D on R
  5. 4i* ← the i in R with the largest S_i = Σ over j ≠ i of χ²[i][j], ties to the smaller i
  6. 5D⁺ ← the sites of D with x_i* = c_i*; D⁻ ← the other sites
  7. 6if |D⁺| < m or |D⁻| < m then return a leaf with the weight matrix of D on R
  8. 7return a split on i* with the base distribution q of D at i* and the children MDD-BUILD(D⁺, R - {i*}, c) and MDD-BUILD(D⁻, R - {i*}, c)
  9. MDD-LOG-PROB(x, v)
  10. 8if v is a leaf then return Σ over j in R_v of ln w_v[j](x_j)
  11. 9return ln q_v(x_i*) + MDD-LOG-PROB(x, the child of v that x_i* = c_i* selects)

The first call is MDD-BUILD(D,{0,…,p−1},c)(D, \{0, \ldots, p - 1\}, c). Every base distribution, in a leaf (wv[j]w_v[j]) or at a split (qvq_v), is (count +α+ \alpha) // (∣Dv∣+4α|D_v| + 4\alpha), so no probability is 0. The consensus stays the one of the full training set at every node, as in the original model.

Example

Take the eight sites GAT, GAT, GCT, GAT, GAA, AAC, CAG and TCT, so p=3p = 3, N=8N = 8 and the consensus is GAT. Use the toy values κ=3\kappa = 3, m=3m = 3 and α=12\alpha = \frac12. For the pair (0,2)(0, 2), the five sites with G at position 0 have the bases T, T, T, T, A at position 2, and the other three have C, G, T. The table is:

A C G T total
x0=Gx_0 = G 1 0 0 4 5
x0≠Gx_0 \ne G 0 1 1 1 3
total 1 1 1 5 8

The expected counts are 5/8,5/8,5/8,25/85/8, 5/8, 5/8, 25/8 in the first row and 3/8,3/8,3/8,15/83/8, 3/8, 3/8, 15/8 in the second, and χ2=34475≈4.587\chi^2 = \frac{344}{75} \approx 4.587. All six statistics are:

ii jj χ2(Ci,Xj)\chi^2(C_i, X_j)
0 1 8/45≈0.1788/45 \approx 0.178
0 2 344/75≈4.587344/75 \approx 4.587
1 0 56/15≈3.73356/15 \approx 3.733
1 2 8/5=1.6008/5 = 1.600
2 0 344/75≈4.587344/75 \approx 4.587
2 1 8/5=1.6008/5 = 1.600

Three of them are above 3, so the node is split. The sums are S0≈4.764S_0 \approx 4.764, S1≈5.333S_1 \approx 5.333 and S2≈6.187S_2 \approx 6.187, so line L4 picks position 2 with consensus T. The five sites with T at position 2 (GAT, GAT, GCT, GAT, TCT) go to D+D^+, and the other three (GAA, AAC, CAG) go to D−D^-. Both children have the positions {0,1}\{0, 1\}, and neither can be split again without a part under m=3m = 3 or a statistic above 3, so both are leaves.

  • Root, position 2: q(T)=1120q(T) = \frac{11}{20} and q(A)=q(C)=q(G)=320q(A) = q(C) = q(G) = \frac{3}{20}.
  • Leaf +2+2 (5 sites): position 0 has G 914\frac{9}{14}, T 314\frac{3}{14}, A and C 114\frac{1}{14}; position 1 has A 12\frac{1}{2}, C 514\frac{5}{14}, G and T 114\frac{1}{14}.
  • Leaf −2-2 (3 sites): position 0 has A, C and G 310\frac{3}{10} and T 110\frac{1}{10}; position 1 has A 710\frac{7}{10} and C, G and T 110\frac{1}{10}.

Then P(GAT)=1120⋅914⋅12=99560≈0.177P(\mathrm{GAT}) = \frac{11}{20} \cdot \frac{9}{14} \cdot \frac{1}{2} = \frac{99}{560} \approx 0.177, and P(AAT)=1120⋅114⋅12=11560≈0.020P(\mathrm{AAT}) = \frac{11}{20} \cdot \frac{1}{14} \cdot \frac{1}{2} = \frac{11}{560} \approx 0.020. A single weight matrix of the same eight sites gives 0.1970.197 and 0.0540.054. In the training data, A at position 0 occurs only when position 2 is not T, and MDD has learned that: it gives AAT less than half of the weight-matrix probability.

Correctness

MDD-BUILD is a recursive partition, and the proof has three parts. First, every split removes its position from RR and a node with at most one position is a leaf, so the recursion ends and the tree has depth at most p−1p - 1. Second, a split puts each site into exactly one child, so the leaves partition the training sites. Third, the model is a probability distribution: by induction on the height of a node, the sum of PvP_v over all bases at its positions is 1, because a leaf is a product of distributions on separate positions, and a split multiplies the distribution qvq_v at its position by a child whose distribution, by induction, sums to 1 over the remaining positions. MDD-LOG-PROB is the logarithm of that product. The full proof is in the proofs folder, and the test file checks that the probabilities of all 444^4 sites of length 4 sum to exactly 1.

Proof: The MDD tree is well defined, ends, and gives a probability distributionfull

Let DD be a non-empty list of NN aligned sites of length pp over Σ={A,C,G,T}\Sigma = \{A, C, G, T\}, let cc be a consensus string of length pp, let R⊆{0,…,p−1}R \subseteq \{0, \ldots, p - 1\} be the positions to model, and let κ\kappa (the cutoff), m≥1m \ge 1 (the minimum subset size) and α>0\alpha > 0 (the pseudocount) be fixed.

Lemma 1 (the statistic). For positions i≠ji \ne j, the statistic χ2(Ci,Xj)\chi^2(C_i, X_j) of line L2 is at least 0, and it is 0 if and only if the empirical distribution of the base xjx_j is the same among the sites with xi=cix_i = c_i and among the others (when both groups are non-empty).

Proof. The statistic is ∑(O−E)2/E\sum (O - E)^2 / E over the cells of the 2×42 \times 4 table with E>0E > 0, where E=(row total)(column total)/NE = (\text{row total})(\text{column total}) / N. Each term is at least 0. A cell with E=0E = 0 lies in an empty row or column, so its count OO is 0 too. The sum is 0 if and only if O=EO = E in every cell, that is, if and only if every count equals the product of its row and column totals divided by NN, which is the stated equality of the two conditional distributions. □\square

Lemma 2 (termination and partition). The recursion ends, the tree has depth at most ∣R∣−1|R| - 1, and the sets of sites at the leaves form a partition of DD.

Proof. Each split (line L7) removes the position i∗i^* from RR for both children, and a node with ∣R∣≤1|R| \le 1 is a leaf (line L1). So along any path ∣R∣|R| drops by 1 at each level, and the depth is at most ∣R∣−1|R| - 1. A split puts each site of its set into exactly one child, according to whether xi∗=ci∗x_{i^*} = c_{i^*} (line L5). By induction on the depth, the sets at the leaves under a node partition the set of that node. □\square

Lemma 3 (the choice of the split). At a node that is split, i∗i^* maximizes Si=∑j∈R,j≠iχ2(Ci,Xj)S_i = \sum_{j \in R, j \ne i} \chi^2(C_i, X_j) over i∈Ri \in R, with ties broken by the smaller position; some pair of RR has a statistic above κ\kappa; and both parts have at least mm sites.

Proof. Line L3 returns a leaf if no statistic exceeds κ\kappa, and line L6 returns a leaf if a part is smaller than mm. Otherwise line L4 chooses i∗i^* by the largest pair (Si,−i)(S_i, -i). □\square

Theorem (a probability distribution). For every node vv with position set RvR_v, the function PvP_v defined by

Pv(x)=∏j∈Rvwv[j](xj) if v is a leaf,Pv(x)=qv(xi) Pv′(x) if v splits on i,P_v(x) = \prod_{j \in R_v} w_v[j](x_j) \text{ if } v \text{ is a leaf}, \qquad P_v(x) = q_v(x_{i}) \, P_{v'}(x) \text{ if } v \text{ splits on } i,

where v′v' is the child that xi=cix_i = c_i selects, depends only on the bases of xx at RvR_v, satisfies Pv(x)>0P_v(x) > 0, and sums to 1 over the 4∣Rv∣4^{|R_v|} choices of these bases.

Proof. Every distribution wv[j]w_v[j] and qvq_v is (count+α)/(∣Dv∣+4α)(\text{count} + \alpha)/(|D_v| + 4\alpha) with α>0\alpha > 0, so it is positive and sums to 1 over Σ\Sigma. By induction on the height of vv. For a leaf, the sum of the product over all x∈ΣRvx \in \Sigma^{R_v} factors into ∏j∑bwv[j](b)=1\prod_{j} \sum_{b} w_v[j](b) = 1. For a split on ii, both children have the position set Rv∖{i}R_v \setminus \{i\}. Fix the base bb at ii. The child v′v' is then fixed (the match child if b=cib = c_i, the other child if not), and by the induction hypothesis the sum of Pv′P_{v'} over the bases at Rv∖{i}R_v \setminus \{i\} is 1. So the total is ∑bqv(b)⋅1=1\sum_{b} q_v(b) \cdot 1 = 1. □\square

So the root defines a proper probability model of the sites, and ln⁡P\ln P (lines L8 and L9) is the sum of the logarithms of the factors along the path from the root to the leaf that xx selects, which can be used in a log-likelihood ratio against a background model.

Running time. At a node with ∣Dv∣=Nv|D_v| = N_v sites and r=∣Rv∣r = |R_v| positions, line L2 fills r(r−1)r(r - 1) tables with one pass over the sites each, in O(r2Nv)O(r^2 N_v) time, and the rest of the node costs O(r2+rNv)O(r^2 + r N_v). The nodes of one depth have disjoint sets of sites (Lemma 2), so one depth costs O(p2N)O(p^2 N), and with at most pp depths the build takes O(p3N)O(p^3 N) time. If the root is a leaf, the time is Θ(p2N)\Theta(p^2 N). Scoring a site follows one path of length at most p−1p - 1 and multiplies at most pp factors in total, so it takes O(p)O(p) time.

Complexity

  • Building. At a node with NvN_v sites and rr positions, line L2 fills r(r−1)r(r - 1) tables, each in one pass over the sites, in O(r2Nv)O(r^2 N_v) time. The nodes of one depth hold disjoint sets of sites, so a depth costs O(p2N)O(p^2 N), and the depth is at most p−1p - 1, which gives O(p3N)O(p^3 N). If the root is a leaf, the time is Θ(p2N)\Theta(p^2 N). Splice site models use about 9 positions for a donor site, so the build takes very little time.
  • Scoring. A site follows one path and multiplies at most pp factors, so ln⁡P(x)\ln P(x) takes O(p)O(p) time, the same as a weight matrix. To scan a sequence of length nn, the cost is O(np)O(n p).
  • Space. The recursion holds the site lists of the current path, O(pN)O(p N) in the worst case, and the statistics of one node, O(p2)O(p^2). The tree has at most min⁡(2p−1,N/m)\min(2^{p-1}, N / m) leaves, each with a matrix of 4p4p numbers.

Properties

  • A tree of weight matrices. Each leaf is a position weight matrix of the positions that its path has not used. A tree with one leaf is the weight matrix of all the data, and the test file checks this case.
  • Models dependence with little data. A full first-order or higher-order model has many more parameters. MDD spends parameters only on the dependences that the test marks as strong, and the minimum size mm stops it from fitting small subsets.
  • Asymmetric, by design. It conditions on the consensus indicator CiC_i, not on the full base xix_i. Each split has two children, so the data are not cut into four parts at each level.
  • Greedy. The split at each node is the best one by the sum of the statistics. It is not a search over all trees, and there is no claim that the tree is optimal for the likelihood.
  • Deterministic. With the tie rule of line L4, the same data give the same tree.

Variants and improvements

  • Other signals. The same procedure can model acceptor sites, start codons or other short signals. Burge and Karlin used MDD for the donor site and a windowed weight array model, which conditions each position on the one before it, for the acceptor.
  • Other split tests. Mutual information or a likelihood ratio can replace the chi-squared statistic. The tree is then a decision tree built for density estimation.
  • Maximum entropy models. Yeo and Burge (2004) fit the distribution of largest entropy that matches chosen low-order marginal counts of real sites. The model uses all pairs of positions, not one tree, and they report it as more accurate than simpler splice site models.
  • Bayesian networks and discriminative models. A Bayesian network learns a general graph of dependences between positions. Support vector machines and neural networks learn a classifier of true against false sites directly, at the cost of a less transparent model.

When to use it

Use MDD for a short signal with a known alignment and a clear consensus, when the training set is a few hundred to a few thousand sites, and when there is evidence of dependence between positions that a weight matrix misses. It fits well inside a generalized HMM, where a signal model must return a probability in O(p)O(p) time. For a signal with no clear consensus, or for very large training sets, a maximum entropy model or a discriminative classifier is often better.

Pitfalls

  • The cutoff is not a test of the tree. The statistics of a node are tested many times and on data chosen by earlier splits, so the 0.001 level is only a rule of thumb.
  • Small subsets. Without a minimum size, deep leaves have few sites and their matrices are noise. Choose mm so that each leaf has enough sites for 4∣R∣4|R| frequencies, and use pseudocounts.
  • Consensus from the full data. Using the consensus of the subset at a lower node changes the meaning of CiC_i and the tree; keep one consensus, or say clearly which one is used.
  • Probability, not a score. P(x)P(x) alone ranks sites by how typical they are. To separate true sites from random sequence that happens to contain GT, compare it with a background model.
  • Alignment. The model assumes that every site is aligned on the same exon and intron boundary. Sites from a wrong annotation add false dependence.

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)
maximal_dependence_decomposition.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-dependence-decomposition/. The authors are listed in prov/7S803Q.jsonl.
"""Maximal dependence decomposition (MDD) of aligned signal sites.

The input is a list of aligned sites of the same length p over ACGT, for
example donor splice sites. Each position i has a consensus base c[i]. MDD
builds a binary tree:
- At a node with the set D of sites and the set R of positions not yet used,
  it computes, for every pair i != j in R, the chi-squared statistic of the
  2 x 4 table that crosses "x[i] == c[i]" with the base x[j].
- If no statistic is above the cutoff, or fewer than two positions are left,
  the node is a leaf with a weight matrix (one base distribution per position
  of R) estimated from D.
- Otherwise it picks the position i* with the largest sum S_i of its
  statistics, splits D into the sites with x[i*] == c[i*] and the others, and
  builds both children with R - {i*}, unless one part has fewer than min_size
  sites, in which case the node is a leaf.

The model gives each site x the probability
P(x | leaf) = product over j in R of w[j][x[j]], and
P(x | split on i) = q[x[i]] * P(x | child chosen by x[i] == c[i]),
where q is the base distribution at i* of the node. All probabilities use the
counts plus a pseudocount, and they are Fractions, so they are exact.
Ties between positions go to the smaller position.
"""

from __future__ import annotations

import math
from collections import namedtuple
from fractions import Fraction
from typing import Dict, List, Optional, Sequence, Tuple

BASES = "ACGT"

Leaf = namedtuple("Leaf", ["size", "positions", "wmm"])
Split = namedtuple("Split", ["size", "pos", "base", "dist", "match", "other"])


def consensus(sites: Sequence[str]) -> str:
    """The most frequent base at each position; ties go to the first in ACGT order."""
    p = len(sites[0])
    out = []
    for i in range(p):
        counts = {b: 0 for b in BASES}
        for s in sites:
            counts[s[i]] += 1
        out.append(max(BASES, key=lambda b: (counts[b], -BASES.index(b))))
    return "".join(out)


def chi_squared(sites: Sequence[str], i: int, j: int, c: str) -> Fraction:
    """Pearson's chi-squared statistic of (x[i] == c) against the base x[j], exact."""
    table = {(m, b): 0 for m in (True, False) for b in BASES}
    for s in sites:
        table[(s[i] == c, s[j])] += 1
    n = len(sites)
    rows = {m: sum(table[(m, b)] for b in BASES) for m in (True, False)}
    cols = {b: table[(True, b)] + table[(False, b)] for b in BASES}
    total = Fraction(0)
    for m in (True, False):
        for b in BASES:
            if rows[m] and cols[b]:
                e = Fraction(rows[m] * cols[b], n)
                total += (table[(m, b)] - e) ** 2 / e
    return total


def base_distribution(sites: Sequence[str], i: int, pseudo: Fraction) -> Dict[str, Fraction]:
    """The base frequencies at position i with a pseudocount added to each base."""
    counts = {b: 0 for b in BASES}
    for s in sites:
        counts[s[i]] += 1
    z = len(sites) + 4 * pseudo
    return {b: (counts[b] + pseudo) / z for b in BASES}


def _leaf(sites, R, pseudo):
    return Leaf(len(sites), tuple(R), {j: base_distribution(sites, j, pseudo) for j in R})


def build_mdd(sites: Sequence[str], cons: Optional[str] = None, positions: Optional[Sequence[int]] = None,
              cutoff: float = 16.3, min_size: int = 20, pseudo: Fraction = Fraction(1, 2)):
    """The MDD tree of the sites. cutoff 16.3 is about the 0.001 level of chi-squared with 3 df."""
    if not sites:
        raise ValueError("need at least one site")
    p = len(sites[0])
    if any(len(s) != p or any(c not in BASES for c in s) for s in sites):
        raise ValueError("sites must have the same length and use only ACGT")
    c = cons if cons is not None else consensus(sites)
    R = list(range(p)) if positions is None else sorted(positions)
    return _build(list(sites), R, c, cutoff, min_size, Fraction(pseudo))


def _build(D, R, c, cutoff, min_size, pseudo):
    if len(R) <= 1:  # @line L1
        return _leaf(D, R, pseudo)
    chi = {(i, j): chi_squared(D, i, j, c[i]) for i in R for j in R if i != j}  # @line L2
    if not any(v > cutoff for v in chi.values()):  # @line L3
        return _leaf(D, R, pseudo)
    best = max(R, key=lambda i: (sum(chi[(i, j)] for j in R if j != i), -i))  # @line L4
    plus = [s for s in D if s[best] == c[best]]  # @line L5
    minus = [s for s in D if s[best] != c[best]]
    if len(plus) < min_size or len(minus) < min_size:  # @line L6
        return _leaf(D, R, pseudo)
    rest = [j for j in R if j != best]
    return Split(len(D), best, c[best], base_distribution(D, best, pseudo),  # @line L7
                 _build(plus, rest, c, cutoff, min_size, pseudo),
                 _build(minus, rest, c, cutoff, min_size, pseudo))


def prob(x: str, node) -> Fraction:
    """The exact probability of the site x under the tree."""
    out = Fraction(1)
    while isinstance(node, Split):
        out *= node.dist[x[node.pos]]
        node = node.match if x[node.pos] == node.base else node.other
    for j in node.positions:
        out *= node.wmm[j][x[j]]
    return out


def log_prob(x: str, node) -> float:
    """ln P(x) under the tree."""
    if isinstance(node, Leaf):
        return sum(math.log(node.wmm[j][x[j]]) for j in node.positions)  # @line L8
    return math.log(node.dist[x[node.pos]]) + log_prob(  # @line L9
        x, node.match if x[node.pos] == node.base else node.other)


def leaves(node) -> List[Tuple[str, int]]:
    """The leaves as (path, size), where the path lists the splits, such as '+3 -0'."""
    out: List[Tuple[str, int]] = []

    def rec(n, path):
        if isinstance(n, Leaf):
            out.append((" ".join(path), n.size))
        else:
            rec(n.match, path + ["+%d" % n.pos])
            rec(n.other, path + ["-%d" % n.pos])

    rec(node, [])
    return out
test_maximal_dependence_decomposition.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-dependence-decomposition/. The authors are listed in prov/7S803Q.jsonl.
"""Tests of maximal dependence decomposition."""

import itertools
import math
import random
import unittest
from fractions import Fraction

from bioseq import random_dna
from maximal_dependence_decomposition import (BASES, Leaf, Split, base_distribution, build_mdd,
                                              chi_squared, consensus, leaves, log_prob, prob)


def chi_float(sites, i, j, c):
    """The chi-squared statistic by the textbook formula, in floating point."""
    n = len(sites)
    obs = [[sum(1 for s in sites if (s[i] == c) == m and s[j] == b) for b in BASES] for m in (True, False)]
    rows = [sum(r) for r in obs]
    cols = [obs[0][k] + obs[1][k] for k in range(4)]
    t = 0.0
    for r in range(2):
        for k in range(4):
            e = rows[r] * cols[k] / n
            if e > 0:
                t += (obs[r][k] - e) ** 2 / e
    return t


def dependent_sites(rng, n):
    """Sites of length 6. Position 0 is G with probability 0.6; after a G at 0,
    position 3 is A with probability 0.85, otherwise position 3 is uniform.
    The other positions are independent."""
    out = []
    for _ in range(n):
        s = list(random_dna(rng, 6, 0.5))
        s[0] = "G" if rng.random() < 0.6 else rng.choice("ACT")
        if s[0] == "G" and rng.random() < 0.85:
            s[3] = "A"
        else:
            s[3] = rng.choice(BASES)
        out.append("".join(s))
    return out


class TestChiSquared(unittest.TestCase):
    def test_hand_example(self):
        # Position 0 against position 1, consensus G at 0. Matches GA, GA, GC; non-matches TC, TC, AT.
        sites = ["GA", "GA", "GC", "TC", "TC", "AT"]
        # Table: match row A2 C1 T0; other row A0 C2 T1. Column totals A2 C3 T1, n 6.
        # Expected 1, 1.5, 0.5 in each row. Sum of (O-E)^2/E = 2 * (1 + 1/6 + 1/2) = 10/3.
        self.assertEqual(chi_squared(sites, 0, 1, "G"), Fraction(10, 3))

    def test_matches_float_formula(self):
        rng = random.Random(31)
        for _ in range(20):
            sites = [random_dna(rng, 5, rng.random()) for _ in range(rng.randrange(2, 40))]
            c = consensus(sites)
            for i, j in itertools.permutations(range(5), 2):
                self.assertAlmostEqual(float(chi_squared(sites, i, j, c[i])), chi_float(sites, i, j, c[i]), places=9)

    def test_independent_columns_give_zero(self):
        # Every combination once: the indicator and the base are independent.
        sites = ["".join(p) for p in itertools.product(BASES, repeat=2)]
        self.assertEqual(chi_squared(sites, 0, 1, "A"), 0)


class TestTree(unittest.TestCase):
    def test_consensus(self):
        self.assertEqual(consensus(["GTA", "GTC", "ATC"]), "GTC")
        self.assertEqual(consensus(["AC", "CA"]), "AA")

    def test_planted_dependence_found_at_root(self):
        rng = random.Random(32)
        sites = dependent_sites(rng, 600)
        tree = build_mdd(sites, min_size=30)
        self.assertIsInstance(tree, Split)
        self.assertIn(tree.pos, (0, 3))
        c = consensus(sites)
        S = {i: sum(chi_float(sites, i, j, c[i]) for j in range(6) if j != i) for i in range(6)}
        self.assertEqual(tree.pos, max(range(6), key=lambda i: (S[i], -i)))
        self.assertEqual(sum(size for _, size in leaves(tree)), 600)

    def test_independent_sites_give_a_leaf(self):
        rng = random.Random(33)
        sites = [random_dna(rng, 5, 0.5) for _ in range(400)]
        tree = build_mdd(sites, cutoff=30.0)
        self.assertIsInstance(tree, Leaf)
        self.assertEqual(tree.positions, (0, 1, 2, 3, 4))

    def test_min_size_stops_the_split(self):
        rng = random.Random(34)
        sites = dependent_sites(rng, 600)
        self.assertIsInstance(build_mdd(sites, min_size=10 ** 6), Leaf)

    def test_probabilities_sum_to_one(self):
        rng = random.Random(35)
        sites = [s[:4] for s in dependent_sites(rng, 300)]
        tree = build_mdd(sites, min_size=10, cutoff=5.0)
        self.assertIsInstance(tree, Split)
        total = sum(prob("".join(x), tree) for x in itertools.product(BASES, repeat=4))
        self.assertEqual(total, 1)
        for x in ("GACA", "TTTT", "CGTA"):
            self.assertAlmostEqual(log_prob(x, tree), math.log(prob(x, tree)), places=12)

    def test_leaf_is_a_weight_matrix(self):
        sites = ["GTAAGT", "GTGAGT", "GTAAGA", "GTAGGT"]
        tree = build_mdd(sites, cutoff=1e9)
        x = "GTAAGT"
        expect = Fraction(1)
        for j in range(6):
            expect *= base_distribution(sites, j, Fraction(1, 2))[x[j]]
        self.assertEqual(prob(x, tree), expect)

    def test_mdd_beats_weight_matrix_on_dependent_data(self):
        rng = random.Random(36)
        train, test = dependent_sites(rng, 800), dependent_sites(rng, 400)
        mdd = build_mdd(train, min_size=30)
        wmm = build_mdd(train, cutoff=1e9)
        self.assertGreater(sum(log_prob(x, mdd) for x in test), sum(log_prob(x, wmm) for x in test))

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            build_mdd([])
        with self.assertRaises(ValueError):
            build_mdd(["ACG", "AC"])
        with self.assertRaises(ValueError):
            build_mdd(["ACN"])


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

History

Burge and Karlin introduced maximal dependence decomposition in their 1997 paper on GENSCAN, as the model of the donor splice site, after they found dependences between the positions of human donor sites that a weight matrix does not capture. Their 1998 review lists MDD with the weight array model, HMMs, decision trees and neural networks as the main models of splice sites, and reports in its Table 1 that the GENSCAN splice site models, on the Burset and Guigó set of vertebrate genes, are much more accurate inside the gene finder than alone. Yeo and Burge (2004) later proposed maximum entropy models of splice sites as a more general way to model the same dependences.

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 maximal dependence decomposition model of the donor splice site, built from chi-squared tests of the consensus indicators against the other positions
  2. Christopher B. Burge and Samuel Karlin, Finding the genes in genomic DNA, Current Opinion in Structural Biology 8(3), 1998, pp. 346 to 354; the list of splice site models and Table 1, the accuracy of the GENSCAN splice site models alone and inside the gene finder
  3. Gene Yeo and Christopher B. Burge, Maximum entropy modeling of short sequence motifs with applications to RNA splicing signals, Journal of Computational Biology 11(2-3), 2004, the maximum entropy models of 9 base donor sites and 23 base acceptor sites, compared with simpler splice site models

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