Algorithm Search⌘K

Algorithmadvanced

Split-read method

Also called split-read SV detection.

Find breakpoints at base resolution by aligning the two parts of a read to different places, as one anchored mate and one split mate.

Time
O(W L) worstO(W) best
Space
O(W) extra
Where
L = the length of the read; W = the length of the search window
Properties
deterministicexactofflineiterative
Origin
Kai Ye, Marcel H. Schulz, Quan Long, Rolf Apweiler, Zemin Ning, 2009

The split-read method finds the exact breakpoint of a deletion or an insertion from a read that crosses it. Such a read does not align to the reference as one piece: its first part matches on one side of the breakpoint and its second part on the other side. In a paired library, the mate of that read maps normally and is the anchor, so the search for the two parts is limited to a short window next to it. The method finds the longest prefix and the longest suffix of the read that match in the window, and the gap or the overlap between them gives the type, the place and the size of the event, to the base. This page follows Pindel (Ye et al., 2009), with exact matches.

In plain words

When a piece of DNA is missing in a sample, a read that crosses the missing piece is the two sides joined together. Its start matches one place on the reference and its end matches a place a little further on.

So take a read that does not match anywhere as a whole, and look near its mate, which did match. Find how much of the start of the read matches there, then how much of its end matches after that. If the two parts are farther apart on the reference than in the read, bases were lost, and the distance tells how many. If they overlap, bases were added, and the read shows which ones.

The problem

The input is a reference ref\mathit{ref}, a read rr of length LL turned to the forward strand of the reference, and a window [lo,hi)[lo, hi) where the read must lie. The window comes from the anchor: it starts at the anchor and is about two insert sizes long. The output is one event that explains the read as two exact parts, each of at least mm bases, or nothing:

  • a deletion of DD bases: r=ref[p:p+i]+ref[p+i+D:e]r = \mathit{ref}[p{:}p + i] + \mathit{ref}[p + i + D{:}e], or
  • an insertion of ι\iota bases: r=ref[p:p+i]+w+ref[p+i:e]r = \mathit{ref}[p{:}p + i] + w + \mathit{ref}[p + i{:}e] with ∣w∣=ι|w| = \iota.

The read must not occur in the window as a whole, and each part must occur only once, so that the place is not in doubt. See structural variant detection for the problem and the other signals.

The algorithm

Pattern growth keeps the list of places where the current prefix occurs and adds one base at a time until the list is empty. The suffix grows in the same way from the right end, only at or after the start pp of the prefix.

  1. SPLIT-READ(ref, r, lo, hi, m, ι_max)
  2. 1P ← the positions x in [lo, hi) with ref[x] = r[0]; a ← 1
  3. 2while a < L and some x in P has ref[x + a] = r[a] do keep those x in P; a ← a + 1
  4. 3if a = L or a < m or |P| ≠ 1 then return none, else p ← the one x in P
  5. 4grow the suffix r[L - b..L) in [p, hi) the same way; Q ← the end positions of its matches
  6. 5if b < m or |Q| ≠ 1 then return none, else e ← the one end in Q
  7. 6D ← e - p - L
  8. 7first ← max(L - max(-D, 0) - b, 1); last ← min(a, L - max(-D, 0) - 1)
  9. 8if D > 0 then return DEL at p + first of D bases
  10. 9else return INS before p + first of -D bases, the bases r[first..first - D)

Line L6 is the key step. The prefix starts at pp and the suffix ends at ee, so the read covers e−pe - p bases of the reference. If e−p>Le - p > L, the reference has DD more bases than the read, which is a deletion. If e−p<Le - p < L, the read has −D-D bases that are not in the reference, which is an insertion. D=0D = 0 is no event, and an insertion longer than ιmax⁡\iota_{\max} is rejected.

The parts can overlap on the read when the bases next to the breakpoint repeat, an effect called microhomology. Then the split point ii can be any value in the range of line L7, and every one gives the same event. The code takes the leftmost one, which is the left-aligned form of variant normalization. A range that leaves a part shorter than mm is rejected.

Example

The reference has 40 bases and the read 20:

ref=CAGAACCTGCTGTGACATAAACTAGCTGATATGTGTTCCC,r=ACCTGCTGTGACTAGCTGAT.\mathit{ref} = \texttt{CAGAACCTGCTGTGACATAAACTAGCTGATATGTGTTCCC}, \qquad r = \texttt{ACCTGCTGTGACTAGCTGAT}.

The prefix grows to a=12a = 12 bases, ACCTGCTGTGAC\texttt{ACCTGCTGTGAC}, which occurs once, at p=4p = 4. The suffix grows to b=10b = 10 bases, ACTAGCTGAT\texttt{ACTAGCTGAT}, which occurs once in [4,40)[4, 40) and ends at e=30e = 30. The read covers e−p=26e - p = 26 bases of the reference, so D=26−20=6D = 26 - 20 = 6: a deletion of 6 bases.

The two parts overlap by two bases, AC\texttt{AC}, so the split point can be 10, 11 or 12. At i=10i = 10 the read is ref[4:14]+ref[20:30]\mathit{ref}[4{:}14] + \mathit{ref}[20{:}30] and the deleted bases are ref[14:20]=ACATAA\mathit{ref}[14{:}20] = \texttt{ACATAA}. At i=12i = 12 the deleted bases are ref[16:22]=ATAAAC\mathit{ref}[16{:}22] = \texttt{ATAAAC}, the same event shifted by the repeat. The call is the leftmost form, a deletion of 6 bases at position 14.

On a simulated reference of 6000 bases, with a deletion of 40 bases at 2000 and an insertion of GATTACA\texttt{GATTACA} before 4000, 1500 pairs with reads of 60 bases and an insert size of 300±20300 \pm 20 were made from the sample. The mates that did not map as a whole near their anchor gave 31 reads to split. Nine of them gave no call, because one part was too short or occurred twice. The deletion got 14 reads and the insertion 8, each at its true normalized place, and no read gave another event.

Correctness

Pattern growth keeps the invariant that PP is the list of all places where r[0:a]r[0{:}a] occurs in the window, so it returns the longest prefix that occurs and all its places; the same holds for the suffix. For any ii in the range of line L7, r[0:i]r[0{:}i] is a prefix of the first part and r[i+ι:L]r[i + \iota{:}L] is a suffix of the second part, so the read is exactly the reference with the stated deletion or insertion, by the arithmetic of line L6. Conversely, every split with i≤ai \le a and the suffix inside the second part is in that range, and they all give the same event up to a shift in a repeat. The proofs are in proofs/correctness.md, and the tests check the calls against a search over every split of every read in small random cases.

These are theorems for the model of two exact parts. As a detector of structural variants the method is a heuristic: a part can match by chance, a read with a sequencing error in the wrong place gives no call, and an event that is not a deletion or a short insertion is outside the model.

Proof: A unique prefix and suffix match give the event D = e - p - L, and the split range holds every split that explains the readfull

Setting. The reference is ref\mathit{ref}, the read is rr of length LL, and the window is [lo,hi)[lo, hi) with hi≤∣ref∣hi \le |\mathit{ref}|. For strings, x[i:j]x[i{:}j] is the part from position ii up to, but not including, jj. A string ww occurs at xx in the window when lo≤xlo \le x, x+∣w∣≤hix + |w| \le hi and ref[x:x+∣w∣]=w\mathit{ref}[x{:}x + |w|] = w.

Lemma 1 (prefix growth). grow_prefix returns the largest a≤La \le L such that r[0:a]r[0{:}a] occurs in the window, and the list PP of all positions where it occurs. If r[0]r[0] does not occur, it returns a=0a = 0.

Proof. Line L1 sets PP to the positions xx in the window with ref[x]=r[0]\mathit{ref}[x] = r[0], which are the occurrences of r[0:1]r[0{:}1]. The loop at line L2 keeps the invariant that PP is the list of the occurrences of r[0:a]r[0{:}a]. A position xx is an occurrence of r[0:a+1]r[0{:}a+1] exactly when it is an occurrence of r[0:a]r[0{:}a], x+a<hix + a < hi and ref[x+a]=r[a]\mathit{ref}[x + a] = r[a], which is the filter of the loop. So if the filter keeps some positions, the invariant holds for a+1a + 1. If it keeps none, r[0:a+1]r[0{:}a+1] does not occur, and then no longer prefix occurs either, because each occurrence of a longer prefix is an occurrence of r[0:a+1]r[0{:}a+1]. So the returned aa is the largest. □\square

grow_suffix is the same with the read and the window read from the right end, and returns the largest bb such that r[L−b:L]r[L - b{:}L] occurs in the window [p,hi)[p, hi), with the list QQ of the end positions ee of its occurrences. Line L4 searches only at or after pp, so the second part cannot start to the left of the first.

Lemma 2 (the event). Let r[0:a]r[0{:}a] occur at pp and r[L−b:L]r[L - b{:}L] end at ee, and let D=e−p−LD = e - p - L (line L6) and ι=max⁡(−D,0)\iota = \max(-D, 0). Let ii be an integer with max⁡(L−ι−b,1)≤i≤min⁡(a,L−ι−1)\max(L - \iota - b, 1) \le i \le \min(a, L - \iota - 1), the range of line L7. Then:

  • if D>0D > 0, r=ref[p:p+i]+ref[p+i+D:e]r = \mathit{ref}[p{:}p + i] + \mathit{ref}[p + i + D{:}e], so rr is the sequence of ref[p:e]\mathit{ref}[p{:}e] with the DD bases ref[p+i:p+i+D]\mathit{ref}[p + i{:}p + i + D] deleted;
  • if D<0D < 0, r=ref[p:p+i]+r[i:i+ι]+ref[p+i:e]r = \mathit{ref}[p{:}p + i] + r[i{:}i + \iota] + \mathit{ref}[p + i{:}e], so rr is ref[p:e]\mathit{ref}[p{:}e] with the ι\iota bases r[i:i+ι]r[i{:}i + \iota] inserted before ref[p+i]\mathit{ref}[p + i].

Proof. Since i≤ai \le a, the prefix r[0:i]r[0{:}i] is a prefix of r[0:a]r[0{:}a], so r[0:i]=ref[p:p+i]r[0{:}i] = \mathit{ref}[p{:}p + i]. Since L−(i+ι)≤bL - (i + \iota) \le b, the suffix r[i+ι:L]r[i + \iota{:}L] is a suffix of r[L−b:L]r[L - b{:}L], so r[i+ι:L]=ref[e−(L−i−ι):e]r[i + \iota{:}L] = \mathit{ref}[e - (L - i - \iota){:}e]. If D>0D > 0, then ι=0\iota = 0 and e−(L−i)=p+D+ie - (L - i) = p + D + i, which is the first claim. If D<0D < 0, then ι=−D\iota = -D and e−(L−i−ι)=p+D+i+ι=p+ie - (L - i - \iota) = p + D + i + \iota = p + i, so the suffix is ref[p+i:e]\mathit{ref}[p + i{:}e], and the middle r[i:i+ι]r[i{:}i + \iota] is left over, which is the second claim. The bounds 1≤i≤L−ι−11 \le i \le L - \iota - 1 make both parts non-empty. □\square

Lemma 3 (the range is complete). Every split point ii for which the first part r[0:i]r[0{:}i] is ref[p:p+i]\mathit{ref}[p{:}p + i] and the second part r[i+ι:L]r[i + \iota{:}L] ends at ee, with both parts non-empty, is in the range of line L7.

Proof. The second part starts at or after p+ip + i and ends at e≤hie \le hi, so p+i≤hip + i \le hi, and r[0:i]r[0{:}i] occurs at pp in the window. By the maximality of aa in Lemma 1, i≤ai \le a. If r[i+ι:L]r[i + \iota{:}L] ends at ee, then it is a suffix of rr that occurs in [p,hi)[p, hi), and by the lemma for grow_suffix, L−i−ι≤bL - i - \iota \le b. Non-empty parts give i≥1i \ge 1 and i≤L−ι−1i \le L - \iota - 1. □\square

When the range has more than one split point, the bases next to the breakpoint repeat (microhomology), and every point gives the same sequence of the sample, by Lemma 2. The event is then not fixed at one place by the read, and the code reports the leftmost point that leaves both parts at least mmin⁡m_{\min} long, as VCF normalization does for indels.

Theorem. If split_read returns ("DEL", qq, DD, "") then the read equals ref[p:e]\mathit{ref}[p{:}e] with ref[q:q+D]\mathit{ref}[q{:}q + D] deleted. If it returns ("INS", qq, ι\iota, ww) then the read equals ref[p:e]\mathit{ref}[p{:}e] with ww inserted before ref[q]\mathit{ref}[q]. In both cases both parts have at least mmin⁡m_{\min} bases, and the prefix r[0:a]r[0{:}a] occurs once in the window and the suffix r[L−b:L]r[L - b{:}L] occurs once in [p,hi)[p, hi).

Proof. Line L3 returns nothing unless the prefix occurs exactly once, at pp, and line L5 returns nothing unless the suffix occurs exactly once, ending at ee. Line L6 returns nothing for D=0D = 0 (the whole read would then match ref[p:e]\mathit{ref}[p{:}e] as one piece, or not at all) and for an insertion longer than the limit. Line L7 takes the smallest ii of the range of Lemma 2 that is at least mmin⁡m_{\min} and leaves a second part of at least mmin⁡m_{\min}, and returns nothing if there is none. Lines L8 and L9 return q=p+iq = p + i with the event of Lemma 2. □\square

What the theorem does not say. Uniqueness is uniqueness of the longest exact matches in the window. If the read has a sequencing error in the first aa bases, aa stops early and the call can be wrong or missing; the method has no mismatch model. A unique match can still be a wrong one, if the true place of the read is outside the window. These are limits of the method, which the page lists.

Cost. Each step of the growth filters the current list of occurrences, so the prefix growth costs O(w+∑t∣Pt∣)O(w + \sum_t |P_t|), where w=hi−low = hi - lo and PtP_t is the list after step tt. This is O(wa)O(w a) in the worst case, and close to O(w)O(w) when the list shrinks to one position after a few bases, as it does in a random sequence. The suffix growth is the same, so one read costs O(wL)O(w L) in the worst case.

Complexity

  • Time. Line L1 scans the window in O(W)O(W) for W=hi−loW = hi - lo. Each step of line L2 filters the list PP, so the growth costs O(W+a∣P1∣)O(W + a |P_1|), where P1P_1 is the first list; in the worst case, as for a read of one repeated base, this is O(WL)O(W L). In random sequence, the list shrinks by a factor of about 4 at each step, and the cost is close to O(W)O(W).
  • Space. O(W)O(W) for the lists.
  • For a sample. Only reads whose mate maps and that do not map as a whole are split, so the work grows with the number of such reads times the window length.

Properties

  • Base resolution. The call gives the exact breakpoint and, for an insertion, the inserted bases.
  • Exact matching. The two parts must match without errors in this version. Pindel and later tools allow a few mismatches.
  • Short events only for insertions. Both parts and the insertion must fit in one read, so an insertion can have at most L−2mL - 2m bases.
  • Unique parts. A part that occurs twice in the window gives no call, so repeats near the breakpoint hide the event.
  • Normalized output. The leftmost split point gives the same call for every read of one event, so the reads can be counted together.

Variants and improvements

  • Mismatches. Allow a few mismatches in each part, at the cost of more candidate places.
  • Other types. With the second part searched on the other strand, or before the first part, the same method finds inversions and tandem duplications. With a window on another chromosome, it finds translocations.
  • Large insertions. Pindel joins the two ends of a long insertion from two groups of reads, one for each breakpoint.
  • Split alignments from the mapper. Mappers such as BWA and minimap2 report a read that aligns in two pieces as a primary and a supplementary alignment. Many callers start from these and skip the search.
  • Refinement of other signals. DELLY finds a cluster with discordant pairs first and then uses split reads near it to find the breakpoint to the base.
  • Long reads. With long reads, one read often crosses a whole event, and the split alignment shows larger and more complex events.

When to use it

Use it to find the exact breakpoints of deletions and of insertions shorter than a read, or to refine the place of events found by read pairs or read depth. It fills a gap in size between the small indels that a normal alignment finds and the large events that read pairs find. It is weak in repeats, for long insertions with short reads, and in regions where the mates do not map.

Pitfalls

  • Repeats at the breakpoint. A part that occurs twice gives no call, and a part of 10 or 15 bases can match by chance in a long window. Set the minimum length of a part with the window length in mind.
  • Microhomology. Without normalization, reads of one event give calls at different places in the repeat and look like several events.
  • Sequencing errors. An error near the breakpoint shortens one part and can move or lose the call.
  • The strand of the read. The unmapped mate must be turned to the strand of the reference before the search; with the forward-reverse layout of most libraries, that is its reverse complement.
  • A wrong window. A wrong insert size, or an anchor in a repeat, puts the window in the wrong place.

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)
split_read_method.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/split-read-method/. The authors are listed in prov/TDWFBV.jsonl.
"""Split-read calls of deletions and short insertions, in the style of Pindel.

The input is a reference string ref, a read r that did not map as a whole
(already turned to the forward strand of ref), and a window [lo, hi) of ref
where the read must lie. In a paired library the window comes from the mapped
mate (the anchor): it starts at the anchor and is about two insert sizes long.

The method grows the read from both ends by pattern growth:

1. the longest prefix r[:a] that occurs in the window, with its set of
   occurrences, grown one base at a time;
2. the longest suffix r[L-b:] that occurs in the window at or after the
   start p of the prefix, grown the same way from the right end.

Each part must occur once. If the prefix starts at p and the suffix ends at
e, the read is ref[p:p+i] + ref[e-(L-i):e] for a deletion of D = e - p - L
bases, and the same holds with D < 0 for an insertion of -D bases. The split
point i can move over a range when the bases next to the breakpoint repeat
(microhomology); the call takes the leftmost i, as in VCF normalization.

What this code leaves out compared with Pindel: mismatches in the two parts,
the search of the reverse strand and of the other mate, large insertions
whose two ends come from two reads, inversions and tandem duplications, the
grouping of reads of one event across samples, and the quality scores.
"""

from __future__ import annotations

from typing import List, Optional, Tuple


def grow_prefix(ref: str, r: str, lo: int, hi: int) -> Tuple[int, List[int]]:
    """The longest a such that r[:a] occurs in ref[lo:hi], and the start positions of r[:a]."""
    occ = [x for x in range(lo, hi) if ref[x] == r[0]] if r else []  # @line L1
    if not occ:
        return 0, []
    a = 1
    while a < len(r):  # @line L2
        nxt = [x for x in occ if x + a < hi and ref[x + a] == r[a]]
        if not nxt:
            break
        occ, a = nxt, a + 1
    return a, occ


def grow_suffix(ref: str, r: str, lo: int, hi: int) -> Tuple[int, List[int]]:
    """The longest b such that r[L-b:] occurs in ref[lo:hi], and the end positions (exclusive)."""
    L = len(r)
    occ = [x + 1 for x in range(lo, hi) if ref[x] == r[-1]] if r else []
    if not occ:
        return 0, []
    b = 1
    while b < L:
        nxt = [e for e in occ if e - b - 1 >= lo and ref[e - b - 1] == r[L - b - 1]]
        if not nxt:
            break
        occ, b = nxt, b + 1
    return b, occ


def split_read(ref: str, r: str, lo: int, hi: int, min_part: int = 10,
               max_ins: int = 20) -> Optional[Tuple[str, int, int, str]]:
    """Return (kind, pos, size, inserted) or None.

    kind is "DEL" or "INS". For a DEL, ref[pos:pos+size] is deleted. For an
    INS, the bases inserted are put before ref[pos]. inserted is the inserted
    sequence ("" for a DEL). None means no unique split with both parts of at
    least min_part bases, or that the read maps as a whole.
    """
    L = len(r)
    hi = min(hi, len(ref))
    a, P = grow_prefix(ref, r, lo, hi)
    if a == L or a < min_part or len(P) != 1:  # @line L3
        return None
    p = P[0]
    b, Q = grow_suffix(ref, r, p, hi)  # @line L4
    if b < min_part or len(Q) != 1:  # @line L5
        return None
    e = Q[0]
    D = e - p - L  # @line L6
    if D == 0 or -D > max_ins:
        return None
    ins = max(-D, 0)
    # The split points i with r[:i] in the prefix and the rest in the suffix.
    first, last = max(L - ins - b, 1), min(a, L - ins - 1)  # @line L7
    if max(first, min_part) > min(last, L - ins - min_part):
        return None
    if D > 0:
        return "DEL", p + first, D, ""  # @line L8
    return "INS", p + first, ins, r[first:first + ins]  # @line L9
test_split_read_method.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/split-read-method/. The authors are listed in prov/TDWFBV.jsonl.

import random
from collections import Counter

from bioseq import random_dna, revcomp
from split_read_method import grow_prefix, grow_suffix, split_read

EXAMPLE_REF = "CAGAACCTGCTGTGACATAAACTAGCTGATATGTGTTCCC"
EXAMPLE_READ = "ACCTGCTGTGACTAGCTGAT"


def normalize(ref, event):
    """Shift a DEL or INS to the left as far as the reference allows (VCF left alignment)."""
    kind, pos, size, ins = event
    if kind == "DEL":
        while pos > 0 and ref[pos - 1] == ref[pos + size - 1]:
            pos -= 1
        return kind, pos, size, ""
    while pos > 0 and ref[pos - 1] == ins[-1]:
        ins = ref[pos - 1] + ins[:-1]
        pos -= 1
    return kind, pos, size, ins


def brute_events(ref, r, lo, hi, min_part, max_ins, max_del):
    """Every DEL or INS that explains r as two exact parts of at least min_part bases in ref[lo:hi]."""
    L, out = len(r), set()
    for p in range(lo, hi):
        for i in range(min_part, L - min_part + 1):
            if ref[p:p + i] != r[:i]:
                break
            for D in range(1, max_del + 1):
                q = p + i + D
                if q + L - i <= hi and ref[q:q + L - i] == r[i:]:
                    out.add(normalize(ref, ("DEL", p + i, D, "")))
            for I in range(1, max_ins + 1):
                rest = L - i - I
                if rest >= min_part and p + i + rest <= hi and ref[p + i:p + i + rest] == r[i + I:]:
                    out.add(normalize(ref, ("INS", p + i, I, r[i:i + I])))
    return out


def longest_prefix_naive(ref, r, lo, hi):
    a = 0
    while a < len(r) and r[:a + 1] in ref[lo:hi]:
        a += 1
    return a


def test_grow_against_naive_search():
    rng = random.Random(1)
    for _ in range(200):
        ref = random_dna(rng, rng.randint(1, 30))
        r = random_dna(rng, rng.randint(1, 8))
        lo = rng.randrange(len(ref))
        hi = rng.randint(lo + 1, len(ref))
        a, P = grow_prefix(ref, r, lo, hi)
        assert a == longest_prefix_naive(ref, r, lo, hi)
        assert P == [x for x in range(lo, hi - a + 1) if ref[x:x + a] == r[:a]] or a == 0
        b, Q = grow_suffix(ref, r, lo, hi)
        rr = r[::-1]
        assert b == longest_prefix_naive(ref[::-1], rr, len(ref) - hi, len(ref) - lo)
        if b:
            assert Q == [e for e in range(lo + b, hi + 1) if ref[e - b:e] == r[len(r) - b:]]


def test_example_with_microhomology():
    a, P = grow_prefix(EXAMPLE_REF, EXAMPLE_READ, 0, 40)
    assert (a, P) == (12, [4])
    b, Q = grow_suffix(EXAMPLE_REF, EXAMPLE_READ, 4, 40)
    assert (b, Q) == (10, [30])
    # D = e - p - L = 30 - 4 - 20 = 6. The split point can be 10, 11 or 12 because "AC"
    # repeats; the leftmost gives the deletion of ref[14:20].
    assert split_read(EXAMPLE_REF, EXAMPLE_READ, 0, 40, min_part=5) == ("DEL", 14, 6, "")
    for s in (14, 15, 16):
        assert EXAMPLE_REF[:s] + EXAMPLE_REF[s + 6:] == EXAMPLE_REF[:14] + EXAMPLE_REF[20:]


def test_whole_match_and_too_short_parts():
    ref = EXAMPLE_REF
    assert split_read(ref, ref[3:23], 0, 40, min_part=5) is None
    # The read leaves only 3 bases after the deletion, fewer than min_part.
    r = ref[4:14] + ref[20:30]
    assert split_read(ref, r[:13], 0, 40, min_part=5) is None


def test_against_brute_force():
    rng = random.Random(7)
    checked = 0
    for trial in range(150):
        ref = random_dna(rng, 90)
        L = rng.randint(16, 30)
        kind = rng.choice(["DEL", "INS", "NONE", "MISMATCH"])
        s = rng.randint(20, 50)
        if kind == "DEL":
            alt = ref[:s] + ref[s + rng.randint(1, 25):]
        elif kind == "INS":
            alt = ref[:s] + random_dna(rng, rng.randint(1, 6)) + ref[s:]
        else:
            alt = ref
        start = rng.randint(max(0, s - L + 5), s - 5)
        r = alt[start:start + L]
        if kind == "MISMATCH":
            k = rng.randrange(L)
            r = r[:k] + ("A" if r[k] != "A" else "C") + r[k + 1:]
        call = split_read(ref, r, 0, len(ref), min_part=5, max_ins=8)
        truth = brute_events(ref, r, 0, len(ref), 5, 8, 60)
        if call is not None:
            assert normalize(ref, call) in truth
            ev_kind, pos, size, ins = call
            if ev_kind == "DEL":
                assert r in ref[:pos] + ref[pos + size:]
            else:
                assert r in ref[:pos] + ins + ref[pos:]
        if len(truth) == 1 and call is not None:
            checked += 1
        if len(truth) == 0:
            assert call is None
    assert checked >= 50


def test_simulated_sample():
    rng = random.Random(2009)
    ref = random_dna(rng, 6000)
    # The sample has the deletion of ref[2000:2040] and the insertion of GATTACA before ref[4000].
    sample = ref[:2000] + ref[2040:4000] + "GATTACA" + ref[4000:]
    truth = {normalize(ref, ("DEL", 2000, 40, "")), normalize(ref, ("INS", 4000, 7, "GATTACA"))}

    def to_ref(x):
        if x < 2000:
            return x
        if x < 3960:
            return x + 40
        if x < 3967:
            return None
        return x + 33

    L, mu, sigma = 60, 300, 20
    events = Counter()
    for _ in range(1500):
        f = round(rng.gauss(mu, sigma))
        s = rng.randrange(len(sample) - f)
        anchor = to_ref(s)
        if anchor is None or to_ref(s + L - 1) is None or to_ref(s + L - 1) - anchor != L - 1:
            continue
        mate = revcomp(sample[s + f - L:s + f])  # as sequenced, on the reverse strand
        r = revcomp(mate)
        lo, hi = anchor, anchor + 2 * mu + 100
        if r in ref[lo:hi]:
            continue
        call = split_read(ref, r, lo, hi, min_part=10)
        if call is not None:
            events[normalize(ref, call)] += 1
    top = [e for e, n in events.items() if n >= 3]
    assert set(top) == truth
    assert sum(events.values()) - sum(events[e] for e in truth) <= 1

History

Ye, Schulz, Long, Apweiler and Ning (2009) introduced Pindel. It took the read pairs in which one mate mapped and the other did not, and searched for the two ends of the unmapped read near the anchor by pattern growth, which found deletions and medium sized insertions to the base from short Illumina reads. DELLY (Rausch et al., 2012) combined read pairs with split reads to refine the breakpoints. Later callers use the split alignments that the mappers report, and long reads made split alignments the main signal for many classes of events.

References

  1. Kai Ye, Marcel H. Schulz, Quan Long, Rolf Apweiler and Zemin Ning, Pindel, a pattern growth approach to detect break points of large deletions and medium sized insertions from paired-end short reads, Bioinformatics 25(21), 2009, the sections on the anchor points, the pattern growth of the two ends of the unmapped read and the calls of deletions and insertions
  2. Tobias Rausch, Thomas Zichner, Andreas Schlattl and others, DELLY, structural variant discovery by integrated paired-end and split-read analysis, Bioinformatics 28(18), 2012, the sections on the split-read refinement of the breakpoints of paired-end clusters
  3. Can Alkan, Bradley P. Coe and Evan E. Eichler, Genome structural variation discovery and genotyping, Nature Reviews Genetics 12(5), 2011, the section on split-read methods and their place among the other signals

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