Algorithm Search⌘K

Algorithmresearch

Fixed-parameter MEC dynamic programming

Also called WhatsHap algorithm.

Solve weighted MEC exactly with a dynamic program over the variant columns. The time is exponential only in the coverage and linear in the number of columns.

Time
O(2^c m) worst · average · best
Space
O(2^c m) extra
Where
c = the largest number of fragments active at one column; m = the number of variant columns
Properties
deterministicexactofflineiterative
Origin
Murray Patterson, Tobias Marschall, Nadia Pisanti, Leo van Iersel, Leen Stougie, Gunnar W. Klau, Alexander Schönhuth, 2015

The fixed-parameter MEC dynamic program solves the minimum error correction problem exactly, column by column. At each variant column it keeps one table entry for each way to split the reads that cover the column into two groups, and it carries the best cost from one column to the next. The table of a column has 2c2^c entries when cc reads cover it, so the time is O(2cm)O(2^c m) for mm columns: exponential in the coverage, but linear in the number of columns and not dependent on the read length. This makes MEC fixed-parameter tractable in the coverage. Patterson et al. (2015) used it in WhatsHap, which phases long reads that cover many variants.

In plain words

You have many reads from the two copies of a chromosome, and at each place where the copies can differ, each read shows one of two letters. Some letters are wrong. You want to sort the reads into two piles, one for each copy, changing as few letters as possible so that each pile agrees with itself.

Work along the chromosome from left to right. At each place, only the reads that cover it matter, and there are not many of them. For each way to sort just those reads into two piles, write down the least cost of all the work done so far. When you move to the next place, the reads that cover both places must stay in their pile, so each new entry looks back only at the entries that agree with it. At the end, take the cheapest entry and follow the choices back.

The problem

The input is a fragment matrix with nn rows (the fragments, usually reads) and mm columns (the heterozygous variant sites). Entry Fi(j)F_i(j) is 0, 1 or a hole, and each non-hole entry has a weight wi(j)≥0w_i(j) \ge 0, often its Phred quality. Find a bipartition (R,S)(R, S) of the fragments and two haplotypes h1,h2∈{0,1}mh_1, h_2 \in \{0, 1\}^m that minimize the total weight of the entries that differ from the haplotype of their part:

∑i∈R∑j:Fi(j)≠h1(j)wi(j)+∑i∈S∑j:Fi(j)≠h2(j)wi(j).\sum_{i \in R} \sum_{j : F_i(j) \ne h_1(j)} w_i(j) + \sum_{i \in S} \sum_{j : F_i(j) \ne h_2(j)} w_i(j).

With all weights 1 this is MEC; with weights it is weighted MEC (wMEC). In the all-heterozygous form, h2h_2 must be the complement of h1h_1.

A fragment is active at every column from its first to its last non-hole entry, holes inside included, and A(j)A(j) is the set of fragments active at column jj. The coverage cc is the largest ∣A(j)∣|A(j)|. For a set XX of fragments, Wj(X,a)W_j(X, a) is the weight of the entries of XX in column jj that are not aa: the cost to set them all to aa.

The algorithm

For a bipartition BB of A(j)A(j) and a set YY, B∩YB \cap Y is the bipartition that BB induces on A(j)∩YA(j) \cap Y.

  1. WHATSHAP-MEC(F, w, m)
  2. 1A(j) ← the fragments active at column j, for j = 1, ..., m
  3. 2for j ← 1 to m do
  4. 3X ← A(j)
  5. 4for each bipartition B = (R, S) of X do
  6. 5Δ(j, B) ← min_a W_j(R, a) + min_a W_j(S, a)
  7. 6if j = 1 then C(j, B) ← Δ(j, B)
  8. 7else C(j, B) ← Δ(j, B) + C̄(j - 1, B ∩ A(j - 1))
  9. 8C̄(j, B') ← min C(j, B) over the B with B ∩ A(j + 1) = B', and D(j, B') ← that B
  10. 9B*(m) ← a bipartition B of A(m) with the least C(m, B)
  11. 10for j ← m - 1 down to 1 do B*(j) ← D(j, B*(j + 1) ∩ A(j))
  12. 11h1(j), h2(j) ← the alleles that reach the two minima of Δ(j, B*(j)), for each j
  13. 12return C(m, B*(m)), h1, h2 and the parts of B*

Line L5 is the cost of column jj alone: each part takes the allele that is cheaper for it, and the entries against it are flipped. In the all-heterozygous form, line L5 becomes min⁡a(Wj(R,a)+Wj(S,1−a))\min_a (W_j(R, a) + W_j(S, 1 - a)). Line L7 joins column jj to the best solution of the columns before it that agrees with BB on the fragments that are active at both j−1j - 1 and jj. Line L8 groups the entries of column jj by the part that will matter at column j+1j + 1, which is how the table moves from one set of active fragments to the next: a fragment that ends at jj is dropped, and one that starts at j+1j + 1 can go to either side.

The code encodes a bipartition of A(j)A(j) as a bit mask, with bit tt set when the tt-th active fragment is in SS. It computes Wj(X,0)W_j(X, 0) and Wj(X,1)W_j(X, 1) for all masks XX at once, each from the mask with its lowest bit removed, and it maps a mask over A(j)A(j) to a mask over A(j)∩A(j+1)A(j) \cap A(j + 1) with a table built the same way.

Example

The example of Patterson et al. (2015) has four fragments and two columns, with weights in brackets:

fragment column 1 column 2
f0f_0 0 (5)
f1f_1 1 (3) 0 (2)
f2f_2 1 (6) 1 (1)
f3f_3 0 (2)

So A(1)={f0,f1,f2}A(1) = \{f_0, f_1, f_2\} and A(2)={f1,f2,f3}A(2) = \{f_1, f_2, f_3\}. Column 1 has eight bipartitions; four of them, with the other four the same with RR and SS exchanged, are:

RR SS Δ(1,B)\Delta(1, B) flips
f0,f1,f2f_0, f_1, f_2 none 5 f0f_0 to 1
f1,f2f_1, f_2 f0f_0 0 none
f0,f2f_0, f_2 f1f_1 5 f0f_0 to 1
f0,f1f_0, f_1 f2f_2 3 f1f_1 to 0

Line L8 groups these by the side of f1f_1 and f2f_2, the fragments that are also active at column 2. When f1f_1 and f2f_2 are on the same side, the best is 0 (with f0f_0 on the other side). When they are apart, the best is 3. At column 2, f1f_1 shows 0 and f2f_2 shows 1, so keeping them together costs 1, the weight of f2f_2 at column 2, whichever side f3f_3 takes. Splitting them costs at least 3+03 + 0. The optimum is 1: the code returns R={f1,f2,f3}R = \{f_1, f_2, f_3\} with h1=10h_1 = 10 and S={f0}S = \{f_0\} with h2=00h_2 = 00, and the one flip is the entry of f2f_2 at column 2. In the all-heterozygous form the cost is also 1, with h2=01h_2 = 01.

Correctness

Two facts make the table work. First, for a fixed bipartition of all fragments, the cost is a sum over columns, and the term of column jj depends only on the fragments in A(j)A(j), so the best haplotypes are found column by column, by line L5. Second, a fragment is active on an interval of columns, so a sequence of bipartitions of the sets A(j)A(j) that agree on every pair of adjacent columns comes from one bipartition of all fragments: a fragment cannot change sides without leaving its interval. Lines L6 to L8 compute, by induction on jj, the least cost over such sequences that end in a given bipartition, and lines L9 to L11 follow the stored choices back. The proof is in proofs/correctness.md, and the tests compare the code with a search over all pairs of haplotypes.

Proof: The column dynamic program returns an optimal weighted MEC solutionfull

Setting. There are nn fragments and mm columns. Fragment ii has an allele Fi(j)∈{0,1}F_i(j) \in \{0, 1\} and a weight wi(j)≥0w_i(j) \ge 0 at each column jj in its set of defined columns JiJ_i; the other columns are holes. A fragment with Ji≠∅J_i \ne \emptyset is active at every column from min⁡Ji\min J_i to max⁡Ji\max J_i, and A(j)A(j) is the set of fragments active at column jj. A bipartition of a set XX is a pair (R,S)(R, S) with R∪S=XR \cup S = X and R∩S=∅R \cap S = \emptyset. For a set YY, the restriction of (R,S)(R, S) to YY is (R∩Y,S∩Y)(R \cap Y, S \cap Y).

For a set XX of fragments, a column jj and an allele aa, let Wj(X,a)=∑i∈X, j∈Ji, Fi(j)≠awi(j)W_j(X, a) = \sum_{i \in X,\ j \in J_i,\ F_i(j) \ne a} w_i(j), the cost to set column jj of every fragment in XX to aa. The weighted MEC problem asks for a bipartition (R,S)(R, S) of all fragments and two haplotypes h1,h2∈{0,1}mh_1, h_2 \in \{0, 1\}^m that minimize

cost(R,S,h1,h2)=∑j=1m(Wj(R,h1(j))+Wj(S,h2(j))).\mathrm{cost}(R, S, h_1, h_2) = \sum_{j=1}^{m} \bigl(W_j(R, h_1(j)) + W_j(S, h_2(j))\bigr).

In the all-heterozygous form, h2h_2 must be the complement of h1h_1. The value is the same as min⁡h1,h2∑imin⁡(di(h1),di(h2))\min_{h_1, h_2} \sum_i \min(d_i(h_1), d_i(h_2)), where di(h)d_i(h) is the weight of the entries of fragment ii that differ from hh, because for fixed haplotypes the best bipartition puts each fragment on the side of the closer haplotype. This second form is what the tests compute by brute force.

The algorithm computes, at lines L4 and L5,

Δ(j,(R,S))=min⁡aWj(R,a)+min⁡aWj(S,a)\Delta(j, (R, S)) = \min_a W_j(R, a) + \min_a W_j(S, a)

for each bipartition (R,S)(R, S) of A(j)A(j), or min⁡a(Wj(R,a)+Wj(S,1−a))\min_a \bigl(W_j(R, a) + W_j(S, 1 - a)\bigr) in the all-heterozygous form.

Lemma 1 (one bipartition). Fix a bipartition (R,S)(R, S) of all fragments. Then min⁡h1,h2cost(R,S,h1,h2)=∑jΔ(j,(R∩A(j),S∩A(j)))\min_{h_1, h_2} \mathrm{cost}(R, S, h_1, h_2) = \sum_j \Delta(j, (R \cap A(j), S \cap A(j))), and the minimum is reached by taking h1(j)h_1(j) and h2(j)h_2(j) as the alleles that give the two minima of Δ\Delta.

Proof. The cost is a sum over columns, and the term of column jj depends only on h1(j)h_1(j) and h2(j)h_2(j). So the minimum over (h1,h2)(h_1, h_2) is the sum over jj of the minimum over (h1(j),h2(j))(h_1(j), h_2(j)). In the free form the two choices are independent and give min⁡aWj(R,a)+min⁡aWj(S,a)\min_a W_j(R, a) + \min_a W_j(S, a). In the all-heterozygous form there is one choice a=h1(j)a = h_1(j), which gives the second formula. A fragment with an entry at column jj has min⁡Ji≤j≤max⁡Ji\min J_i \le j \le \max J_i, so it is in A(j)A(j). Fragments outside A(j)A(j) add 0 to WjW_j, so Wj(R,a)=Wj(R∩A(j),a)W_j(R, a) = W_j(R \cap A(j), a), and the same holds for SS. □\square

Lemma 2 (consistent sequences). Call a sequence B1,…,BmB_1, \ldots, B_m, with BjB_j a bipartition of A(j)A(j), consistent when BjB_j and Bj+1B_{j+1} have the same restriction to A(j)∩A(j+1)A(j) \cap A(j+1) for each j<mj < m. The restrictions of a bipartition of all fragments to the sets A(j)A(j) form a consistent sequence, and each consistent sequence comes from a bipartition of all fragments in this way.

Proof. The first claim is clear, because two restrictions of one bipartition agree on every common fragment. For the second claim, take a consistent sequence. A fragment ii with Ji≠∅J_i \ne \emptyset is in A(j)A(j) exactly for jj in the interval [min⁡Ji,max⁡Ji][\min J_i, \max J_i]. For two adjacent columns j,j+1j, j+1 of that interval, ii is in A(j)∩A(j+1)A(j) \cap A(j+1), so consistency puts ii on the same side in BjB_j and Bj+1B_{j+1}. By induction along the interval, ii is on the same side in every BjB_j that contains it. Put ii on that side. Put each fragment with no entries on either side; it is in no A(j)A(j). The restrictions of this bipartition are the given sequence. □\square

The interval property is the reason for the definition of active: a paired read with a long gap between its mates stays in A(j)A(j) over the gap, so the sequence cannot move it from one side to the other there.

By Lemmas 1 and 2, the optimum of weighted MEC is min⁡∑jΔ(j,Bj)\min \sum_j \Delta(j, B_j) over consistent sequences.

Lemma 3 (table invariant). After line L7 for column jj, for each bipartition BB of A(j)A(j), C(j,B)=min⁡∑l=1jΔ(l,Bl)C(j, B) = \min \sum_{l=1}^{j} \Delta(l, B_l) over the sequences B1,…,BjB_1, \ldots, B_j that are consistent up to jj and have Bj=BB_j = B. After line L8, Cˉ(j,B′)\bar C(j, B') is the minimum of C(j,B)C(j, B) over the bipartitions BB of A(j)A(j) whose restriction to A(j)∩A(j+1)A(j) \cap A(j+1) is B′B', and D(j,B′)D(j, B') is a BB that reaches it.

Proof. By induction on jj. For j=1j = 1, the only sequence is B1=BB_1 = B, and line L6 sets C(1,B)=Δ(1,B)C(1, B) = \Delta(1, B). For j>1j > 1, a sequence consistent up to jj with Bj=BB_j = B is a sequence consistent up to j−1j - 1 whose last element Bj−1B_{j-1} has the same restriction to A(j−1)∩A(j)A(j-1) \cap A(j) as BB, followed by BB. The cost is Δ(j,B)\Delta(j, B) plus the cost of the first part. The least cost of the first part, over all choices, is min⁡C(j−1,Bj−1)\min C(j-1, B_{j-1}) over those Bj−1B_{j-1}, by the induction hypothesis, and this is Cˉ(j−1,B′)\bar C(j-1, B') with B′B' the restriction of BB to A(j−1)∩A(j)A(j-1) \cap A(j). Line L7 adds these two numbers. The claim on Cˉ\bar C and DD is the definition of line L8: the code visits each BB, maps it to its restriction, and keeps the smallest value and the first BB that gives it. □\square

Theorem. Line L9 finds the optimal weighted MEC cost C∗=min⁡BC(m,B)C^* = \min_B C(m, B). Lines L10 and L11 return a bipartition of the fragments and haplotypes h1,h2h_1, h_2 with cost(R,S,h1,h2)=C∗\mathrm{cost}(R, S, h_1, h_2) = C^*, and the MEC value of (h1,h2)(h_1, h_2), with each fragment on its closer haplotype, is also C∗C^*.

Proof. By Lemma 3 with j=mj = m and the remark after Lemma 2, C∗C^* is the optimum. Line L10 sets Bm∗B^*_m to a minimizer and then Bj∗=D(j,Bj+1∗∩A(j))B^*_j = D(j, B^*_{j+1} \cap A(j)) for j=m−1j = m - 1 down to 1. By Lemma 3, Bj∗B^*_j has the same restriction to A(j)∩A(j+1)A(j) \cap A(j+1) as Bj+1∗B^*_{j+1}, so the sequence is consistent, and C(j+1,Bj+1∗)=Δ(j+1,Bj+1∗)+C(j,Bj∗)C(j+1, B^*_{j+1}) = \Delta(j+1, B^*_{j+1}) + C(j, B^*_j). Summing these equations gives ∑jΔ(j,Bj∗)=C(m,Bm∗)=C∗\sum_j \Delta(j, B^*_j) = C(m, B^*_m) = C^*. By Lemma 2 the sequence comes from a bipartition (R,S)(R, S) of all fragments, which is the returned side. Line L11 takes for each column the alleles that reach the minima in Δ(j,Bj∗)\Delta(j, B^*_j), so by Lemma 1, cost(R,S,h1,h2)=C∗\mathrm{cost}(R, S, h_1, h_2) = C^*. Last, the MEC value of (h1,h2)(h_1, h_2) moves each fragment to its closer haplotype, so it is at most C∗C^*, and it is at least C∗C^* because C∗C^* is the optimum. □\square

Cost. Let c=max⁡j∣A(j)∣c = \max_j |A(j)|. Line L1 costs O(n+∑i(max⁡Ji−min⁡Ji+1))O(n + \sum_i (\max J_i - \min J_i + 1)). For each column, the code computes the subset sums Wj(⋅,0)W_j(\cdot, 0) and Wj(⋅,1)W_j(\cdot, 1) over the 2∣A(j)∣2^{|A(j)|} masks, each from a mask with one bit less, in O(2∣A(j)∣)O(2^{|A(j)|}) time. Then Δ\Delta, the projection of each mask to the intersection, CC and Cˉ\bar C also take O(2∣A(j)∣)O(2^{|A(j)|}) time. So the time is O(2cm)O(2^c m) plus the cost of line L1, and the back pointers take O(2cm)O(2^c m) space. Because (R,S)(R, S) and (S,R)(S, R) have the same Δ\Delta and the same CC, an implementation can keep one of each two masks, which gives the bound O(2c−1m)O(2^{c-1} m) of Patterson et al. (2015). The code keeps both.

Complexity

  • Time. Column jj costs O(2∣A(j)∣)O(2^{|A(j)|}) for the subset sums, Δ\Delta, the projection and CC. The total is O(2cm)O(2^c m), plus O(n+∑iℓi)O(n + \sum_i \ell_i) to find the active sets, where ℓi\ell_i is the number of columns a fragment spans. The read length does not enter, only how many reads overlap at one place.
  • Half the masks. (R,S)(R, S) and (S,R)(S, R) have the same cost, so an implementation can keep one of the two and get O(2c−1m)O(2^{c-1} m), the bound of Patterson et al. The code keeps both.
  • Space. The back pointers take O(2cm)O(2^c m) space. Only two columns of costs are kept at a time.
  • In practice. With c=20c = 20, a column has about 10610^6 entries, so tools first select a subset of the reads that keeps the coverage below a set value, and phase with the rest.

Properties

  • Exact. It returns an optimal solution of weighted MEC, a theorem, not a heuristic. The result is optimal for the reads that it is given; after read selection it is optimal for the selected reads only.
  • Fixed-parameter tractable in the coverage. MEC is NP-hard, even for gapless fragments, so no polynomial algorithm is expected. This one is polynomial for each fixed coverage.
  • Linear in the number of columns. It does not depend on how many columns a read spans, so long reads with many variants cost no more per column than short ones.
  • One pass. It goes once from left to right and once back. The table does not depend on the order of the reads.

Variants and improvements

  • All-heterozygous. If the columns are known heterozygous sites, h2h_2 is the complement of h1h_1; only line L5 changes.
  • Genotypes and pedigrees. Later work on WhatsHap extends the same dynamic program to re-genotype the sites and to phase a parent and child trio together, with a cost that grows with the number of people.
  • Read selection. Before the dynamic program, keep a subset of the reads with high quality and many variants, with the coverage of each column at most a bound.
  • Polyploid genomes. With kk haplotypes, the table has one entry for each assignment of the active reads to kk parts, kck^c entries per column.
  • Heuristics for higher coverage. Haplotype assembly tools such as HapCUT use max-cut style local search instead of an exact table, with no bound on the coverage.

When to use it

Use it to phase one diploid sample from long reads, or from paired or linked reads, when the coverage after read selection is small, about 15 to 20. It is the standard exact method for this case. For short reads with few variants per read, a heuristic is fast enough and gives about the same phase. For the phase of many people from genotypes, the problem is haplotype phasing, which this method does not solve.

Pitfalls

  • The coverage is the coverage of active fragments. A paired read is active over the gap between its mates, so a library of pairs with a long insert can have a much higher cc than its depth suggests.
  • Exponential memory. The back pointers are O(2cm)O(2^c m). A region of very high coverage, such as a repeat, can make one column too large.
  • Weights must be comparable. wMEC adds the weights of different reads, so Phred values that are not calibrated give the wrong optimum.
  • Ties. Many optima can have the same cost, as in the example, where f3f_3 can go to either side. A phase between two blocks with no read in common is not defined; the table then joins the blocks in an arbitrary way.
  • Homozygous columns. A column where both haplotypes have the same allele carries no phase information; if it is in the input, use the free form, not the all-heterozygous form.

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.

fixed_parameter_mec.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fixed-parameter-mec/. The authors are listed in prov/W2Z7FH.jsonl.
"""The dynamic program of WhatsHap for weighted minimum error correction (wMEC).

A fragment is a dict {column: allele}, with columns 0-based (0 to m - 1) and
alleles 0 or 1. A column that is not in the dict is a hole. The weights have the
same shape, {column: weight}; with no weights every entry costs 1 to flip.

A fragment is active in every column from its leftmost to its rightmost
non-hole column, so the internal segment of a paired read counts as covered.
The coverage c of a column is the number of active fragments. The table of
column j has one entry for each bipartition (R, S) of the active fragments,
encoded as a bit mask: bit t is 1 when the t-th active fragment is in S.

The cost is O(2^c m) time for maximum coverage c and m columns, after an
O(n + total number of entries) pass to find the active fragments. Patterson
et al. (2015) store only half of the masks, because (R, S) and (S, R) have the
same cost; this code keeps all of them, which costs a factor 2.
"""

from __future__ import annotations

from typing import Dict, List, Optional, Sequence, Tuple

Fragment = Dict[int, int]


def _subset_sums(vals: Sequence[int]) -> List[int]:
    """sums[mask] = the sum of vals[t] over the bits t of mask, in O(2^len) time."""
    sums = [0] * (1 << len(vals))
    for mask in range(1, len(sums)):
        low = mask & -mask
        sums[mask] = sums[mask ^ low] + vals[low.bit_length() - 1]
    return sums


def _bit_map(src: Sequence[int], dst: Sequence[int]) -> List[int]:
    """proj[mask] maps a mask over the list src to a mask over the list dst.

    A bit of an item of src that is not in dst is dropped.
    """
    where = {f: t for t, f in enumerate(dst)}
    bit = [1 << where[f] if f in where else 0 for f in src]
    proj = [0] * (1 << len(src))
    for mask in range(1, len(proj)):
        low = mask & -mask
        proj[mask] = proj[mask ^ low] | bit[low.bit_length() - 1]
    return proj


def active_sets(fragments: Sequence[Fragment], m: int) -> List[List[int]]:
    """A[j] = the indices of the fragments active at column j, in increasing order."""
    A: List[List[int]] = [[] for _ in range(m)]
    for i, f in enumerate(fragments):  # @line L1
        if f:
            for j in range(min(f), max(f) + 1):
                A[j].append(i)
    return A


def column_costs(fragments: Sequence[Fragment], weights, active: Sequence[int], j: int,
                 all_het: bool) -> Tuple[List[int], List[int], List[int]]:
    """Return delta, w0 and w1 for every mask over the active fragments of column j.

    w0[mask] is the cost to set column j of every fragment in mask to 0, and
    w1[mask] the cost to set it to 1. delta[mask] is the least cost to make
    column j conflict free when mask is S and the other active fragments are R.
    """
    to0, to1 = [], []
    for i in active:
        a = fragments[i].get(j)
        wt = 0 if a is None else (1 if weights is None else weights[i][j])
        to0.append(wt if a == 1 else 0)
        to1.append(wt if a == 0 else 0)
    w0, w1 = _subset_sums(to0), _subset_sums(to1)
    full = (1 << len(active)) - 1
    delta = []
    for s in range(full + 1):  # @line L4
        r = full ^ s
        if all_het:  # @line L5
            delta.append(min(w0[r] + w1[s], w1[r] + w0[s]))
        else:
            delta.append(min(w0[r], w1[r]) + min(w0[s], w1[s]))
    return delta, w0, w1


def whatshap_mec(fragments: Sequence[Fragment], m: int, weights: Optional[Sequence[Dict[int, int]]] = None,
                 all_het: bool = False) -> Tuple[int, List[int], List[int], List[int]]:
    """Solve wMEC exactly.

    Returns (cost, h1, h2, side): the least total weight of flips, two haplotypes
    as lists of 0 and 1, and side[i] = 0 if fragment i is in the part of h1 and 1
    if it is in the part of h2. A column with no active fragment gets 0 in both
    haplotypes (0 and 1 under all_het). A fragment with no entries gets side 0.
    """
    if m == 0:
        return 0, [], [], [0] * len(fragments)
    A = active_sets(fragments, m)
    back: List[List[int]] = []  # back[j][mask over A[j] & A[j+1]] = best mask over A[j]
    prev_bar: Optional[List[int]] = None
    for j in range(m):  # @line L2
        cur = A[j]  # @line L3
        delta, _, _ = column_costs(fragments, weights, cur, j, all_het)
        if j == 0:  # @line L6
            C = delta
        else:  # @line L7
            proj_in = _bit_map(cur, inter)
            C = [delta[s] + prev_bar[proj_in[s]] for s in range(len(delta))]
        if j + 1 < m:  # @line L8
            inter = [f for f in cur if f in set(A[j + 1])]
            proj_out = _bit_map(cur, inter)
            bar = [None] * (1 << len(inter))
            arg = [0] * (1 << len(inter))
            for s, cost in enumerate(C):
                p = proj_out[s]
                if bar[p] is None or cost < bar[p]:
                    bar[p], arg[p] = cost, s
            back.append(arg)
            prev_bar = bar
    best = min(range(len(C)), key=lambda s: (C[s], s))  # @line L9
    cost = C[best]
    masks = [0] * m
    masks[m - 1] = best
    for j in range(m - 2, -1, -1):  # @line L10
        inter = [f for f in A[j] if f in set(A[j + 1])]
        masks[j] = back[j][_bit_map(A[j + 1], inter)[masks[j + 1]]]
    side = [0] * len(fragments)
    h1, h2 = [0] * m, [0] * m
    for j in range(m):  # @line L11
        for t, i in enumerate(A[j]):
            side[i] = (masks[j] >> t) & 1
        _, w0, w1 = column_costs(fragments, weights, A[j], j, all_het)
        s = masks[j]
        r = ((1 << len(A[j])) - 1) ^ s
        if all_het:
            h1[j] = 0 if w0[r] + w1[s] <= w1[r] + w0[s] else 1
            h2[j] = 1 - h1[j]
        else:
            h1[j] = 0 if w0[r] <= w1[r] else 1
            h2[j] = 0 if w0[s] <= w1[s] else 1
    return cost, h1, h2, side  # @line L12


def flip_cost(fragment: Fragment, hap: Sequence[int], weight: Optional[Dict[int, int]] = None) -> int:
    """The weight of the entries of fragment that differ from hap."""
    return sum((1 if weight is None else weight[j]) for j, a in fragment.items() if hap[j] != a)


def mec_cost(fragments: Sequence[Fragment], h1: Sequence[int], h2: Sequence[int],
             weights: Optional[Sequence[Dict[int, int]]] = None) -> int:
    """The MEC objective of a haplotype pair: each fragment goes to the closer haplotype."""
    total = 0
    for i, f in enumerate(fragments):
        wt = None if weights is None else weights[i]
        total += min(flip_cost(f, h1, wt), flip_cost(f, h2, wt))
    return total
test_fixed_parameter_mec.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fixed-parameter-mec/. The authors are listed in prov/W2Z7FH.jsonl.

import itertools
import random

from fixed_parameter_mec import active_sets, column_costs, mec_cost, whatshap_mec

# Fig. 1 of Patterson et al. (2015), with columns renumbered from 0.
PAPER_FRAGS = [{0: 0}, {0: 1, 1: 0}, {0: 1, 1: 1}, {1: 0}]
PAPER_WEIGHTS = [{0: 5}, {0: 3, 1: 2}, {0: 6, 1: 1}, {1: 2}]


def brute_mec(fragments, m, weights=None, all_het=False):
    """Least MEC cost over all haplotype pairs (h1, h2), or all (h1, complement) pairs."""
    haps = list(itertools.product((0, 1), repeat=m))
    best = None
    for h1 in haps:
        partners = [tuple(1 - a for a in h1)] if all_het else haps
        for h2 in partners:
            c = mec_cost(fragments, h1, h2, weights)
            if best is None or c < best:
                best = c
    return best


def random_fragments(rng, n, m, max_len, hole_rate):
    frags = []
    for _ in range(n):
        start = rng.randrange(m)
        end = min(m, start + rng.randint(1, max_len))
        f = {j: rng.randint(0, 1) for j in range(start, end) if j == start or rng.random() >= hole_rate}
        frags.append(f)
    return frags


def test_paper_example_first_column():
    A = active_sets(PAPER_FRAGS, 2)
    assert A == [[0, 1, 2], [1, 2, 3]]
    delta, _, _ = column_costs(PAPER_FRAGS, PAPER_WEIGHTS, A[0], 0, False)
    # mask bit t = 1 puts the t-th active fragment in S.
    assert delta[0b000] == 5  # ({f0, f1, f2}, {})
    assert delta[0b100] == 3  # ({f0, f1}, {f2})
    assert delta[0b010] == 5  # ({f0, f2}, {f1})
    assert delta[0b001] == 0  # ({f1, f2}, {f0})


def test_paper_example_optimum():
    cost, h1, h2, side = whatshap_mec(PAPER_FRAGS, 2, PAPER_WEIGHTS)
    assert cost == 1
    assert mec_cost(PAPER_FRAGS, h1, h2, PAPER_WEIGHTS) == 1
    assert side[1] == side[2] == side[3] != side[0]
    assert brute_mec(PAPER_FRAGS, 2, PAPER_WEIGHTS) == 1


def test_conflict_free_input_costs_zero():
    h = [0, 1, 1, 0, 1, 0]
    g = [1 - a for a in h]
    frags = [{0: 0, 1: 1, 2: 1}, {2: 0, 3: 1, 4: 0}, {3: 0, 4: 1, 5: 0}, {0: 1, 5: 1}]
    cost, h1, h2, _ = whatshap_mec(frags, 6, all_het=True)
    assert cost == 0
    assert {tuple(h1), tuple(h2)} == {tuple(h), tuple(g)}


def test_against_brute_force_unweighted():
    rng = random.Random(7)
    for _ in range(60):
        m = rng.randint(1, 5)
        frags = random_fragments(rng, rng.randint(1, 7), m, 4, 0.2)
        cost, h1, h2, _ = whatshap_mec(frags, m)
        assert cost == brute_mec(frags, m)
        assert mec_cost(frags, h1, h2) == cost


def test_against_brute_force_weighted_and_all_het():
    rng = random.Random(11)
    for _ in range(60):
        m = rng.randint(1, 7)
        frags = random_fragments(rng, rng.randint(1, 8), m, 5, 0.3)
        weights = [{j: rng.randint(1, 9) for j in f} for f in frags]
        for all_het in (False, True):
            cost, h1, h2, _ = whatshap_mec(frags, m, weights, all_het)
            assert cost == brute_mec(frags, m, weights, all_het)
            assert mec_cost(frags, h1, h2, weights) == cost
            if all_het:
                assert all(a != b for a, b in zip(h1, h2))


def test_all_het_twelve_columns():
    rng = random.Random(12)
    m = 12
    frags = random_fragments(rng, 14, m, 5, 0.25)
    cost, h1, h2, _ = whatshap_mec(frags, m, all_het=True)
    assert cost == brute_mec(frags, m, all_het=True)


def test_side_matches_cost():
    rng = random.Random(3)
    for _ in range(30):
        m = rng.randint(2, 6)
        frags = random_fragments(rng, 6, m, 4, 0.2)
        cost, h1, h2, side = whatshap_mec(frags, m)
        total = 0
        for f, s in zip(frags, side):
            hap = h2 if s else h1
            total += sum(1 for j, a in f.items() if hap[j] != a)
        assert total == cost


def test_recovers_simulated_haplotypes():
    rng = random.Random(2015)
    m = 40
    h = [rng.randint(0, 1) for _ in range(m)]
    g = [1 - a for a in h]
    frags = []
    for _ in range(60):
        start = rng.randrange(m - 3)
        end = min(m, start + rng.randint(4, 8))
        src = h if rng.random() < 0.5 else g
        frags.append({j: (1 - src[j]) if rng.random() < 0.03 else src[j] for j in range(start, end)})
    cost, h1, h2, _ = whatshap_mec(frags, m, all_het=True)
    assert {tuple(h1), tuple(h2)} == {tuple(h), tuple(g)}
    assert cost <= mec_cost(frags, h, g)
    assert max(len(a) for a in active_sets(frags, m)) <= 16


def test_empty_and_gap_columns():
    assert whatshap_mec([], 0) == (0, [], [], [])
    frags = [{0: 1}, {0: 0}, {3: 1}, {3: 1}]
    cost, h1, h2, _ = whatshap_mec(frags, 4)
    assert cost == 0
    assert {h1[0], h2[0]} == {0, 1}

History

Lancia et al. (2001) and Lippert et al. (2002) defined MEC and other models of haplotype assembly from fragment conflicts. MEC is NP-hard, and Cilibrasi et al. (2007) proved that it stays NP-hard when no fragment has a hole. Patterson et al. described WhatsHap, the dynamic program on this page, and published it in the Journal of Computational Biology in 2015, for third-generation reads that span many variants. The WhatsHap tool later added pedigree phasing and genotyping.

References

  1. Murray Patterson, Tobias Marschall, Nadia Pisanti, Leo van Iersel, Leen Stougie, Gunnar W. Klau and Alexander Schönhuth, WhatsHap, weighted haplotype assembly for future-generation sequencing reads, Journal of Computational Biology 22(6), 2015, pp. 498 to 509, the sections on the dynamic programming algorithm (the active fragments, the bipartitions of each column, the recurrence and the O(2^(c-1) m) bound) and on the all-heterozygous case
  2. Rudi Cilibrasi, Leo van Iersel, Steven Kelk and John Tromp, The complexity of the single individual SNP haplotyping problem, Algorithmica 49(1), 2007, pp. 13 to 36 (MEC is NP-hard also for gapless fragments, and polynomial cases)
  3. Ross Lippert, Russell Schwartz, Giuseppe Lancia and Sorin Istrail, Algorithmic strategies for the single nucleotide polymorphism haplotype assembly problem, Briefings in Bioinformatics 3(1), 2002, the sections on the fragment conflict models and their complexity

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
  • a scene preset for the example