Visualization
A results section of a variant calling study carries a small set of standard figures, and each one doubles as a quality check. This page draws four of them for the four callers sarek ran on HG002: the transition to transversion ratio, the allele balance of heterozygous SNVs, the density of calls along the region and the indel lengths. Each tab prints the numbers behind its figure before drawing it in ggplot2 or matplotlib, so your text can quote them.
The four call sets
Section titled “The four call sets”Four callers write four different VCFs, so read the headers before writing any code that assumes a sample name or a FORMAT field.
The HG002 inputs come from NIST and the Genome in a Bottle consortium. The preparation on October 29, 2026 selects the chromosome 20 interval, subsets the GIAB v4.2.1 benchmark, and produces fresh analysis outputs. The source and terms notice identifies the original sequencing and benchmark publications, the exact source files, and the changes. It also records the grants for the Broad reference bundle and Ensembl release 99 annotation.
cd /opt/data/variant_callingfor vcf in haplotypecaller/HG002.haplotypecaller.filtered.vcf.gz \ deepvariant/HG002.deepvariant.vcf.gz \ freebayes/HG002.freebayes.filtered.vcf.gz \ bcftools/HG002.bcftools.vcf.gz; do sample=$(bcftools query -l "$vcf") fields=$(bcftools view -h "$vcf" \ | grep -o '^##FORMAT=<ID=[^,]*' \ | cut -d '=' -f 3 \ | paste -sd ' ') ad=$(bcftools view -h "$vcf" \ | grep '^##FORMAT=<ID=AD,' \ | sed 's/.*Description="//; s/">$//') no_alt=$(bcftools view -H -i 'ALT="."' "$vcf" 2> /dev/null | wc -l) echo "${vcf%%/*} sample=$sample records with ALT '.': $no_alt" echo " FORMAT: $fields" echo " AD: $ad"donehaplotypecaller sample=HG002_HG002 records with ALT '.': 0 FORMAT: AD DP GQ GT PL AD: Allelic depths for the ref and alt alleles in the order listeddeepvariant sample=HG002 records with ALT '.': 0 FORMAT: GT GQ DP MIN_DP AD VAF PL PS MF MD MT MI MED_DP MID AD: Read depth for each allelefreebayes sample=HG002_HG002 records with ALT '.': 0 FORMAT: GT GQ GL DP AD RO QR AO QA MIN_DP AD: Number of observation for each allelebcftools sample=HG002 records with ALT '.': 124 FORMAT: PL AD GT AD: Allelic depths (high-quality bases)Three differences matter for the code. HaplotypeCaller and FreeBayes name the sample
HG002_HG002, the <patient>_<sample> read group that sarek builds, while DeepVariant and
bcftools name it HG002, so the code reads the one sample by position. All four write AD
and describe it differently, and FreeBayes writes the same counts again as RO and AO. And
bcftools writes 124 records with ALT . and genotype ./., sites with no called variant,
which the tabs remove explicitly and count.
Each call set is the file a sarek user would pick up, with the filter that caller ships.
| Caller | File | Records kept |
|---|---|---|
| HaplotypeCaller | HG002.haplotypecaller.filtered.vcf.gz |
FILTER PASS |
| DeepVariant | HG002.deepvariant.vcf.gz |
FILTER PASS, which drops RefCall and NoCall |
| FreeBayes | HG002.freebayes.filtered.vcf.gz |
every record, after the sarek --freebayes_filter QUAL cut |
| bcftools | HG002.bcftools.vcf.gz |
every record with a called genotype |
The tabs turn each VCF into one row per ALT allele. They drop the spanning deletion allele
*, which stands for a deletion called upstream, and they reduce an allele pair of equal
length to the bases that differ. FreeBayes and multiallelic records write some SNVs with
shared bases around the change, such as TA to CA, which is the SNV T>C. A pair that
still differs at more than one base is an MNP, and a pair of unequal length is an indel.
suppressPackageStartupMessages({ library(VariantAnnotation) library(dplyr) library(tidyr) library(ggplot2)})
dir.create("outputs", showWarnings = FALSE, recursive = TRUE)
call_dir <- "/opt/data/variant_calling"call_files <- c( HaplotypeCaller = "haplotypecaller/HG002.haplotypecaller.filtered.vcf.gz", DeepVariant = "deepvariant/HG002.deepvariant.vcf.gz", FreeBayes = "freebayes/HG002.freebayes.filtered.vcf.gz", bcftools = "bcftools/HG002.bcftools.vcf.gz")caller_levels <- names(call_files)# One fixed colour per caller, the same in every figure on the page.caller_colours <- c( HaplotypeCaller = "#2a78d6", DeepVariant = "#eb6834", FreeBayes = "#1baf7a", bcftools = "#eda100")
#' Describe an equal length REF and ALT pair by the bases that differ.#'#' FreeBayes and multiallelic records can write a one base change with#' shared bases around it, such as TA>CA, which is the SNV T>C.#'#' @param ref The REF allele.#' @param alt One ALT allele.#' @return "T>C" style text for the differing bases, or NA when the two#' alleles differ in length.SubstitutionOf <- function(ref, alt) { if (nchar(ref) != nchar(alt)) { return(NA_character_) } ref_bases <- strsplit(ref, "", fixed = TRUE)[[1]] alt_bases <- strsplit(alt, "", fixed = TRUE)[[1]] differ <- ref_bases != alt_bases paste0( paste(ref_bases[differ], collapse = ""), ">", paste(alt_bases[differ], collapse = "") )}
#' Read one call set as one row per ALT allele.#'#' Keeps the records whose FILTER is PASS or missing, with every ALT#' allele. VariantAnnotation stores the spanning deletion allele `*` and#' the ALT `.` of a site with no alternate allele as empty strings.#'#' @param path Path to a bgzipped VCF file.#' @param caller Caller name for the caller column.#' @return A data frame with one row per ALT allele.ReadCallSet <- function(path, caller) { param <- ScanVcfParam(info = NA, geno = c("GT", "AD")) vcf <- readVcf(path, "hg38", param = param) vcf <- vcf[filt(vcf) %in% c("PASS", ".")] n_alt <- lengths(alt(vcf)) record <- rep(seq_along(n_alt), n_alt) allele <- sequence(n_alt) depths <- geno(vcf)$AD[record, 1] alleles <- data.frame( caller = caller, sample = samples(header(vcf)), record = record, pos = start(vcf)[record], ref = as.character(ref(vcf))[record], alt = as.character(unlist(alt(vcf))), n_alt = n_alt[record], gt = sub("|", "/", geno(vcf)$GT[record, 1], fixed = TRUE), ad_ref = as.integer(mapply("[", depths, 1)), ad_alt = as.integer(mapply("[", depths, allele + 1)) ) alleles$change <- unname( mapply(SubstitutionOf, alleles$ref, alleles$alt) ) alleles$kind <- ifelse( is.na(alleles$change), "indel", ifelse(nchar(alleles$change) == 3, "SNV", "MNP") ) alleles$indel_length <- ifelse( alleles$kind == "indel", nchar(alleles$alt) - nchar(alleles$ref), NA ) alleles}
all_alleles <- bind_rows( Map(ReadCallSet, file.path(call_dir, call_files), caller_levels))all_alleles$caller <- factor(all_alleles$caller, caller_levels)
# A record with GT ./. holds no called variant. Count and remove them.no_call <- all_alleles |> filter(gt == "./.") |> distinct(caller, record) |> count(caller, name = "no_call_records", .drop = FALSE)print(as.data.frame(no_call), row.names = FALSE)cat("\n")# The spanning deletion allele * stands for a deletion called upstream.call_sets <- filter(all_alleles, gt != "./.", nchar(alt) > 0)
overview <- call_sets |> group_by(caller, sample) |> summarise( records = n_distinct(record), snv = sum(kind == "SNV"), indel = sum(kind == "indel"), mnp = sum(kind == "MNP"), .groups = "drop" )print(as.data.frame(overview), row.names = FALSE)
# FreeBayes writes the depths twice, as AD and as RO plus AO.freebayes_vcf <- readVcf( file.path(call_dir, call_files[["FreeBayes"]]), "hg38", param = ScanVcfParam(info = NA, geno = c("AD", "RO", "AO")))freebayes_ad <- geno(freebayes_vcf)$AD[, 1]freebayes_ro_ao <- Map( c, geno(freebayes_vcf)$RO[, 1], geno(freebayes_vcf)$AO[, 1])cat("\nFreeBayes records where AD differs from RO,AO:", sum(!mapply(identical, freebayes_ad, freebayes_ro_ao)), "\n") caller no_call_records HaplotypeCaller 0 DeepVariant 0 FreeBayes 0 bcftools 124
caller sample records snv indel mnp HaplotypeCaller HG002_HG002 1795 1452 382 0 DeepVariant HG002 1788 1444 384 0 FreeBayes HG002_HG002 1713 1378 363 29 bcftools HG002 1809 1479 361 0
FreeBayes records where AD differs from RO,AO: 0import jsonfrom pathlib import Path
import cyvcf2import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
CALL_DIR = Path("/opt/data/variant_calling")CALL_FILES = { "HaplotypeCaller": "haplotypecaller/HG002.haplotypecaller.filtered.vcf.gz", "DeepVariant": "deepvariant/HG002.deepvariant.vcf.gz", "FreeBayes": "freebayes/HG002.freebayes.filtered.vcf.gz", "bcftools": "bcftools/HG002.bcftools.vcf.gz",}CALLERS = list(CALL_FILES)# One fixed colour per caller, the same in every figure on the page.CALLER_COLOURS = { "HaplotypeCaller": "#2a78d6", "DeepVariant": "#eb6834", "FreeBayes": "#1baf7a", "bcftools": "#eda100",}OUTPUT_DIR = Path("outputs")OUTPUT_DIR.mkdir(exist_ok=True)
def substitution_of(ref, alt): """Describe an equal length REF and ALT pair by the bases that differ.
FreeBayes and multiallelic records can write a one base change with shared bases around it, such as TA>CA, which is the SNV T>C.
Args: ref: The REF allele. alt: One ALT allele.
Returns: "T>C" style text for the differing bases, or None when the two alleles differ in length. """ if len(ref) != len(alt): return None differ = [index for index in range(len(ref)) if ref[index] != alt[index]] ref_bases = "".join(ref[index] for index in differ) alt_bases = "".join(alt[index] for index in differ) return f"{ref_bases}>{alt_bases}"
def genotype_text(genotype): """Write one cyvcf2 genotype as unphased VCF text.
Args: genotype: One sample's entry of Variant.genotypes.
Returns: The genotype, such as "0/1", with "." for a missing allele. """ alleles = ["." if allele < 0 else str(allele) for allele in genotype[:2]] return "/".join(alleles)
def read_call_set(path, caller): """Read one call set as one row per ALT allele.
Keeps the records whose FILTER is PASS or missing, which cyvcf2 reports as None, with every ALT allele. cyvcf2 returns no ALT allele for the ALT "." of a site with no alternate allele, so that record gets one row with ALT ".".
Args: path: Path to a bgzipped VCF file. caller: Caller name for the caller column.
Returns: A data frame with one row per ALT allele. """ vcf = cyvcf2.VCF(str(path)) sample = vcf.samples[0] rows = [] record = 0 for variant in vcf: if variant.FILTER is not None: continue record += 1 depths = variant.format("AD")[0] alts = variant.ALT or ["."] for allele, alt in enumerate(alts, start=1): change = substitution_of(variant.REF, alt) if change is None: kind = "indel" else: kind = "SNV" if len(change) == 3 else "MNP" rows.append({ "caller": caller, "sample": sample, "record": record, "pos": variant.POS, "ref": variant.REF, "alt": alt, "n_alt": len(variant.ALT), "gt": genotype_text(variant.genotypes[0]), "ad_ref": depths[0], "ad_alt": depths[allele] if allele < len(depths) else None, "change": change, "kind": kind, "indel_length": ( len(alt) - len(variant.REF) if kind == "indel" else None ), }) vcf.close() return pd.DataFrame(rows)
def count_ad_mismatches(path): """Count the records whose AD differs from RO followed by AO.
Args: path: Path to a FreeBayes VCF file.
Returns: The number of records where the two depth fields disagree. """ vcf = cyvcf2.VCF(str(path)) mismatches = 0 for variant in vcf: ad = variant.format("AD")[0] ro_ao = np.concatenate( [variant.format("RO")[0], variant.format("AO")[0]] ) mismatches += int(not np.array_equal(ad, ro_ao)) vcf.close() return mismatches
all_alleles = pd.concat( [read_call_set(CALL_DIR / name, caller) for caller, name in CALL_FILES.items()], ignore_index=True,)
# A record with GT ./. holds no called variant. Count and remove them.no_call = ( all_alleles[all_alleles["gt"] == "./."] .drop_duplicates(["caller", "record"]) .groupby("caller").size() .reindex(CALLERS, fill_value=0))print(no_call.rename_axis("caller").reset_index( name="no_call_records").to_string(index=False))print()# The spanning deletion allele * stands for a deletion called upstream.call_sets = all_alleles[ (all_alleles["gt"] != "./.") & (all_alleles["alt"] != "*")]by_caller = call_sets.groupby("caller")kind_counts = pd.crosstab(call_sets["caller"], call_sets["kind"])overview = pd.DataFrame({ "sample": by_caller["sample"].first(), "records": by_caller["record"].nunique(), "snv": kind_counts["SNV"], "indel": kind_counts["indel"], "mnp": kind_counts["MNP"],}).reindex(CALLERS).rename_axis("caller").reset_index()print(overview.to_string(index=False))print()print("FreeBayes records where AD differs from RO,AO:", count_ad_mismatches(CALL_DIR / CALL_FILES["FreeBayes"])) caller no_call_recordsHaplotypeCaller 0 DeepVariant 0 FreeBayes 0 bcftools 124
caller sample records snv indel mnpHaplotypeCaller HG002_HG002 1795 1452 382 0 DeepVariant HG002 1788 1444 384 0 FreeBayes HG002_HG002 1713 1378 363 29 bcftools HG002 1809 1479 361 0
FreeBayes records where AD differs from RO,AO: 0R and Python print the same tables here and in every section below. The 124 no-call records all come from bcftools, which keeps 1,809 records once they are gone. FreeBayes alone writes MNP alleles, 29 of them, because it merges changes a few bases apart into one haplotype allele. Its AD agrees with RO and AO on every record, so AD serves all four callers.
Ti/Tv per caller
Section titled “Ti/Tv per caller”A transition swaps a purine for a purine or a pyrimidine for a pyrimidine, A and G or C and T. Every other substitution is a transversion, and there are twice as many possible transversions as transitions, so random errors give a ratio near 0.5. Real human variation is rich in transitions, and the GATK guide to evaluating a germline call set expects about 2.0 to 2.1 for a whole genome and more for an exome. A ratio well below that range points to false positives.
transition_changes <- c("A>G", "G>A", "C>T", "T>C")titv <- call_sets |> filter(kind == "SNV") |> mutate(transition = change %in% transition_changes) |> group_by(caller) |> summarise( transitions = sum(transition), transversions = sum(!transition), .groups = "drop" ) |> mutate(ti_tv = transitions / transversions)print( mutate(as.data.frame(titv), ti_tv = sprintf("%.3f", ti_tv)), row.names = FALSE)bcftools_row <- titv[titv$caller == "bcftools", ]haplotypecaller_row <- titv[titv$caller == "HaplotypeCaller", ]cat( "\nbcftools minus HaplotypeCaller: transitions", bcftools_row$transitions - haplotypecaller_row$transitions, "transversions", bcftools_row$transversions - haplotypecaller_row$transversions, "\n")
titv_plot <- ggplot(titv, aes(x = ti_tv, y = caller, colour = caller)) + annotate( "rect", xmin = 2.0, xmax = 2.1, ymin = -Inf, ymax = Inf, fill = "grey90" ) + annotate( "text", x = 2.05, y = 4.45, label = "whole genome range", size = 3, colour = "grey35" ) + geom_point(size = 4, show.legend = FALSE) + geom_text( aes(label = sprintf("%.3f", ti_tv)), nudge_y = 0.25, size = 3.2, colour = "grey20" ) + scale_colour_manual(values = caller_colours) + scale_y_discrete(limits = rev(caller_levels)) + coord_cartesian(xlim = c(1.9, 2.3)) + labs(x = "Transitions / transversions, SNV alleles", y = NULL) + theme_minimal(base_size = 11) + theme(panel.grid.minor = element_blank())ggsave( "outputs/visualization_titv_r.png", titv_plot, width = 6.5, height = 3.2, dpi = 150, bg = "white") caller transitions transversions ti_tv HaplotypeCaller 998 454 2.198 DeepVariant 991 453 2.188 FreeBayes 948 430 2.205 bcftools 1007 472 2.133
bcftools minus HaplotypeCaller: transitions 9 transversions 18
TRANSITIONS = {"A>G", "G>A", "C>T", "T>C"}
snvs = call_sets[call_sets["kind"] == "SNV"]is_transition = snvs["change"].isin(TRANSITIONS)titv = pd.DataFrame({ "transitions": is_transition.groupby(snvs["caller"]).sum(), "transversions": (~is_transition).groupby(snvs["caller"]).sum(),}).reindex(CALLERS)titv["ti_tv"] = titv["transitions"] / titv["transversions"]print(titv.rename_axis("caller").reset_index().to_string( index=False, formatters={"ti_tv": "{:.3f}".format}))surplus = titv.loc["bcftools"] - titv.loc["HaplotypeCaller"]print( "\nbcftools minus HaplotypeCaller: transitions", int(surplus["transitions"]), "transversions", int(surplus["transversions"]),)
fig, ax = plt.subplots(figsize=(6.5, 3.2))ax.axvspan(2.0, 2.1, color="0.9", zorder=0)ax.text(2.05, 3.45, "whole genome range", ha="center", fontsize=8, color="0.35")positions = np.arange(len(CALLERS))[::-1]for position, caller in zip(positions, CALLERS): value = titv.loc[caller, "ti_tv"] ax.scatter(value, position, s=60, color=CALLER_COLOURS[caller], zorder=3) ax.text(value, position + 0.22, f"{value:.3f}", ha="center", fontsize=8, color="0.2")ax.set_yticks(positions, CALLERS)ax.set_ylim(-0.5, len(CALLERS) - 0.2)ax.set_xlim(1.9, 2.3)ax.set_xlabel("Transitions / transversions, SNV alleles")ax.grid(axis="x", color="0.92")ax.spines[["top", "right", "left"]].set_visible(False)fig.tight_layout()fig.savefig(OUTPUT_DIR / "visualization_titv_python.png", dpi=150)plt.close(fig) caller transitions transversions ti_tvHaplotypeCaller 998 454 2.198 DeepVariant 991 453 2.188 FreeBayes 948 430 2.205 bcftools 1007 472 2.133
bcftools minus HaplotypeCaller: transitions 9 transversions 18
Three callers land between 2.188 and 2.205, and bcftools sits apart at 2.133. It also reports the most SNV alleles, 1,479 against 1,452 for HaplotypeCaller, and the surplus is 9 transitions and 18 transversions. A surplus with a ratio of 0.5 is what random errors look like. All four values sit above the whole genome range. That range describes a whole genome, and one 1 Mb stretch of chr20 with 1,378 to 1,479 SNVs per caller can sit off it, so compare the callers with each other here rather than with the band.
bcftools stats is the usual command line route to the same number.
cd /opt/data/variant_callingfor vcf in haplotypecaller/HG002.haplotypecaller.filtered.vcf.gz \ deepvariant/HG002.deepvariant.vcf.gz \ freebayes/HG002.freebayes.filtered.vcf.gz \ bcftools/HG002.bcftools.vcf.gz; do bcftools stats -f .,PASS "$vcf" 2> /dev/null \ | awk -v caller="${vcf%%/*}" \ '$1 == "TSTV" {printf "%-16s ts=%s tv=%s ts/tv=%s\n", caller, $3, $4, $5}'donehaplotypecaller ts=998 tv=454 ts/tv=2.20deepvariant ts=991 tv=453 ts/tv=2.19freebayes ts=941 tv=428 ts/tv=2.20bcftools ts=1007 tv=472 ts/tv=2.13Its counts match the tabs exactly for HaplotypeCaller, DeepVariant and bcftools. For FreeBayes it counts 941 and 428 where the tabs count 948 and 430. Every single-base allele counts the same way in both, so the difference sits in FreeBayes’ multi-base alleles, which the two methods split into SNVs differently, and both ratios round to 2.20.
Allele balance of heterozygous SNVs
Section titled “Allele balance of heterozygous SNVs”For a heterozygous SNV, about half the reads should carry each allele. The allele balance
is the ALT read count over the REF plus ALT count from the AD field, and the tabs compute
it for every biallelic SNV with genotype 0/1. They also count the calls below 0.3 and
above 0.7 and check how many of the low ones sit at a position that the GIAB truth VCF
lists.
truth_path <- "/opt/data/truth/hg002_giab_v4_2_1_chr20_region.vcf.gz"truth_param <- ScanVcfParam(fixed = NA, info = NA, geno = NA)truth_positions <- start(readVcf(truth_path, "hg38", param = truth_param))
het_snvs <- call_sets |> filter(kind == "SNV", n_alt == 1, gt == "0/1") |> mutate(allele_balance = ad_alt / (ad_ref + ad_alt)) |> filter(!is.na(allele_balance))balance_summary <- het_snvs |> group_by(caller) |> summarise( het_snvs = n(), median = sprintf("%.3f", median(allele_balance)), below_0.3 = sum(allele_balance < 0.3), of_which_in_truth = sum( allele_balance < 0.3 & pos %in% truth_positions ), above_0.7 = sum(allele_balance > 0.7), .groups = "drop" )print(as.data.frame(balance_summary), row.names = FALSE)
balance_plot <- ggplot(het_snvs, aes(x = allele_balance, fill = caller)) + geom_histogram( binwidth = 0.025, boundary = 0, colour = "white", linewidth = 0.2, show.legend = FALSE ) + geom_vline(xintercept = 0.5, colour = "grey30", linewidth = 0.4) + facet_wrap(~caller, ncol = 2) + scale_fill_manual(values = caller_colours) + scale_x_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.25)) + labs(x = "ALT reads / (REF + ALT reads)", y = "Heterozygous SNVs") + theme_minimal(base_size = 11) + theme(panel.grid.minor = element_blank())ggsave( "outputs/visualization_allele_balance_r.png", balance_plot, width = 7, height = 4.5, dpi = 150, bg = "white") caller het_snvs median below_0.3 of_which_in_truth above_0.7 HaplotypeCaller 898 0.500 25 6 1 DeepVariant 887 0.500 3 3 4 FreeBayes 852 0.500 8 4 3 bcftools 920 0.493 31 8 6
het_snvs = call_sets[ (call_sets["kind"] == "SNV") & (call_sets["n_alt"] == 1) & (call_sets["gt"] == "0/1")].copy()het_snvs["allele_balance"] = het_snvs["ad_alt"] / ( het_snvs["ad_ref"] + het_snvs["ad_alt"])het_snvs = het_snvs.dropna(subset=["allele_balance"])
truth_path = "/opt/data/truth/hg002_giab_v4_2_1_chr20_region.vcf.gz"truth_positions = {variant.POS for variant in cyvcf2.VCF(truth_path)}low = het_snvs["allele_balance"] < 0.3low_in_truth = low & het_snvs["pos"].isin(truth_positions)high = het_snvs["allele_balance"] > 0.7
balance = het_snvs.groupby("caller")["allele_balance"]balance_summary = pd.DataFrame({ "het_snvs": balance.size(), "median": balance.median(), "below_0.3": low.groupby(het_snvs["caller"]).sum(), "of_which_in_truth": low_in_truth.groupby(het_snvs["caller"]).sum(), "above_0.7": high.groupby(het_snvs["caller"]).sum(),}).reindex(CALLERS)print(balance_summary.rename_axis("caller").reset_index().to_string( index=False, formatters={"median": "{:.3f}".format}))
fig, axes = plt.subplots(2, 2, figsize=(7, 4.5), sharex=True, sharey=True)bins = np.arange(0, 1.0001, 0.025)for ax, caller in zip(axes.flat, CALLERS): values = het_snvs.loc[het_snvs["caller"] == caller, "allele_balance"] ax.hist(values, bins=bins, color=CALLER_COLOURS[caller], edgecolor="white", linewidth=0.3) ax.axvline(0.5, color="0.3", linewidth=0.8) ax.set_title(caller, fontsize=10) ax.grid(axis="y", color="0.92") ax.set_axisbelow(True) ax.spines[["top", "right"]].set_visible(False)fig.supxlabel("ALT reads / (REF + ALT reads)", fontsize=10)fig.supylabel("Heterozygous SNVs", fontsize=10)fig.tight_layout()fig.savefig(OUTPUT_DIR / "visualization_allele_balance_python.png", dpi=150)plt.close(fig) caller het_snvs median below_0.3 of_which_in_truth above_0.7HaplotypeCaller 898 0.500 25 6 1 DeepVariant 887 0.500 3 3 4 FreeBayes 852 0.500 8 4 3 bcftools 920 0.493 31 8 6
The centers agree, with a median of 0.500 for three callers and 0.493 for bcftools. The tails do not. HaplotypeCaller has 25 heterozygous SNVs below 0.3 and bcftools has 31, against 3 for DeepVariant and 8 for FreeBayes. Only 6 of the HaplotypeCaller calls and 8 of the bcftools calls sit at a position in the truth VCF, while all 3 of the DeepVariant calls do.
A heterozygous call that one read in five supports deserves suspicion. Reads that belong elsewhere in the genome can produce this pattern, and this section’s chr20-only reference gives such reads nowhere else to go. Absence from the truth VCF is not proof of an error, because the truth set is complete only inside its benchmark regions, and the Benchmarking page scores the calls inside them properly.
Variant density along the region
Section titled “Variant density along the region”Counting the records in 10 kb windows shows where along the region the calls fall. The tabs count records rather than alleles, give every window of the 1 Mb region a count even when it is zero, and correlate each caller’s 100 counts with those of HaplotypeCaller.
region_start <- 10000000region_end <- 11000000bin_width <- 10000bin_starts <- seq(region_start, region_end - bin_width, by = bin_width)
density <- call_sets |> distinct(caller, record, pos) |> mutate( bin_start = region_start + (pos - 1 - region_start) %/% bin_width * bin_width ) |> count(caller, bin_start) |> complete(caller, bin_start = bin_starts, fill = list(n = 0))density_summary <- density |> group_by(caller) |> summarise( bins = n(), mean = sprintf("%.2f", mean(n)), min = min(n), max = max(n), max_bin_start = bin_start[which.max(n)], empty_bins = sum(n == 0), .groups = "drop" )print(as.data.frame(density_summary), row.names = FALSE)
density_wide <- pivot_wider(density, names_from = caller, values_from = n)bin_correlation <- cor(density_wide[caller_levels])[, "HaplotypeCaller"]cat("\nPearson correlation of the bin counts with HaplotypeCaller\n")cat(sprintf("%-16s %.3f\n", caller_levels, bin_correlation), sep = "")
density_plot <- ggplot( density, aes(x = (bin_start + bin_width / 2) / 1e6, y = n, fill = caller)) + geom_col(width = bin_width / 1e6 * 0.85, show.legend = FALSE) + facet_wrap(~caller, ncol = 1) + scale_fill_manual(values = caller_colours) + labs(x = "Position on chr20 (Mb)", y = "Records per 10 kb") + theme_minimal(base_size = 11) + theme(panel.grid.minor = element_blank())ggsave( "outputs/visualization_density_r.png", density_plot, width = 7, height = 5.5, dpi = 150, bg = "white") caller bins mean min max max_bin_start empty_bins HaplotypeCaller 100 17.95 0 67 10020000 1 DeepVariant 100 17.88 0 68 10020000 1 FreeBayes 100 17.13 0 64 10110000 1 bcftools 100 18.09 1 70 10020000 0
Pearson correlation of the bin counts with HaplotypeCallerHaplotypeCaller 1.000DeepVariant 0.992FreeBayes 0.982bcftools 0.994
REGION_START = 10_000_000REGION_END = 11_000_000BIN_WIDTH = 10_000bin_starts = np.arange(REGION_START, REGION_END, BIN_WIDTH)
records = call_sets.drop_duplicates(["caller", "record"]).copy()records["bin_start"] = ( REGION_START + (records["pos"] - 1 - REGION_START) // BIN_WIDTH * BIN_WIDTH)full_grid = pd.MultiIndex.from_product( [CALLERS, bin_starts], names=["caller", "bin_start"])density = ( records.groupby(["caller", "bin_start"]).size() .reindex(full_grid, fill_value=0) .rename("n") .reset_index())by_caller = density.groupby("caller")["n"]density_summary = pd.DataFrame({ "bins": by_caller.size(), "mean": by_caller.mean(), "min": by_caller.min(), "max": by_caller.max(), "max_bin_start": density.loc[by_caller.idxmax(), "bin_start"].to_numpy(), "empty_bins": (density["n"] == 0).groupby(density["caller"]).sum(),}).reindex(CALLERS)print(density_summary.rename_axis("caller").reset_index().to_string( index=False, formatters={"mean": "{:.2f}".format}))
density_wide = density.pivot(index="bin_start", columns="caller", values="n")bin_correlation = density_wide[CALLERS].corr()["HaplotypeCaller"]print("\nPearson correlation of the bin counts with HaplotypeCaller")for caller in CALLERS: print(f"{caller:<16} {bin_correlation[caller]:.3f}")
fig, axes = plt.subplots(4, 1, figsize=(7, 5.5), sharex=True, sharey=True)for ax, caller in zip(axes, CALLERS): counts = density[density["caller"] == caller] centres = (counts["bin_start"] + BIN_WIDTH / 2) / 1e6 ax.bar(centres, counts["n"], width=BIN_WIDTH / 1e6 * 0.85, color=CALLER_COLOURS[caller]) ax.set_title(caller, fontsize=10) ax.grid(axis="y", color="0.92") ax.set_axisbelow(True) ax.spines[["top", "right"]].set_visible(False)axes[-1].set_xlabel("Position on chr20 (Mb)")fig.supylabel("Records per 10 kb", fontsize=10)fig.tight_layout()fig.savefig(OUTPUT_DIR / "visualization_density_python.png", dpi=150)plt.close(fig) caller bins mean min max max_bin_start empty_binsHaplotypeCaller 100 17.95 0 67 10020000 1 DeepVariant 100 17.88 0 68 10020000 1 FreeBayes 100 17.13 0 64 10110000 1 bcftools 100 18.09 1 70 10020000 0
Pearson correlation of the bin counts with HaplotypeCallerHaplotypeCaller 1.000DeepVariant 0.992FreeBayes 0.982bcftools 0.994
The four callers trace the same profile. The mean runs from 17.13 records per window for FreeBayes to 18.09 for bcftools, and the correlation with HaplotypeCaller is 0.992 for DeepVariant, 0.994 for bcftools and 0.982 for FreeBayes. Three callers put their densest window at 10,020,000, with 67 to 70 records, and FreeBayes puts its densest at 10,110,000, with 64.
The useful contrast is between what all four show and what one shows alone. A peak or a dip in every panel belongs to the genome or to the coverage, and the Coverage & QC page has the depth to tell the two apart. A peak in one panel alone belongs to that caller and is worth opening in a genome browser.
Indel lengths
Section titled “Indel lengths”The last figure counts the indel alleles by length, positive for an insertion and negative for a deletion. The plots show lengths up to 20 bases in either direction, and the tables count what lies beyond.
indels <- filter(call_sets, kind == "indel")indel_summary <- indels |> group_by(caller) |> summarise( indels = n(), insertions = sum(indel_length > 0), deletions = sum(indel_length < 0), one_base = sum(abs(indel_length) == 1), over_20 = sum(abs(indel_length) > 20), min = min(indel_length), max = max(indel_length), .groups = "drop" )print(as.data.frame(indel_summary), row.names = FALSE)
indel_plot <- indels |> filter(abs(indel_length) <= 20) |> count(caller, indel_length) |> ggplot(aes(x = indel_length, y = n, fill = caller)) + geom_col(width = 0.8, show.legend = FALSE) + facet_wrap(~caller, ncol = 2) + scale_fill_manual(values = caller_colours) + scale_x_continuous(breaks = seq(-20, 20, 5)) + labs( x = "Indel length (bases; negative = deletion)", y = "ALT alleles" ) + theme_minimal(base_size = 11) + theme(panel.grid.minor = element_blank())ggsave( "outputs/visualization_indel_length_r.png", indel_plot, width = 7, height = 4.5, dpi = 150, bg = "white")
# The gate compares these numbers with the Python tab.parity_metrics <- c( setNames(overview$records, paste0(overview$caller, "_records")), setNames(overview$snv, paste0(overview$caller, "_snv")), setNames(titv$ti_tv, paste0(titv$caller, "_ti_tv")), setNames( balance_summary$below_0.3, paste0(balance_summary$caller, "_ab_low") ), setNames(bin_correlation, paste0(caller_levels, "_bin_r")), setNames(indel_summary$indels, paste0(indel_summary$caller, "_indels")))jsonlite::write_json( as.list(parity_metrics), "outputs/visualization_metrics_r.json", auto_unbox = TRUE, digits = NA) caller indels insertions deletions one_base over_20 min max HaplotypeCaller 382 198 184 165 16 -48 144 DeepVariant 384 193 191 171 11 -48 28 FreeBayes 363 176 187 157 8 -36 28 bcftools 361 182 179 153 10 -42 28
indels = call_sets[call_sets["kind"] == "indel"].copy()indels["indel_length"] = indels["indel_length"].astype(int)lengths = indels.groupby("caller")["indel_length"]indel_summary = pd.DataFrame({ "indels": lengths.size(), "insertions": (indels["indel_length"] > 0).groupby( indels["caller"]).sum(), "deletions": (indels["indel_length"] < 0).groupby( indels["caller"]).sum(), "one_base": (indels["indel_length"].abs() == 1).groupby( indels["caller"]).sum(), "over_20": (indels["indel_length"].abs() > 20).groupby( indels["caller"]).sum(), "min": lengths.min(), "max": lengths.max(),}).reindex(CALLERS)print(indel_summary.rename_axis("caller").reset_index().to_string( index=False))
fig, axes = plt.subplots(2, 2, figsize=(7, 4.5), sharex=True, sharey=True)shown = indels[indels["indel_length"].abs() <= 20]for ax, caller in zip(axes.flat, CALLERS): counts = shown.loc[shown["caller"] == caller, "indel_length"] counts = counts.value_counts().sort_index() ax.bar(counts.index, counts.to_numpy(), width=0.8, color=CALLER_COLOURS[caller]) ax.set_title(caller, fontsize=10) ax.set_xticks(np.arange(-20, 21, 5)) ax.grid(axis="y", color="0.92") ax.set_axisbelow(True) ax.spines[["top", "right"]].set_visible(False)fig.supxlabel("Indel length (bases; negative = deletion)", fontsize=10)fig.supylabel("ALT alleles", fontsize=10)fig.tight_layout()fig.savefig(OUTPUT_DIR / "visualization_indel_length_python.png", dpi=150)plt.close(fig)
# The gate compares these numbers with the R tab.parity_tables = { "records": overview.set_index("caller")["records"], "snv": overview.set_index("caller")["snv"], "ti_tv": titv["ti_tv"], "ab_low": balance_summary["below_0.3"], "bin_r": bin_correlation, "indels": indel_summary["indels"],}parity_metrics = { f"{caller}_{metric}": float(values[caller]) for metric, values in parity_tables.items() for caller in CALLERS}(OUTPUT_DIR / "visualization_metrics_python.json").write_text( json.dumps(parity_metrics, indent=2) + "\n") caller indels insertions deletions one_base over_20 min maxHaplotypeCaller 382 198 184 165 16 -48 144 DeepVariant 384 193 191 171 11 -48 28 FreeBayes 363 176 187 157 8 -36 28 bcftools 361 182 179 153 10 -42 28
The four shapes match. One base indels are the largest group for every caller, from 153 of 361 for bcftools to 171 of 384 for DeepVariant, and insertions and deletions come close to even, 198 against 184 for HaplotypeCaller. The callers part at the long end. HaplotypeCaller reports 16 indels longer than 20 bases, including a 144 base insertion, while DeepVariant, FreeBayes and bcftools report 11, 8 and 10 and stop at 28 bases on the insertion side. A 144 base insertion is past the 50 base line that the What is DNA-seq page draws between an indel and a structural variant, so it needs a look in the alignments before it goes in a table.
Where these figures mislead
Section titled “Where these figures mislead”- AD is not one quantity. The headers above give four descriptions, from allelic depths for HaplotypeCaller to high-quality bases for bcftools, and each caller applies its own read and base quality rules before it counts. Compare the shapes of the allele balance histograms across callers rather than their exact tails.
- Representation changes the counts. The same change can be one MNP allele in FreeBayes
and two SNVs in another caller, and the same indel can sit at different positions in a
repeat. Normalize with
bcftools normand the reference before any comparison that matches calls by position. - The filter decides the figure. Every number here describes the call set after the filter each caller ships with, and the Filtering page shows what a filter removes. Drawn before and after a filter, the allele balance tail and the Ti/Tv show whether it removed the right calls.
Next steps
Section titled “Next steps”The code for this page is in guides/dnaseq/visualization/ of the companion repository.
The Benchmarking page replaces the indirect checks on this
page with a direct one, precision and recall against the GIAB truth set.
Scientific references
Section titled “Scientific references”Danecek and colleagues, 2021 describe the development and the current features of SAMtools and BCFtools.
Obenchain and colleagues, 2014 describe VariantAnnotation, the Bioconductor package for the exploration and annotation of genetic variants.
Further reading
Section titled “Further reading”The VCF specification defines the allele and genotype fields used by these summaries. A plot must preserve the distinction between records and alternate alleles.
The BCFtools query and normalization reference explains field extraction and variant representation. It helps interpret comparisons between the four caller outputs.