File size: 11,083 Bytes
1cb676d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e304570
 
 
 
 
 
 
 
 
 
 
 
 
 
2fbd9d0
 
 
 
 
 
 
 
 
 
e304570
2fbd9d0
e304570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fbd9d0
 
e304570
 
 
 
 
 
 
 
2fbd9d0
 
 
 
 
 
e304570
 
 
2fbd9d0
 
 
 
df22bef
 
e304570
 
 
 
 
 
1cb676d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env python3
"""Base-resolution breakpoint detection from an alignment.

A double-strand break leaves two independent signatures in aligned reads:

* *fragment ends* -- reads from the cut molecule terminate exactly at the break, so
  alignment start and end positions pile up there;
* *clip boundaries* -- reads that read through a repaired or chimeric junction align
  partially and are soft-clipped at the break.

Both are measurements. They are reported separately because agreeing on a position is
strong evidence, whereas one signature alone can be produced by ordinary coverage
structure (a capture boundary, a repeat edge, an adapter artefact).

This is deliberately generic: the same statistic locates Cas9 cut sites, viral
integration sites, fusion junctions and structural-variant breakpoints.
"""

from __future__ import annotations

import re
import subprocess
from bisect import bisect_left, bisect_right
from collections import Counter
from pathlib import Path

CIGAR_RE = re.compile(r"(\d+)([MIDNSHP=X])")
# Operations that advance along the reference; used to find where an alignment ends.
REF_CONSUMING = frozenset("MDN=X")
MIN_CLIP = 5  # shorter clips are usually sequencing error, not a junction
POOL = 50     # candidates ranked before truncating, so `k` cannot change the ranking


def scan_sam(lines, *, min_mapq: int = 20, min_clip: int = MIN_CLIP) -> dict:
    """Accumulate breakpoint evidence from SAM records.

    Args:
        lines: Iterable of SAM text lines; headers are ignored.
        min_mapq: Reads below this are dropped, because a breakpoint claim made from
            multi-mapping reads is not a claim about a location.
        min_clip: Minimum soft-clip length counted as a junction.

    Returns:
        Counters keyed by ``(chrom, position)``: ``left_end`` and ``right_end`` for
        alignment termini, ``clip`` for soft-clip boundaries, plus ``n_reads`` scanned.
    """
    left_end: Counter = Counter()   # 1-based position of an alignment's first base
    right_end: Counter = Counter()  # 1-based position of an alignment's last base
    clip: Counter = Counter()
    n = 0
    for line in lines:
        if not line or line[0] == "@":
            continue
        f = line.rstrip("\n").split("\t")
        if len(f) < 6:
            continue
        flag = int(f[1])
        if flag & 0x904:            # unmapped, secondary or supplementary
            continue
        chrom, pos, mapq, cigar = f[2], int(f[3]), int(f[4]), f[5]
        if chrom == "*" or mapq < min_mapq or cigar == "*":
            continue
        n += 1
        ops = CIGAR_RE.findall(cigar)
        span = sum(int(ln) for ln, op in ops if op in REF_CONSUMING)
        end = pos + span - 1
        left_end[(chrom, pos)] += 1
        right_end[(chrom, end)] += 1
        if ops and ops[0][1] == "S" and int(ops[0][0]) >= min_clip:
            clip[(chrom, pos)] += 1
        if ops and ops[-1][1] == "S" and int(ops[-1][0]) >= min_clip:
            clip[(chrom, end)] += 1
    return {"left_end": left_end, "right_end": right_end, "clip": clip, "n_reads": n}


def top_positions(counter: Counter, k: int = 20) -> list[dict]:
    """The `k` most-supported positions, as JSON-ready records."""
    return [{"chrom": c, "pos": p, "reads": n}
            for (c, p), n in counter.most_common(k)]


def consensus(ev: dict, k: int = 20, window: int = 10) -> list[dict]:
    """Positions supported by more than one signature, at base resolution.

    A cut site should show reads ending on its left and reads beginning on its right, so
    a candidate is scored by the summed support of every signature within `window` bases.
    Requiring agreement is what separates a break from a coverage edge.

    Clusters are seeded in descending order of support *at a single base*, so the
    position reported is the cluster's peak rather than any base near it. Seeding from
    each signature's own ranking instead put the reported position up to `window` bases
    off the true break, which is the difference between a right and a wrong answer when
    a coordinate is graded to a few base pairs.
    """
    by_chrom: dict[str, dict[str, list]] = {}
    for name in ("left_end", "right_end", "clip"):
        for (c, p), n in ev[name].items():
            by_chrom.setdefault(c, {}).setdefault(name, []).append((p, n))
    for chrom in by_chrom:
        for name in by_chrom[chrom]:
            by_chrom[chrom][name].sort()

    def near(chrom: str, pos: int, name: str) -> int:
        """Support for `name` within `window` bases of `pos`."""
        entries = by_chrom.get(chrom, {}).get(name)
        if not entries:
            return 0
        lo = bisect_left(entries, (pos - window, 0))
        hi = bisect_right(entries, (pos + window, 1 << 62))
        return sum(n for _, n in entries[lo:hi])

    peak: Counter = Counter()
    for name in ("left_end", "right_end", "clip"):
        peak.update(ev[name])

    # Collect a fixed pool regardless of `k`, then rank, then truncate. Collecting only
    # `k` and ranking those makes the runner-up -- and therefore the reported margin --
    # depend on how many results the caller asked for, which is not a property of the
    # data.
    pool = max(k, POOL)
    kept: list[dict] = []
    for (c, p), _ in peak.most_common():
        if any(c == s["chrom"] and abs(p - s["pos"]) <= window for s in kept):
            continue
        counts = {name: near(c, p, name) for name in ("left_end", "right_end", "clip")}
        kept.append({"chrom": c, "pos": p,
                     "signatures": sum(1 for v in counts.values() if v > 0),
                     "total": sum(counts.values()), **counts})
        if len(kept) >= pool:
            break
    kept.sort(key=lambda d: (-d["signatures"], -d["total"]))
    return kept[:k]


# The floor this tool already declares. Two conditions, not one: `consensus` keeps only
# positions "supported by more than one signature", because agreement is what separates a
# break from a coverage edge, and the blind spot below calls anything under 20 reads a
# candidate rather than a location. `alternatives` is counted against BOTH, so uniqueness
# means "no rival clears the bar this tool itself set".
#
# Counting support alone was wrong and a test caught it. A library with one real break and
# uniform read length piles 40 read starts at `pos - readlen + 1` and 40 read ends at
# `pos + readlen - 1`; each clears 20 reads, and each is a single signature -- a coverage
# edge, which is precisely what the agreement rule exists to reject. Scoring them as
# rivals made a clean, unambiguous cut site non-unique.
SUPPORT_FLOOR = 20
MIN_SIGNATURES = 2

# A rival has to be an alternative *event*, not another view of the same one. Simulation
# missed this because it placed distractors 5 kb apart; the real Cas9 library does not. One
# cut site there produces a peak at chr3:46,373,178 and a shoulder of positions carrying
# three signatures and hundreds of reads within ~130 bp of it, all of them the same break.
# Counting those as rivals made the caller abstain on an answer it had ranked first.
#
# No single junction can produce evidence further away than one read length, so the read
# span the scan actually observed is the independence window. It is measured, not chosen.
DEFAULT_INDEPENDENCE = 150


def competence_for(found: list[dict], independence: int = DEFAULT_INDEPENDENCE):
    """State what a ranked breakpoint list can and cannot establish.

    Factored out of the `biotool breakpoints` command so the shipped rule is the one under
    test. A breakpoint is a claim about a single base, so the margin that matters is how
    far the top candidate stands above the second, not how much total support it has.

    `alternatives` counts rivals that clear this tool's own floor on both axes,
    `MIN_SIGNATURES` and `SUPPORT_FLOOR`. Measured on the variant caller first: a large
    margin arises both when the true answer dominates and when a distractor does, so
    separation between the top two is not the absence of a rival. Generalising the count
    here showed the floor a tool declares can be multi-dimensional, and using only part of
    it invents rivals that the tool's own ranking has already dismissed.

    Args:
        found: Ranked output of `consensus`, best first.
        independence: Minimum distance at which a candidate counts as a separate event.
            Pass the observed read span; the default is a typical short read.

    Returns:
        A `Competence` describing the list.
    """
    from .competence import bounded

    top = found[0]["total"] if found else 0
    runner_up = found[1]["total"] if len(found) > 1 else 0
    lead = found[0] if found else None

    def independent(f: dict) -> bool:
        """Whether `f` describes a different event from the top candidate."""
        return (lead is not None and (f["chrom"] != lead["chrom"]
                                      or abs(f["pos"] - lead["pos"]) > independence))
    return bounded(
        confidence=min(1.0, top / 100.0),
        margin=((top - runner_up) / top) if top else 0.0,
        alternatives=sum(1 for f in found
                         if f["total"] >= SUPPORT_FLOOR
                         and f["signatures"] >= MIN_SIGNATURES
                         and independent(f)),
        ties=sum(1 for f in found[1:]
                 if top and (top - f["total"]) / top < 0.05 and independent(f)),
        blind_spots=((f"fewer than {SUPPORT_FLOOR} reads support the top position; it is "
                      "a candidate, not a location",) if top < SUPPORT_FLOOR else ()),
        remedy="scan without --region, or sequence deeper at the locus",
    )


def scan_bam(bam: Path, *, samtools: str | None = None, region: str | None = None,
             min_mapq: int = 20, min_clip: int = MIN_CLIP) -> dict:
    """Accumulate breakpoint evidence from an indexed BAM.

    Args:
        bam: Sorted, indexed alignment.
        samtools: Binary to use; located if omitted.
        region: Restrict to `chr:start-end`. Omit to scan the whole genome, which is
            what lets the tool find a locus the agent has not already guessed.
        min_mapq: See `scan_sam`.
        min_clip: See `scan_sam`.

    Raises:
        RuntimeError: If samtools is missing or the scan fails.
    """
    from . import references  # local import keeps this module importable standalone

    binary = samtools or references.find_binary("samtools")
    if binary is None:
        raise RuntimeError("samtools is not installed")
    cmd = [binary, "view", str(bam)] + ([region] if region else [])
    with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                          text=True, errors="replace", bufsize=1 << 20) as proc:
        evidence = scan_sam(proc.stdout, min_mapq=min_mapq, min_clip=min_clip)
        proc.stdout.close()
        err = proc.stderr.read()
    if proc.returncode not in (0, None) and not evidence["n_reads"]:
        raise RuntimeError(f"samtools view failed: {err[-300:]}")
    return evidence