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
- Model
- Real RAM
- Properties
- deterministicexactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
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 is the consensus base" is linked to the base at each other position . It splits the sites on the position 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 of aligned sites over , a consensus string (by default the most frequent base at each position), a cutoff for the chi-squared statistic, a minimum subset size , and a pseudocount .
Output. A probability model on that captures the strongest dependences of the training sites, and a way to compute for a new site. In a gene finder, the score of a candidate site is the log-likelihood ratio against a background model.
For positions , let be the indicator of . The statistic is Pearson's statistic of the table of counts that crosses with the base 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 is the total dependence of the other positions on .
The algorithm
MDD-BUILD(D, R, c)- 1
if |R| ≤ 1 then return a leaf with the weight matrix of D on R - 2
for each pair i ≠ j in R: χ²[i][j] ← the chi-squared statistic of C_i against X_j over D - 3
if no χ²[i][j] is above the cutoff κ then return a leaf with the weight matrix of D on R - 4
i* ← the i in R with the largest S_i = Σ over j ≠ i of χ²[i][j], ties to the smaller i - 5
D⁺ ← the sites of D with x_i* = c_i*; D⁻ ← the other sites - 6
if |D⁺| < m or |D⁻| < m then return a leaf with the weight matrix of D on R - 7
return 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) MDD-LOG-PROB(x, v)- 8
if v is a leaf then return Σ over j in R_v of ln w_v[j](x_j) - 9
return 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. Every base distribution, in a leaf () or at a split (), is (count ) (), 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 , and the consensus is GAT. Use the toy values , and . For the pair , 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 | |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 4 | 5 | |
| 0 | 1 | 1 | 1 | 3 | |
| total | 1 | 1 | 1 | 5 | 8 |
The expected counts are in the first row and in the second, and . All six statistics are:
| 0 | 1 | |
| 0 | 2 | |
| 1 | 0 | |
| 1 | 2 | |
| 2 | 0 | |
| 2 | 1 |
Three of them are above 3, so the node is split. The sums are , and , so line L4 picks position 2 with consensus T. The five sites with T at position 2 (GAT, GAT, GCT, GAT, TCT) go to , and the other three (GAA, AAC, CAG) go to . Both children have the positions , and neither can be split again without a part under or a statistic above 3, so both are leaves.
- Root, position 2: and .
- Leaf (5 sites): position 0 has G , T , A and C ; position 1 has A , C , G and T .
- Leaf (3 sites): position 0 has A, C and G and T ; position 1 has A and C, G and T .
Then , and . A single weight matrix of the same eight sites gives and . 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 and a node with at most one position is a leaf, so the recursion ends and the tree has depth at most . 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 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 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 sites of length 4 sum to exactly 1.
Proof: The MDD tree is well defined, ends, and gives a probability distributionfull
Let be a non-empty list of aligned sites of length over , let be a consensus string of length , let be the positions to model, and let (the cutoff), (the minimum subset size) and (the pseudocount) be fixed.
Lemma 1 (the statistic). For positions , the statistic of line L2 is at least 0, and it is 0 if and only if the empirical distribution of the base is the same among the sites with and among the others (when both groups are non-empty).
Proof. The statistic is over the cells of the table with , where . Each term is at least 0. A cell with lies in an empty row or column, so its count is 0 too. The sum is 0 if and only if in every cell, that is, if and only if every count equals the product of its row and column totals divided by , which is the stated equality of the two conditional distributions.
Lemma 2 (termination and partition). The recursion ends, the tree has depth at most , and the sets of sites at the leaves form a partition of .
Proof. Each split (line L7) removes the position from for both children, and a node with is a leaf (line L1). So along any path drops by 1 at each level, and the depth is at most . A split puts each site of its set into exactly one child, according to whether (line L5). By induction on the depth, the sets at the leaves under a node partition the set of that node.
Lemma 3 (the choice of the split). At a node that is split, maximizes over , with ties broken by the smaller position; some pair of has a statistic above ; and both parts have at least sites.
Proof. Line L3 returns a leaf if no statistic exceeds , and line L6 returns a leaf if a part is smaller than . Otherwise line L4 chooses by the largest pair .
Theorem (a probability distribution). For every node with position set , the function defined by
where is the child that selects, depends only on the bases of at , satisfies , and sums to 1 over the choices of these bases.
Proof. Every distribution and is with , so it is positive and sums to 1 over . By induction on the height of . For a leaf, the sum of the product over all factors into . For a split on , both children have the position set . Fix the base at . The child is then fixed (the match child if , the other child if not), and by the induction hypothesis the sum of over the bases at is 1. So the total is .
So the root defines a proper probability model of the sites, and (lines L8 and L9) is the sum of the logarithms of the factors along the path from the root to the leaf that selects, which can be used in a log-likelihood ratio against a background model.
Running time. At a node with sites and positions, line L2 fills tables with one pass over the sites each, in time, and the rest of the node costs . The nodes of one depth have disjoint sets of sites (Lemma 2), so one depth costs , and with at most depths the build takes time. If the root is a leaf, the time is . Scoring a site follows one path of length at most and multiplies at most factors in total, so it takes time.
Complexity
- Building. At a node with sites and positions, line L2 fills tables, each in one pass over the sites, in time. The nodes of one depth hold disjoint sets of sites, so a depth costs , and the depth is at most , which gives . If the root is a leaf, the time is . 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 factors, so takes time, the same as a weight matrix. To scan a sequence of length , the cost is .
- Space. The recursion holds the site lists of the current path, in the worst case, and the statistics of one node, . The tree has at most leaves, each with a matrix of 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 stops it from fitting small subsets.
- Asymmetric, by design. It conditions on the consensus indicator , not on the full base . 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 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 so that each leaf has enough sites for frequencies, and use pseudocounts.
- Consensus from the full data. Using the consensus of the subset at a lower node changes the meaning of and the tree; keep one consensus, or say clearly which one is used.
- Probability, not a score. 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7S803Q Edit this page History Report an error Markdown