bio-agent-trajectories / code /vera /breakpoints.py
ryan-superman's picture
Publish trajectories and metrics (BMB content gated)
df22bef verified
Raw History Blame Contribute Delete
11.1 kB
#!/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