Somatic variants with a matched normal
A tumor variant call must distinguish a tumor-specific signal from inherited variation and technical error. A matched normal provides evidence for that comparison, but a tumor alternate allele count alone does not establish a somatic mutation.
This lesson runs GATK Mutect2 and FilterMutectCalls on original simulated tumor
and normal reads. The reference is a random sequence named synthetic_1; its
coordinates do not refer to a human chromosome. Three planted tumor-only SNVs
provide known positive cases, a shared germline SNV provides a negative case,
and one planted low-quality alternate signal provides an error control.
The example starts from aligned BAM files. Their alignments are exact by construction, so it does not evaluate an aligner, duplicate detection, base quality recalibration, or performance on a human genome. The Python code runs the actual GATK tools and then examines their outputs.
Inspect the inputs and sample identities
Section titled “Inspect the inputs and sample identities”Download the input archive and extract its
files into inputs/. It contains the reference, sequence dictionary, FASTA
index, two BAM files and their indexes, a truth table, and a checksum manifest.
The simulation script records the fixed
seed, allele positions, and simulation rules. These original inputs use the
CC0 dedication.
Each fragment supplies two 150-base reads without mate overlap. Fragment starts and lengths vary, and read-pair orientations are balanced. The generator plants alleles with declared probabilities per fragment, so observed allele fractions vary around those probabilities. All ordinary bases have quality 35; alternate bases at the error-control position have quality 15. Mapping quality is 60 because the alignments are supplied directly. No other sequencing errors or cross-sample contamination are simulated.
import hashlibimport jsonfrom pathlib import Pathimport subprocess
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pysam
inputs = Path("inputs")output = Path("outputs")output.mkdir(exist_ok=True)manifest = json.loads((inputs / "simulation_manifest.json").read_text())for filename, expected in manifest["files"].items(): observed = hashlib.sha256((inputs / filename).read_bytes()).hexdigest() assert observed == expectedtruth = pd.read_csv(inputs / "variant_truth.csv")for sample in ["TUMOR", "NORMAL"]: with pysam.AlignmentFile(inputs / f"{sample.lower()}.bam") as handle: groups = handle.header.to_dict()["RG"] assert {group["SM"] for group in groups} == {sample} assert handle.references == ("synthetic_1",) assert handle.lengths == (24000,) print(f"{sample}: {handle.mapped} aligned reads")print(truth[["position", "truth_class", "tumor_probability", "normal_probability"]].to_string(index=False))TUMOR: 32000 aligned readsNORMAL: 24000 aligned reads position truth_class tumor_probability normal_probability 4000 somatic 0.35 0.0 8000 somatic 0.15 0.0 12000 somatic 0.04 0.0 16000 germline 0.50 0.5 20000 quality_artifact 0.20 0.0The NORMAL argument below must match the BAM read group’s SM field. A file
name is not a sample identifier. In a measured experiment, confirm that the
normal belongs to the same donor and that the reference assembly, contig names,
and preprocessing agree across both files.
Discover candidates and apply somatic filters
Section titled “Discover candidates and apply somatic filters”Mutect2 uses local haplotype assembly and a somatic genotype model. It can omit clear germline events before it writes its candidate VCF, so a missing germline record is not evidence that the input reads lacked that allele.
The first filter run uses the tool’s defaults. The second adds a 0.10 minimum allele fraction to illustrate the cost of a stricter reporting rule. This value is an arbitrary teaching choice, not a recommended detection threshold. Both runs receive the statistics file generated with the same candidate VCF.
No human population resource or panel of normals matches this synthetic reference. The example therefore omits both and uses the default tumor-normal prior for alleles absent from a population resource. That prior is a software assumption here, not a measured frequency in a population. The analysis also omits contamination estimates and an orientation artifact model because the fixture supplies neither a realistic population nor a realistic artifact process from which to estimate them.
def run_gatk(arguments, log_name): """Run one GATK command and retain its complete console output.
Args: arguments: Tool name followed by command arguments. log_name: File name for the command log under outputs.
Raises: subprocess.CalledProcessError: GATK exits with a nonzero status. """ with (output / log_name).open("w") as log: subprocess.run(["gatk", *arguments], check=True, stdout=log, stderr=subprocess.STDOUT)
reference = str(inputs / "synthetic_reference.fa")run_gatk([ "Mutect2", "-R", reference, "-I", str(inputs / "tumor.bam"), "-I", str(inputs / "normal.bam"), "-normal", "NORMAL", "--native-pair-hmm-threads", "2", "-O", str(output / "unfiltered.vcf.gz"),], "mutect2.log")for label, extra in [ ("filtered", []), ("minimum_af", ["--min-allele-fraction", "0.10"]),]: run_gatk([ "FilterMutectCalls", "-R", reference, "-V", str(output / "unfiltered.vcf.gz"), "--stats", str(output / "unfiltered.vcf.gz.stats"), "-O", str(output / f"{label}.vcf.gz"), *extra, ], f"{label}.log")print("Mutect2 completed; both FilterMutectCalls runs completed.")Mutect2 completed; both FilterMutectCalls runs completed.Candidate discovery is unconstrained. The truth table is not passed to Mutect2,
and the command does not force specified alleles into its output. Filtering
adds decisions to the candidate records; it does not make every emitted record
an accepted call. Retain the rejected records and their FILTER values when
you investigate why a known event disappeared from a report.
Compare every emitted allele with the truth
Section titled “Compare every emitted allele with the truth”Read all records, including calls outside the five planted positions. Exact contig, position, reference, and alternate matches define true positives for these SNVs. Every accepted allele outside the three tumor-only truth alleles counts as a false positive. Every missing tumor-only truth allele counts as a false negative. These counts describe this small fixture and do not estimate sensitivity across sequencing technologies or mutation classes.
def read_calls(path): """Read every alternate allele and its record-level filter decision.
Args: path: VCF file path.
Returns: A dataframe with allele identity, filters, and sample allele depths. """ rows = [] with pysam.VariantFile(path) as handle: for record in handle: for number, alternate in enumerate(record.alts, start=1): tumor_depths = record.samples["TUMOR"]["AD"] normal_depths = record.samples["NORMAL"]["AD"] rows.append({ "contig": record.contig, "position": record.pos, "reference": record.ref, "alternate": alternate, "filter": ";".join(record.filter.keys()) or ".", "tumor_ref": tumor_depths[0], "tumor_alt": tumor_depths[number], "normal_ref": normal_depths[0], "normal_alt": normal_depths[number], }) return pd.DataFrame(rows)
identity = ["contig", "position", "reference", "alternate"]positive_rows = truth.loc[truth["truth_class"] == "somatic", identity]positive_keys = set(positive_rows.itertuples(index=False, name=None))results = []call_tables = {}for label in ["unfiltered", "filtered", "minimum_af"]: table = read_calls(output / f"{label}.vcf.gz") call_tables[label] = table table.to_csv(output / f"{label}_alleles.csv", index=False) accepted = table if label == "unfiltered" else table.loc[ table["filter"] == "PASS" ] keys = set(accepted[identity].itertuples(index=False, name=None)) results.append({ "stage": label, "emitted_alleles": len(table), "selected_alleles": len(accepted), "true_positive": len(keys & positive_keys), "false_positive": len(keys - positive_keys), "false_negative": len(positive_keys - keys), })summary = pd.DataFrame(results)summary.to_csv(output / "call_recovery.csv", index=False)print(summary.to_string(index=False))print(call_tables["minimum_af"][["position", "alternate", "filter"]] .to_string(index=False)) stage emitted_alleles selected_alleles true_positive false_positive false_negativeunfiltered 3 3 3 0 0 filtered 3 3 3 0 0minimum_af 3 2 2 0 1 position alternate filter 4000 A PASS 8000 T PASS 12000 A low_allele_frac;strand_biasThe unfiltered row scores candidate emission, not final acceptance. Compare it
with the default PASS set before attributing a rejection to FilterMutectCalls.
Then compare the second filter setting. A minimum allele fraction rule can
remove a real low-fraction mutation even when the model finds evidence for it.
The stricter run labels position 12000 with both low_allele_frac and
strand_bias; retain both labels when describing this result.
Allele fraction is a proportion of sequenced molecules at a locus; tumor purity, copy number, and subclones prevent a general conversion to a fraction of cells.
Inspect the reads behind a call or an omission
Section titled “Inspect the reads behind a call or an omission”The next calculation returns to the BAM files and counts bases directly at each planted position. It reports all observed alternate bases and the subset with base quality at least 20. This separates a low-quality signal from an absence of alternate bases. It does not reproduce Mutect2’s assembly, likelihoods, or read filters, so these counts can differ from the VCF’s allele depths.
def count_input_bases(bam_path, variant): """Count direct read evidence at one simulated SNV position.
Args: bam_path: Indexed alignment file. variant: Truth-table row containing the SNV position and alleles.
Returns: Read depth, alternate count, and alternate count with quality >= 20. """ depth = 0 alternate = 0 high_quality = 0 with pysam.AlignmentFile(bam_path) as handle: for read in handle.fetch(variant.contig, variant.position - 1, variant.position): if read.is_unmapped or read.is_secondary or read.is_supplementary: continue for query, reference_position in read.get_aligned_pairs(): if reference_position != variant.position - 1 or query is None: continue depth += 1 if read.query_sequence[query] == variant.alternate: alternate += 1 high_quality += read.query_qualities[query] >= 20 return depth, alternate, high_quality
records = []for variant in truth.itertuples(): for sample in ["TUMOR", "NORMAL"]: depth, alternate, high_quality = count_input_bases( inputs / f"{sample.lower()}.bam", variant ) records.append({ "position": variant.position, "sample": sample, "truth_class": variant.truth_class, "read_depth": depth, "alternate_reads": alternate, "quality_20_alternate": high_quality, "observed_fraction": alternate / depth, })evidence = pd.DataFrame(records)evidence.to_csv(output / "input_read_evidence.csv", index=False)print(evidence[["position", "sample", "read_depth", "alternate_reads", "quality_20_alternate"]].to_string(index=False)) position sample read_depth alternate_reads quality_20_alternate 4000 TUMOR 219 84 84 4000 NORMAL 153 0 0 8000 TUMOR 171 28 28 8000 NORMAL 167 0 0 12000 TUMOR 195 9 9 12000 NORMAL 165 0 0 16000 TUMOR 225 114 114 16000 NORMAL 135 70 70 20000 TUMOR 180 25 0 20000 NORMAL 154 0 0A germline allele can have many supporting tumor reads and still be absent from the somatic candidate file because the normal carries it too. The error control shows why a read fraction must be interpreted with base qualities and other read evidence. In this fixture, the control is a declared synthetic error; in a measured sample, an omitted candidate requires investigation rather than a truth label supplied by a simulator.
Plot allele evidence and filtering decisions
Section titled “Plot allele evidence and filtering decisions”The left panel uses direct input counts, including low-quality alternate bases. The right panel distinguishes an accepted call, a filtered candidate, and an allele that Mutect2 did not emit. The displayed positions belong only to the synthetic sequence.
figure, axes = plt.subplots(1, 2, figsize=(11, 4.5), layout="constrained")positions = truth["position"].to_list()x = np.arange(len(positions))for sample, offset, color in [("TUMOR", -0.18, "#b44d29"), ("NORMAL", 0.18, "#355f8a")]: values = evidence.loc[evidence["sample"] == sample] axes[0].bar(x + offset, values["observed_fraction"], width=0.36, label=sample, color=color)axes[0].axhline(0.10, color="black", linestyle=":", linewidth=1, label="Illustrative 0.10 threshold")axes[0].set(xticks=x, xticklabels=positions, ylim=(0, 0.65), xlabel="Position on synthetic_1", ylabel="Direct alternate fraction", title="Input read evidence, all base qualities")axes[0].legend(fontsize=8)colors = {"PASS": "#2a7c62", "filtered": "#c26934", "not emitted": "#b9bec4"}for column, label in enumerate(["unfiltered", "filtered", "minimum_af"]): table = call_tables[label].set_index("position") for row, position in enumerate(positions): status = "not emitted" if position in table.index: status = "PASS" if label == "unfiltered" else table.loc[ position, "filter" ] if status != "PASS": status = "filtered" axes[1].scatter(column, row, c=colors[status], s=370, marker="s") text = status if label == "unfiltered" and status == "PASS": text = "emitted" axes[1].annotate(text, (column, row), xytext=(0, -23), textcoords="offset points", ha="center", fontsize=8)axes[1].set(xticks=[0, 1, 2], xticklabels=["Candidates", "Default", "AF >= 0.10"], yticks=x, yticklabels=positions, ylim=(4.7, -0.7), xlim=(-0.6, 2.6), ylabel="Position on synthetic_1", title="Emission and filter decisions")figure.savefig(output / "somatic_evidence.png", dpi=180)plt.close(figure)
The result tables include every emitted allele, the read counts, and both filtered VCFs. Rejected records retain their filter labels. Three recovered SNVs on an easy synthetic reference do not establish a detection limit, an indel error rate, or clinical accuracy.
For real data, use resources built for the exact reference assembly. A matched normal addresses inherited variation, a panel of normals addresses recurrent technical signals, and population allele frequencies inform germline priors. Contamination and orientation artifacts require their own measurements and model inputs. Those components are absent from this demonstration, so its successful calls do not show that those problems have been controlled in a sequenced tumor.
Scientific references
Section titled “Scientific references”Benjamin and colleagues, 2019 describe Mutect2’s local assembly, somatic genotype models, and variant filters in a preprint.
McKenna and colleagues, 2010 describe the Genome Analysis Toolkit and its MapReduce design for the analysis of sequencing data.
Further reading
Section titled “Further reading”The GATK 4.7.0.0 Mutect2 documentation explains tumor-normal inputs, early germline exclusion, and the statistics file. Consult its resource requirements before changing from this synthetic reference to measured data.
The GATK 4.7.0.0 FilterMutectCalls documentation defines filter arguments and the separate contamination and orientation inputs. It helps distinguish the added allele-fraction rule from the tool’s default model.
The GATK Mutect2 technical notes describe the statistical models in more detail. Use them when a filter label alone does not explain the evidence behind a decision.