ryan-superman's picture
Publish trajectories and metrics (BMB content gated)
df22bef verified
Raw History Blame Contribute Delete
9.53 kB
"""Calibrated variant evidence from an alignment.
The Cas9 problem showed an agent mis-implementing a statistic. This is the other half of
the same failure: an agent that implements the statistic correctly and cannot tell signal
from noise. On the TP53 problem the baseline ran bwa, `samtools mpileup` and `bcftools`,
found a substitution supported by **two reads**, annotated it correctly as
`NM_000546.6:c.128T>A (p.Leu43Ter)` and reported codon 43. Mean depth over TP53 in that
library is 21.5, so two reads is an allele fraction near the error floor. Ten positions in
the same gene carry a fraction above 0.15 and three are effectively homozygous.
Its annotation machinery was right. Its *selection* was not, and nothing in the pipeline
told it that two reads is not evidence.
So this reports depth and allele fraction for every candidate, ranks by support rather
than by discovery order, and says in the competence field when the depth is too low to
separate a variant from sequencing error. Substitutions and indels are ranked together:
a caller that reports only substitutions cannot see a frameshift, which is the most
common way a coding sequence is truncated.
The parsing is the part worth testing. An mpileup read-base column encodes read starts as
`^` plus a mapping-quality character, read ends as `$`, and indels as `+n<seq>` / `-n<seq>`
whose length is written in decimal inside the field. Miscounting any of them shifts the
allele fraction silently, which is the same class of defect as an off-by-one in a CIGAR.
"""
from __future__ import annotations
import re
import subprocess
from collections import Counter
from pathlib import Path
# `^` is followed by one character encoding mapping quality, which is NOT a base call.
_READ_START = re.compile(r"\^.")
# An indel is written as +/- then a decimal length then that many sequence characters.
_INDEL = re.compile(r"([+-])(\d+)")
_BASES = "ACGTN"
def parse_pileup_bases(field: str) -> dict:
"""Count what an mpileup read-base column actually says.
Args:
field: The read-base column, e.g. ``.,.$..^F.+2AG,`` .
Returns:
``{"ref": int, "alt": Counter, "indels": Counter, "insertions": int,
"deletions": int, "deleted": int}`` where `ref` counts bases matching the
reference, `alt` counts substituted bases by uppercase letter, `indels` counts
indel alleles written ``+SEQ`` / ``-SEQ``, and `deleted` counts positions covered
by a deletion called on an earlier line (`*`, or `#` on the reverse strand).
The indel sequence is upper-cased, because mpileup writes it in lower case for a
read on the reverse strand and the two are the same allele.
"""
text = _READ_START.sub("", field or "")
ref = 0
alt: Counter = Counter()
indels: Counter = Counter()
insertions = deletions = deleted = 0
i = 0
while i < len(text):
ch = text[i]
match = _INDEL.match(text, i)
if match:
length = int(match.group(2))
seq = text[match.end():match.end() + length].upper()
indels[match.group(1) + seq] += 1
if match.group(1) == "+":
insertions += 1
else:
deletions += 1
i = match.end() + length # skip the indel sequence itself
continue
if ch in ".,":
ref += 1
elif ch.upper() in _BASES:
alt[ch.upper()] += 1
elif ch in "*#":
deleted += 1
# '$' and anything else carry no base call
i += 1
return {"ref": ref, "alt": alt, "indels": indels, "insertions": insertions,
"deletions": deletions, "deleted": deleted}
def call_variants(lines, *, min_depth: int = 10, min_af: float = 0.2) -> list[dict]:
"""Rank non-reference alleles by how well the reads support them.
Substitutions and indels compete on one scale. An earlier version ranked
substitutions only and skipped any site whose substitution counter was empty, so a
frameshift could not be reported at all, whatever its support -- a blind spot in a
tool whose stated job is finding truncating mutations, since an indel is the most
common way a coding sequence is truncated.
Args:
lines: Iterable of mpileup text lines.
min_depth: Positions shallower than this are dropped -- not reported as
negative, because shallow coverage is absence of evidence.
min_af: Minimum non-reference fraction. Below this a call is not distinguishable
from sequencing error at ordinary depths.
Returns:
Records sorted by allele fraction then depth, each with `chrom`, `pos`, `ref`,
`alt`, `kind`, `depth`, `alt_reads`, `af`. `alt` is a base for a substitution and
``+SEQ`` / ``-SEQ`` for an indel, which mpileup anchors on the base *before* the
event, so the reported `pos` precedes an inserted or deleted stretch.
"""
out = []
for line in lines:
f = line.rstrip("\n").split("\t")
if len(f) < 5:
continue
try:
pos, depth = int(f[1]), int(f[3])
except ValueError:
continue
if depth < min_depth:
continue
counts = parse_pileup_bases(f[4])
# Depth is recomputed from the bases actually parsed. mpileup's own column counts
# reads spanning the site, including ones whose base is a deletion placeholder,
# so dividing by it inflates or deflates the fraction depending on the site.
# Indel-carrying reads are deliberately NOT added here: each already contributed
# its anchor base to `ref` or `alt`, so counting the indel again would inflate
# the denominator and quietly halve every indel's fraction.
observed = counts["ref"] + sum(counts["alt"].values()) + counts["deleted"]
candidates = Counter(counts["alt"])
candidates.update(counts["indels"])
if not candidates or observed < min_depth:
continue
# Ties are broken on the allele string rather than left to dictionary order, so
# two runs over the same pileup rank identically.
base, n = max(candidates.items(), key=lambda kv: (kv[1], kv[0]))
af = n / observed
if af < min_af:
continue
kind = ("insertion" if base.startswith("+") else
"deletion" if base.startswith("-") else "snv")
out.append({"chrom": f[0], "pos": pos, "ref": f[2].upper(), "alt": base,
"kind": kind,
"depth": observed, "alt_reads": n, "af": round(af, 3),
"insertions": counts["insertions"],
"deletions": counts["deletions"]})
out.sort(key=lambda d: (-d["af"], -d["depth"]))
return out
def competence_for(calls: list[dict], median_depth: int):
"""State what a ranked candidate list can and cannot establish.
Factored out of the `biotool variants` command so the shipped rule is the one under
test: an experiment that re-implements the rule measures the copy, not the tool.
Confidence tracks depth, because at low coverage a real variant and a sequencing error
produce the same column. Margin is the separation between the best-supported call and
the runner-up. Neither is sufficient alone: allele fraction ranks by how much of the
sample carries an allele, which is not the same question as which allele is relevant,
so a single dominant distractor produces a large margin and a wrong top call. The
surviving-candidate count is therefore reported as `alternatives`, and a list with any
rival above the floor is a candidate SET rather than an answer.
Args:
calls: Ranked output of `call_variants`, best first.
median_depth: Median depth over the positions examined.
Returns:
A `Competence` describing the list.
"""
from .competence import bounded
top = calls[0]["af"] if calls else 0.0
runner_up = calls[1]["af"] if len(calls) > 1 else 0.0
return bounded(
confidence=min(1.0, median_depth / 30.0),
margin=max(0.0, top - runner_up),
alternatives=max(0, len(calls) - 1),
ties=sum(1 for c in calls[1:] if top - c["af"] < 0.05),
blind_spots=(("median depth is below 10x; a real variant and a sequencing error "
"look the same here",) if median_depth < 10 else ()),
remedy="restrict --region to the gene of interest, or lower --min-af knowingly",
)
def pileup(bam: Path, reference: Path, *, region: str | None = None,
min_base_quality: int = 15, min_mapq: int = 20,
samtools: str | None = None, timeout: int = 3600):
"""Run `samtools mpileup` and yield its lines.
Raises:
RuntimeError: If samtools is missing or the pileup fails, quoting its stderr.
"""
from . import references
binary = samtools or references.find_binary("samtools")
if binary is None:
raise RuntimeError("samtools is not installed")
cmd = [binary, "mpileup", "-f", str(reference), "-Q", str(min_base_quality),
"-q", str(min_mapq)]
if region:
cmd += ["-r", region]
cmd.append(str(bam))
proc = subprocess.run(cmd, capture_output=True, text=True, errors="replace",
timeout=timeout)
if proc.returncode != 0 and not proc.stdout:
raise RuntimeError(f"samtools mpileup failed: {proc.stderr[-300:]}")
return proc.stdout.splitlines()