Benchmarking
HG002 has an answer key, so the four call sets from Comparing callers can be scored as well as compared. Precision is the share of calls that are right, recall is the share of truth variants that were found, and the F-measure is their harmonic mean. This page computes the three for each caller, for SNVs and indels apart, with the haplotype comparison that the GA4GH best practices of Krusche et al. 2019 call for. It then shows what a plain position match gets wrong. The truth set is GIAB v4.2.1, described in Wagner et al. 2022.
The truth set inside the region
Section titled “The truth set inside the region”A truth set has two parts. The VCF lists the variants, and the BED file lists the regions
where that list is complete, so every score on this page is computed inside the BED. The
count below uses the rule of bcftools view --regions-file, which keeps a record that
overlaps an interval, the same rule as vcfeval.
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.
set -o pipefailREF=/opt/reference/chr20.fastaSDF=/opt/reference/chr20.sdfTRUTH=/opt/data/truth/hg002_giab_v4_2_1_chr20_region.vcf.gzBED=/opt/data/truth/hg002_giab_v4_2_1_chr20_region_noinconsistent.bedCALLS=/opt/data/variant_calling# /work is the page folder. The R and Python tabs read the files from there.OUT=/work/outputs/benchmarkingmkdir -p "$OUT"
echo "BED intervals: $(wc -l < "$BED")"echo "BED bases: $(awk '{bases += $3 - $2} END {print bases}' "$BED")"echo "truth records: $(bcftools view --no-header "$TRUTH" | wc -l)"echo "truth records in the BED: $(bcftools view --no-header \ --regions-file "$BED" "$TRUTH" | wc -l)"BED intervals: 129BED bases: 977839truth records: 1625truth records in the BED: 1588Of the 1,625 truth records in the region, 1,588 overlap the 129 BED intervals, and these are the variants the callers are scored against.
Score each caller with vcfeval
Section titled “Score each caller with vcfeval”A variant can be written in more than one way. A deletion in a repeat can sit at several
positions, and two nearby SNVs can be one MNP. RTG Tools vcfeval, described by
Cleary et al. 2015, applies the calls and the truth
variants to the reference. It then searches for the largest sets of each that produce the
same haplotype sequences, and it requires the genotypes to match as well. hap.py, the
GA4GH reference tool, can use vcfeval as its
comparison engine.
The loop drops the 124 bcftools records that carry no alternative allele, as on the
Comparing callers page, and runs vcfeval once per caller. --sample pairs the truth
sample with the call sample, read from each file, because two callers name it
HG002_HG002. --bed-regions reads only the truth and call records that overlap a BED
interval, according to the
RTG manual.
--vcf-score-field QUAL ranks the calls for the ROC files, since the bcftools file has
no GQ, the default score. vcfeval skips filtered records unless you pass
--all-records, so a FILTER value written by a pipeline changes the score.
callers=(haplotypecaller deepvariant freebayes bcftools)inputs=( "$CALLS/haplotypecaller/HG002.haplotypecaller.filtered.vcf.gz" "$CALLS/deepvariant/HG002.deepvariant.vcf.gz" "$CALLS/freebayes/HG002.freebayes.filtered.vcf.gz" "$CALLS/bcftools/HG002.bcftools.vcf.gz")
# Drop the records without an ALT allele before scoring, and count them.printf '%-16s %-12s %7s %6s\n' caller sample records no_altfor i in "${!callers[@]}"; do caller=${callers[$i]} sample=$(bcftools query --list-samples "${inputs[$i]}") bcftools view --exclude 'ALT="."' "${inputs[$i]}" -Oz \ --output "calls_$caller.vcf.gz" --write-index=tbi printf '%-16s %-12s %7d %6d\n' "$caller" "$sample" \ "$(bcftools view --no-header "${inputs[$i]}" | wc -l)" \ "$(bcftools view --no-header --include 'ALT="."' "${inputs[$i]}" | wc -l)"done
for i in "${!callers[@]}"; do caller=${callers[$i]} sample=$(bcftools query --list-samples "${inputs[$i]}") rtg RTG_MEM=4g vcfeval \ --baseline "$TRUTH" \ --calls "calls_$caller.vcf.gz" \ --sample "HG002,$sample" \ --bed-regions "$BED" \ --template "$SDF" \ --vcf-score-field QUAL \ --threads 2 \ --output "vcfeval_$caller" > /dev/null # The same run with the flag the RTG manual suggests for a truth BED. rtg RTG_MEM=4g vcfeval \ --baseline "$TRUTH" \ --calls "calls_$caller.vcf.gz" \ --sample "HG002,$sample" \ --evaluation-regions "$BED" \ --template "$SDF" \ --vcf-score-field QUAL \ --threads 2 \ --output "evaluation_regions_$caller" > /dev/null mkdir -p "$OUT/$caller" cp "vcfeval_$caller"/{tp-baseline,fn,tp,fp}.vcf.gz "$OUT/$caller/"done
# The "None" row of summary.txt scores every passing call.printf '%-16s %7s %7s %3s %3s %9s %11s %9s\n' caller tp_base tp_call \ fp fn precision sensitivity f_measurefor caller in "${callers[@]}"; do awk -v caller="$caller" '$1 == "None" { printf "%-16s %7s %7s %3s %3s %9s %11s %9s\n", caller, $2, $3, $4, $5, $6, $7, $8 }' "vcfeval_$caller/summary.txt"done
printf '\nwith --evaluation-regions\n'for caller in "${callers[@]}"; do awk -v caller="$caller" '$1 == "None" { printf "%-16s %7s %7s %3s %3s %9s %11s %9s\n", caller, $2, $3, $4, $5, $6, $7, $8 }' "evaluation_regions_$caller/summary.txt"done
# vcfeval also writes a SNP and a non-SNP ROC file. Their last row holds# every passing call.printf '\n%-16s %-8s %7s %3s %7s %3s\n' caller class tp_base fp tp_call fnfor caller in "${callers[@]}"; do for class in snp non_snp; do zcat "vcfeval_$caller/${class}_roc.tsv.gz" \ | tail -n 1 \ | awk -v caller="$caller" -v class="$class" '{ printf "%-16s %-8s %7d %3d %7d %3d\n", caller, class, $2, $3, $4, $5 }' donedonecaller sample records no_althaplotypecaller HG002_HG002 1807 0deepvariant HG002 2010 0freebayes HG002_HG002 1713 0bcftools HG002 1933 124caller tp_base tp_call fp fn precision sensitivity f_measurehaplotypecaller 1586 1586 6 2 0.9962 0.9987 0.9975deepvariant 1588 1591 0 0 1.0000 1.0000 1.0000freebayes 1582 1548 4 6 0.9974 0.9962 0.9968bcftools 1574 1576 19 14 0.9881 0.9912 0.9896
with --evaluation-regionshaplotypecaller 1586 1586 6 2 0.9962 0.9987 0.9975deepvariant 1588 1591 0 0 1.0000 1.0000 1.0000freebayes 1582 1548 4 6 0.9974 0.9962 0.9968bcftools 1574 1576 19 14 0.9881 0.9912 0.9896
caller class tp_base fp tp_call fnhaplotypecaller snp 1353 6 1353 1haplotypecaller non_snp 233 0 233 1deepvariant snp 1354 0 1354 0deepvariant non_snp 234 0 237 0freebayes snp 1353 1 1301 1freebayes non_snp 229 3 247 5bcftools snp 1353 7 1357 1bcftools non_snp 221 12 219 13The None row scores every passing call. The manual suggests --evaluation-regions
for a truth BED, because it handles matches that cross an interval border, and here the
second table is identical to the first. DeepVariant makes no error inside the BED.
HaplotypeCaller reaches a precision of 0.9962 and a sensitivity, the vcfeval word for
recall, of 0.9987. freebayes reaches 0.9974 and 0.9962, and bcftools 0.9881 and 0.9912.
freebayes has 1,582 true positives on the truth side but 1,548 on the call side, because
one of its MNP calls can match two truth SNVs.
SNVs and indels apart
Section titled “SNVs and indels apart”The R and Python tabs sort every record of the vcfeval files with one rule. A record is
an SNV when its REF and every ALT allele are one base long, and an indel otherwise, MNPs
included. Recall uses the truth side, tp-baseline and fn, and precision the call
side, tp and fp, so a freebayes MNP counts as an indel among the calls and as two
SNVs among the truth. The counts equal the last rows of the snp_roc.tsv.gz and
non_snp_roc.tsv.gz files of vcfeval, printed above, and the two tabs print the same
table.
suppressPackageStartupMessages({ library(VariantAnnotation) library(dplyr) library(tidyr) library(readr) library(ggplot2)})
callers <- c("haplotypecaller", "deepvariant", "freebayes", "bcftools")outcomes <- c("tp-baseline", "fn", "tp", "fp")eval_dir <- "outputs/benchmarking"
#' Count the records of one vcfeval output file by variant class.#'#' A record is an SNV when its REF and every ALT allele are one base long.#' Every other record, MNPs and complex alleles included, is an indel.#'#' @param caller Caller name, the folder that holds the vcfeval files.#' @param outcome One of "tp-baseline", "fn", "tp" or "fp".#' @param eval_dir Folder that holds one subfolder per caller.#' @return A tibble with the caller, the outcome, the class and the count.CountByClass <- function(caller, outcome, eval_dir) { vcf <- readVcf(file.path(eval_dir, caller, paste0(outcome, ".vcf.gz"))) single_base <- nchar(ref(vcf)) == 1 & all(nchar(alt(vcf)) == 1) variant_class <- ifelse(single_base, "SNV", "indel") class_counts <- table(factor(variant_class, levels = c("SNV", "indel"))) tibble( caller = caller, outcome = outcome, class = names(class_counts), n = as.integer(class_counts) )}
grid <- expand_grid(caller = callers, outcome = outcomes)counts <- bind_rows(Map( CountByClass, grid$caller, grid$outcome, MoreArgs = list(eval_dir = eval_dir)))
metrics <- counts |> pivot_wider(names_from = outcome, values_from = n) |> rename(tp_baseline = `tp-baseline`, tp_call = tp) |> mutate( caller = factor(caller, levels = callers), class = factor(class, levels = c("SNV", "indel")), precision = tp_call / (tp_call + fp), recall = tp_baseline / (tp_baseline + fn), f_measure = 2 * precision * recall / (precision + recall) ) |> arrange(class, caller)
# The truth side of the table is the same for every caller.metrics |> mutate(truth = tp_baseline + fn) |> distinct(class, truth) |> as.data.frame() |> print(row.names = FALSE)
metrics |> mutate( precision = round(precision, 4), recall = round(recall, 4), f_measure = round(f_measure, 4) ) |> as.data.frame() |> print(row.names = FALSE) class truth SNV 1354 indel 234 caller class tp_baseline fn tp_call fp precision recall f_measure haplotypecaller SNV 1353 1 1353 6 0.9956 0.9993 0.9974 deepvariant SNV 1354 0 1354 0 1.0000 1.0000 1.0000 freebayes SNV 1353 1 1301 1 0.9992 0.9993 0.9992 bcftools SNV 1353 1 1357 7 0.9949 0.9993 0.9971 haplotypecaller indel 233 1 233 0 1.0000 0.9957 0.9979 deepvariant indel 234 0 237 0 1.0000 1.0000 1.0000 freebayes indel 229 5 247 3 0.9880 0.9786 0.9833 bcftools indel 221 13 219 12 0.9481 0.9444 0.9462import jsonimport pathlib
import cyvcf2import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
CALLERS = ["haplotypecaller", "deepvariant", "freebayes", "bcftools"]OUTCOMES = ["tp-baseline", "fn", "tp", "fp"]EVAL_DIR = "outputs/benchmarking"
def count_by_class(caller, outcome, eval_dir): """Count the records of one vcfeval output file by variant class.
A record is an SNV when its REF and every ALT allele are one base long. Every other record, MNPs and complex alleles included, is an indel.
Args: caller: Caller name, the folder that holds the vcfeval files. outcome: One of "tp-baseline", "fn", "tp" or "fp". eval_dir: Folder that holds one subfolder per caller.
Returns: A dict with the caller, the outcome and the SNV and indel counts. """ counts = {"caller": caller, "outcome": outcome, "SNV": 0, "indel": 0} for variant in cyvcf2.VCF(f"{eval_dir}/{caller}/{outcome}.vcf.gz"): alleles = [variant.REF, *variant.ALT] single_base = all(len(allele) == 1 for allele in alleles) counts["SNV" if single_base else "indel"] += 1 return counts
rows = [ count_by_class(caller, outcome, EVAL_DIR) for caller in CALLERS for outcome in OUTCOMES]counts = pd.DataFrame(rows).melt( id_vars=["caller", "outcome"], var_name="class", value_name="n")metrics = counts.pivot( index=["caller", "class"], columns="outcome", values="n").reset_index()metrics = metrics.rename( columns={"tp-baseline": "tp_baseline", "tp": "tp_call"})metrics["precision"] = metrics["tp_call"] / (metrics["tp_call"] + metrics["fp"])metrics["recall"] = metrics["tp_baseline"] / ( metrics["tp_baseline"] + metrics["fn"])metrics["f_measure"] = ( 2 * metrics["precision"] * metrics["recall"] / (metrics["precision"] + metrics["recall"]))metrics["caller"] = pd.Categorical(metrics["caller"], CALLERS)metrics["class"] = pd.Categorical(metrics["class"], ["SNV", "indel"])metrics = metrics.sort_values(["class", "caller"])
# The truth side of the table is the same for every caller.metrics["truth"] = metrics["tp_baseline"] + metrics["fn"]print(metrics[["class", "truth"]].drop_duplicates().to_string(index=False))
columns = [ "caller", "class", "tp_baseline", "fn", "tp_call", "fp", "precision", "recall", "f_measure",]print(metrics[columns].round(4).to_string(index=False))class truth SNV 1354indel 234 caller class tp_baseline fn tp_call fp precision recall f_measurehaplotypecaller SNV 1353 1 1353 6 0.9956 0.9993 0.9974 deepvariant SNV 1354 0 1354 0 1.0000 1.0000 1.0000 freebayes SNV 1353 1 1301 1 0.9992 0.9993 0.9992 bcftools SNV 1353 1 1357 7 0.9949 0.9993 0.9971haplotypecaller indel 233 1 233 0 1.0000 0.9957 0.9979 deepvariant indel 234 0 237 0 1.0000 1.0000 1.0000 freebayes indel 229 5 247 3 0.9880 0.9786 0.9833 bcftools indel 221 13 219 12 0.9481 0.9444 0.9462The truth side holds 1,354 SNVs and 234 indels for every caller. SNVs barely separate the callers, and all four find at least 1,353 of the 1,354. Indels separate them. DeepVariant scores 1.0000 for precision and for recall, HaplotypeCaller 1.0000 and 0.9957, freebayes 0.9880 and 0.9786, and bcftools 0.9481 and 0.9444.
Plot precision and recall
Section titled “Plot precision and recall”The figure draws the same table as dot plots. The x axis starts at 0.94.
caller_names <- c( haplotypecaller = "HaplotypeCaller", deepvariant = "DeepVariant", freebayes = "freebayes", bcftools = "bcftools")plot_data <- metrics |> select(caller, class, precision, recall, f_measure) |> pivot_longer(precision:f_measure, names_to = "metric") |> mutate( metric = factor( metric, levels = c("precision", "recall", "f_measure"), labels = c("Precision", "Recall", "F-measure") ), caller = factor(caller_names[as.character(caller)], levels = rev(caller_names)) )
metric_plot <- ggplot(plot_data, aes(value, caller)) + geom_point(colour = "#2a78d6", size = 3) + facet_grid(class ~ metric) + scale_x_continuous(limits = c(0.94, 1), breaks = c(0.95, 0.975, 1)) + labs( x = NULL, y = NULL, title = "vcfeval against GIAB v4.2.1, HG002 chr20:10,000,001-11,000,000" ) + theme_minimal(base_size = 11) + theme( panel.grid.minor = element_blank(), panel.spacing.x = unit(1.5, "lines") )ggsave( "outputs/benchmarking_precision_recall_r.png", metric_plot, width = 9, height = 4.5, dpi = 120, bg = "white")
caller_names = { "haplotypecaller": "HaplotypeCaller", "deepvariant": "DeepVariant", "freebayes": "freebayes", "bcftools": "bcftools",}metric_names = { "precision": "Precision", "recall": "Recall", "f_measure": "F-measure"}
figure, axes = plt.subplots( 2, 3, figsize=(9, 4.5), sharex=True, sharey=True)for row, variant_class in enumerate(["SNV", "indel"]): subset = metrics[metrics["class"] == variant_class].set_index("caller") for column, metric in enumerate(metric_names): ax = axes[row, column] values = subset.loc[CALLERS, metric] positions = range(len(CALLERS)) ax.scatter(values, positions, color="#2a78d6", s=36, zorder=3) ax.set_xlim(0.94, 1.004) ax.set_xticks([0.95, 0.975, 1.0]) ax.set_yticks(positions, [caller_names[c] for c in CALLERS]) ax.grid(color="#ebeae6") ax.set_axisbelow(True) ax.spines[["top", "right"]].set_visible(False) if row == 0: ax.set_title(metric_names[metric]) if column == 2: ax.text(1.02, 0.5, variant_class, transform=ax.transAxes, rotation=-90, va="center")axes[0, 0].invert_yaxis()figure.suptitle( "vcfeval against GIAB v4.2.1, HG002 chr20:10,000,001-11,000,000", x=0.02, ha="left",)figure.tight_layout()figure.savefig("outputs/benchmarking_precision_recall_python.png", dpi=120)
A naive match by position and allele
Section titled “A naive match by position and allele”The quick alternative is to normalize both files with bcftools norm and count exact
matches with bcftools isec. A shared site is a true positive, a site only in the calls
is a false positive, and a site only in the truth is a false negative.
# Split and left-align the truth and each call set, as on the Comparing# callers page, then keep the records that start inside the BED.bcftools norm --multiallelics -any --fasta-ref "$REF" "$TRUTH" -Ou \ | bcftools view --targets-file "$BED" -Oz --output truth.vcf.gz \ --write-index=tbifor i in "${!callers[@]}"; do caller=${callers[$i]} bcftools view --apply-filters PASS,. "calls_$caller.vcf.gz" -Ou \ | bcftools norm --multiallelics -any --fasta-ref "$REF" -Ou \ | bcftools view --include 'GT="alt" && ALT!="*"' -Oz \ --output "norm_$caller.vcf.gz" --write-index=tbi bcftools view --targets-file "$BED" "norm_$caller.vcf.gz" -Oz \ --output "inside_$caller.vcf.gz" --write-index=tbidone
printf '%-16s %5s %3s %3s %9s %9s\n' caller tp fp fn precision recallfor caller in "${callers[@]}"; do bcftools isec --nfiles +1 --collapse none \ truth.vcf.gz "inside_$caller.vcf.gz" \ | awk -v caller="$caller" ' $5 == "11" {tp++} $5 == "01" {fp++} $5 == "10" {fn++} END { printf "%-16s %5d %3d %3d %9.4f %9.4f\n", caller, tp, fp, fn, tp / (tp + fp), tp / (tp + fn) }'donecaller tp fp fn precision recallhaplotypecaller 1605 6 2 0.9963 0.9988deepvariant 1606 4 1 0.9975 0.9994freebayes 1542 34 65 0.9784 0.9596bcftools 1603 10 4 0.9938 0.9975The naive numbers move in both directions. freebayes falls to 0.9784 and 0.9596, with 34 false positives and 65 false negatives against the 4 and 6 of vcfeval. DeepVariant gains 4 false positives and 1 false negative, and bcftools improves to 10 false positives against 19. The records below show why.
# Print position, alleles and genotype for a region of one VCF.show() { bcftools query --regions "$1" --format '%POS\t%REF\t%ALT\t[%GT]\n' "$2"}echo "freebayes, chr20:10002332"show chr20:10002330-10002335 "$TRUTH" | sed 's/^/ truth /'show chr20:10002330-10002335 "${inputs[2]}" | sed 's/^/ freebayes /'echo "DeepVariant, chr20:10056460-10056500"show chr20:10056460-10056500 "$TRUTH" | sed 's/^/ truth /'show chr20:10056460-10056500 "${inputs[1]}" | sed 's/^/ deepvariant /'echo " DeepVariant records that the naive match cannot pair:"bcftools isec --nfiles +1 --collapse none \ truth.vcf.gz inside_deepvariant.vcf.gz \ | awk '$5 != "11" {print " " $2, $3, $4, $5}'echo "bcftools, chr20:10082287"show chr20:10082287 "$TRUTH" | sed 's/^/ truth /'show chr20:10082287 "${inputs[3]}" | sed 's/^/ bcftools /'freebayes, chr20:10002332 truth 10002332 T C 0/1 truth 10002333 A G 0/1 freebayes 10002332 TA CG 0/1DeepVariant, chr20:10056460-10056500 truth 10056462 T TGATA 1/1 truth 10056496 TGATA TGATAGATA,T 2/1 deepvariant 10056462 T TGATA 0/1 deepvariant 10056477 T TA 0/1 deepvariant 10056480 TA T 0/1 deepvariant 10056496 T TA,TGATA 1/2 deepvariant 10056499 TA T 0/1 DeepVariant records that the naive match cannot pair: 10056477 T TA 01 10056480 TA T 01 10056496 TGATA T 10 10056496 T TA 01 10056499 TA T 01bcftools, chr20:10082287 truth 10082287 CA C 1/1 bcftools 10082287 CAAAAAAAAAAAAAAAAAAAA CAAAAAAAAAAAAAAAAAAA 0/1- freebayes writes
TAtoCGat 10,002,332 as one MNP, and the truth writes two SNVs. The position match counts one false positive and two false negatives, and vcfeval finds the same haplotype. - In the
GATArepeat from 10,056,462 to 10,056,499, the DeepVariant records and the truth records describe the same haplotypes with different records. vcfeval scores them as correct. The position match leaves four DeepVariant records and one truth record unpaired, which are all of the naive DeepVariant errors. - At 10,082,287 the truth is a homozygous deletion of one
Afrom a run, and bcftools calls it heterozygous. Afternormthe alleles match andisecignores the genotype, but vcfeval counts a false positive and a false negative.
The position match also counts split alleles rather than records, so its totals are on a different scale from those of vcfeval. Report the vcfeval numbers.
Where the errors sit
Section titled “Where the errors sit”The bash fence prints the HaplotypeCaller errors with their annotations.
echo "HaplotypeCaller false positives"bcftools query \ --format '%POS\t%REF\t%ALT\tQD=%QD\tSOR=%SOR\tAD=[%AD]\n' \ "vcfeval_haplotypecaller/fp.vcf.gz"echo "DeepVariant records from 10333494 to 10333506"bcftools query --regions chr20:10333494-10333506 \ --format '%POS\t%REF\t%ALT\t%FILTER\tGT=[%GT]\tAD=[%AD]\n' \ "${inputs[1]}"echo "HaplotypeCaller false negatives, as HaplotypeCaller wrote them"bcftools query --format '%CHROM\t%POS\n' \ "vcfeval_haplotypecaller/fn.vcf.gz" > haplotypecaller_fn.tsvbcftools query --regions-file haplotypecaller_fn.tsv \ --format '%POS\t%REF\t%ALT\t%FILTER\t[%GT]\n' "${inputs[0]}"HaplotypeCaller false positives10333494 T C QD=2.44 SOR=3.585 AD=28,510333498 T C QD=2.28 SOR=3.585 AD=29,510333502 A C QD=2.28 SOR=3.586 AD=29,510333506 T C QD=1.47 SOR=3.224 AD=29,410579669 A C QD=2.02 SOR=4.796 AD=30,1010933319 T G QD=1.99 SOR=1.725 AD=22,8DeepVariant records from 10333494 to 1033350610333494 T C RefCall GT=0/0 AD=28,610333502 A C RefCall GT=0/0 AD=29,5HaplotypeCaller false negatives, as HaplotypeCaller wrote them10020371 T G CNN_1D_SNP_Tranche_99.95_100.00 0/1Four of the six HaplotypeCaller false positives sit together, from 10,333,494 to
10,333,506. Each has 4 or 5 alternative reads out of 33 or 34, a QD from 1.47 to 2.44,
and a SOR from 3.224 to 3.586, which is a sign of strand bias. DeepVariant called two of these
positions RefCall, and the tranche filter passed all four. The
Filtering page covers the hard filters on QD and SOR. One
false negative is the reverse case, a call at 10,020,371 that the tranche filter removed.
The tabs set each error against the region ends and against depth. The fetch script kept only read pairs whose two reads both start inside the region, so depth falls at both ends. Depth comes from the 500 bp mosdepth windows after recalibration, and a window below the 5th percentile counts as low.
region <- read_tsv( "/opt/data/region/chr20_region.bed", col_names = c("chrom", "start", "end"), show_col_types = FALSE)windows <- read_tsv( "/opt/data/qc/mosdepth/HG002.recal.regions.bed.gz", col_names = c("chrom", "start", "end", "depth"), show_col_types = FALSE) |> filter(start >= region$start, end <= region$end)depth_cut <- quantile(windows$depth, 0.05, names = FALSE)cat(sprintf( "windows: %d, median depth %.2f, 5th percentile %.2f, maximum %.2f\n", nrow(windows), median(windows$depth), depth_cut, max(windows$depth)))cat(sprintf( "first window %.2f, last window %.2f\n", windows$depth[1], windows$depth[nrow(windows)]))
#' Read the positions of the false positives or false negatives of a caller.#'#' @param caller Caller name, the folder that holds the vcfeval files.#' @param outcome Either "fp" or "fn".#' @param eval_dir Folder that holds one subfolder per caller.#' @return A tibble with the caller, the outcome and the position.ReadErrors <- function(caller, outcome, eval_dir) { vcf <- readVcf(file.path(eval_dir, caller, paste0(outcome, ".vcf.gz"))) tibble(caller = caller, outcome = outcome, pos = start(vcf))}
error_grid <- expand_grid(caller = callers, outcome = c("fp", "fn"))errors <- bind_rows(Map( ReadErrors, error_grid$caller, error_grid$outcome, MoreArgs = list(eval_dir = eval_dir))) |> mutate( window_start = (pos - 1) %/% 500 * 500, to_end = pmin(pos - region$start, region$end - pos + 1) ) |> left_join( select(windows, window_start = start, depth), by = "window_start" )
error_summary <- errors |> mutate(caller = factor(caller, levels = callers)) |> group_by(caller, .drop = FALSE) |> summarise( errors = n(), near_end = sum(to_end <= 1000), low_depth = sum(depth < depth_cut), median_depth = median(depth) )print(as.data.frame(error_summary), row.names = FALSE)
# Positions that are an error for more than one caller.errors |> mutate(label = paste(caller, outcome)) |> group_by(pos, depth) |> summarise( n = n(), callers = paste(label, collapse = ", "), .groups = "drop" ) |> filter(n > 1) |> as.data.frame() |> print(row.names = FALSE)
# The gate compares these numbers with the Python tab.score_long <- metrics |> mutate( across(c(tp_baseline, fn, tp_call, fp), as.numeric), key_end = paste(caller, tolower(class), sep = "_") ) |> select(key_end, tp_baseline:f_measure) |> pivot_longer(-key_end, names_to = "metric")error_long <- error_summary |> select(caller, errors, near_end, low_depth) |> pivot_longer(-caller, names_to = "metric")parity_metrics <- c( setNames( as.list(score_long$value), paste(score_long$metric, score_long$key_end, sep = "_") ), setNames( as.list(error_long$value), paste(error_long$metric, error_long$caller, sep = "_") ), list(depth_cut = depth_cut))jsonlite::write_json( parity_metrics, "outputs/benchmarking_metrics_r.json", auto_unbox = TRUE, digits = NA)windows: 2000, median depth 58.62, 5th percentile 43.70, maximum 87.11first window 35.59, last window 39.36 caller errors near_end low_depth median_depth haplotypecaller 8 0 1 60.805 deepvariant 0 0 0 NA freebayes 10 0 3 46.525 bcftools 33 0 4 56.850 pos depth n callers 10009222 42.62 4 freebayes fp, freebayes fn, bcftools fp, bcftools fn 10023574 64.69 2 bcftools fp, bcftools fn 10056462 72.06 2 freebayes fp, freebayes fn 10065530 50.67 2 bcftools fp, bcftools fn 10082287 57.41 2 bcftools fp, bcftools fn 10107172 58.19 2 bcftools fp, bcftools fn 10116453 63.94 2 bcftools fp, bcftools fn 10236959 48.78 2 bcftools fp, bcftools fn 10260688 53.70 2 bcftools fp, bcftools fn 10282162 36.03 3 haplotypecaller fn, freebayes fn, bcftools fn 10353995 58.24 2 bcftools fp, bcftools fn 10512776 56.85 2 bcftools fp, bcftools fn 10888055 59.05 2 freebayes fp, freebayes fn 10960260 65.77 2 bcftools fp, bcftools fn 10997299 56.92 2 bcftools fp, bcftools fnregion = pd.read_csv( "/opt/data/region/chr20_region.bed", sep="\t", names=["chrom", "start", "end"],).iloc[0]windows = pd.read_csv( "/opt/data/qc/mosdepth/HG002.recal.regions.bed.gz", sep="\t", names=["chrom", "start", "end", "depth"],)windows = windows[ (windows["start"] >= region["start"]) & (windows["end"] <= region["end"])].reset_index(drop=True)depth_cut = windows["depth"].quantile(0.05)print( f"windows: {len(windows)}, median depth {windows['depth'].median():.2f}," f" 5th percentile {depth_cut:.2f}, maximum {windows['depth'].max():.2f}")print( f"first window {windows['depth'].iloc[0]:.2f}," f" last window {windows['depth'].iloc[-1]:.2f}")
def read_errors(caller, outcome, eval_dir): """Read the positions of the false positives or false negatives of a caller.
Args: caller: Caller name, the folder that holds the vcfeval files. outcome: Either "fp" or "fn". eval_dir: Folder that holds one subfolder per caller.
Returns: A list of (caller, outcome, position) tuples. """ path = f"{eval_dir}/{caller}/{outcome}.vcf.gz" return [(caller, outcome, variant.POS) for variant in cyvcf2.VCF(path)]
error_rows = [ row for caller in CALLERS for outcome in ["fp", "fn"] for row in read_errors(caller, outcome, EVAL_DIR)]errors = pd.DataFrame(error_rows, columns=["caller", "outcome", "pos"])errors["window_start"] = (errors["pos"] - 1) // 500 * 500errors["to_end"] = np.minimum( errors["pos"] - region["start"], region["end"] - errors["pos"] + 1)errors = errors.merge( windows[["start", "depth"]].rename(columns={"start": "window_start"}), on="window_start", how="left",)
errors["near_end"] = errors["to_end"] <= 1000errors["low_depth"] = errors["depth"] < depth_cuterrors["caller"] = pd.Categorical(errors["caller"], CALLERS)summary = errors.groupby("caller", observed=False).agg( errors=("pos", "size"), near_end=("near_end", "sum"), low_depth=("low_depth", "sum"), median_depth=("depth", "median"),)print(summary.reset_index().to_string(index=False))
# Positions that are an error for more than one caller.errors["label"] = errors["caller"].astype(str) + " " + errors["outcome"]shared_errors = errors.groupby(["pos", "depth"]).agg( n=("label", "size"), callers=("label", ", ".join)).reset_index()print(shared_errors[shared_errors["n"] > 1].to_string(index=False))
# The gate compares these numbers with the R tab.parity_metrics = {"depth_cut": float(depth_cut)}score_columns = [ "tp_baseline", "fn", "tp_call", "fp", "precision", "recall", "f_measure"]for _, row in metrics.iterrows(): for column in score_columns: key = f"{column}_{row['caller']}_{row['class'].lower()}" parity_metrics[key] = float(row[column])for caller, row in summary.iterrows(): for column in ["errors", "near_end", "low_depth"]: parity_metrics[f"{column}_{caller}"] = int(row[column])pathlib.Path("outputs/benchmarking_metrics_python.json").write_text( json.dumps(parity_metrics, indent=2) + "\n")windows: 2000, median depth 58.62, 5th percentile 43.70, maximum 87.11first window 35.59, last window 39.36 caller errors near_end low_depth median_depthhaplotypecaller 8 0 1 60.805 deepvariant 0 0 0 NaN freebayes 10 0 3 46.525 bcftools 33 0 4 56.850 pos depth n callers10009222 42.62 4 freebayes fp, freebayes fn, bcftools fp, bcftools fn10023574 64.69 2 bcftools fp, bcftools fn10056462 72.06 2 freebayes fp, freebayes fn10065530 50.67 2 bcftools fp, bcftools fn10082287 57.41 2 bcftools fp, bcftools fn10107172 58.19 2 bcftools fp, bcftools fn10116453 63.94 2 bcftools fp, bcftools fn10236959 48.78 2 bcftools fp, bcftools fn10260688 53.70 2 bcftools fp, bcftools fn10282162 36.03 3 haplotypecaller fn, freebayes fn, bcftools fn10353995 58.24 2 bcftools fp, bcftools fn10512776 56.85 2 bcftools fp, bcftools fn10888055 59.05 2 freebayes fp, freebayes fn10960260 65.77 2 bcftools fp, bcftools fn10997299 56.92 2 bcftools fp, bcftools fnThe ends cause no error. The first and last windows sit at 35.59 and 39.36 against a median of 58.62, and no error lies within 1 kb of either end. Low depth matters more. Of the 10 freebayes errors, 3 sit in a window below the cut of 43.70, against 1 of 8 for HaplotypeCaller and 4 of 33 for bcftools. The truth variant at 10,282,162 lies in a window at 36.03, and three callers miss it. Most bcftools errors come as a false positive and a false negative at one position, which is how vcfeval sees a wrong genotype or a wrong repeat length.
Aligning to chr20 alone
Section titled “Aligning to chr20 alone”The reads were cut from a whole genome alignment by position and aligned again to chr20 alone. BWA could move reads from the region elsewhere on chr20, and a read that belongs on another chromosome has nowhere else to go.
read -r _ region_start region_end < /opt/data/region/chr20_region.bed# Reads that BWA placed on chr20 more than 1 kb away from the region.zcat /opt/data/qc/mosdepth/HG002.md.regions.bed.gz \ | awk -v start="$region_start" -v end="$region_end" ' $2 >= start && $3 <= end {inside += $4 * ($3 - $2)} ($3 <= start - 1000 || $2 >= end + 1000) && $4 > 0 { windows++ away += $4 * ($3 - $2) } END { print "aligned bases in the region: " inside print "aligned bases in " windows " windows elsewhere: " away }'
# Calls inside and outside the BED, and the sites all four callers share.printf '%-16s %6s %7s\n' caller inside outsidefor caller in "${callers[@]}"; do bcftools view --targets-file "^$BED" "norm_$caller.vcf.gz" -Oz \ --output "outside_$caller.vcf.gz" --write-index=tbi printf '%-16s %6d %7d\n' "$caller" \ "$(bcftools view --no-header "inside_$caller.vcf.gz" | wc -l)" \ "$(bcftools view --no-header "outside_$caller.vcf.gz" | wc -l)"donefor side in inside outside; do files=() for caller in "${callers[@]}"; do files+=("${side}_$caller.vcf.gz") done bcftools isec --nfiles +1 --collapse none "${files[@]}" \ | awk -v side="$side" '{sites++} $5 == "1111" {shared++} END {print side ": " shared " of " sites " sites in all four"}'donealigned bases in the region: 58535570aligned bases in 113 windows elsewhere: 7870caller inside outsidehaplotypecaller 1611 223deepvariant 1610 218freebayes 1576 194bcftools 1613 227inside: 1540 of 1661 sites in all fouroutside: 116 of 338 sites in all fourThe first effect is small. After duplicate marking the region holds 58,535,570 aligned bases, and 113 windows more than 1 kb away hold 7,870. The second effect leaves no direct trace in these files, and its usual sign, a window at about twice the median depth, is absent, since the deepest window is at 87.11.
The BED shows where such trouble would sit. Each caller makes 194 to 227 calls outside it, and all four agree at only 116 of the 338 sites there, against 1,540 of 1,661 inside. GIAB leaves out the sequence it cannot resolve, and that is where misplaced reads and repeats cause disagreement. The precision and recall above describe the 977,839 bases that the truth covers and nothing else.
How benchmarking fails
Section titled “How benchmarking fails”- The DeepVariant training data notes list HG002 among the training samples of the WGS model and keep chr20 to chr22 out. This region was held out but the person was not, so a perfect score on HG002 is a best case.
- Without
--bed-regions, every call outside the benchmark regions counts as a false positive. - This region holds 234 truth indels, so one more missed indel moves indel recall by one part in 234. Benchmark a whole genome before you choose a caller on the third decimal place.
The code for this page is in the companion repository under
guides/dnaseq/benchmarking/.
Scientific references
Section titled “Scientific references”Danecek and colleagues, 2021 describe the development and the current features of SAMtools and BCFtools.
The RTG Tools repository is the software reference for vcfeval, because the project names no paper to cite.
Obenchain and colleagues, 2014 describe VariantAnnotation, the Bioconductor package for the exploration and annotation of genetic variants.
Further reading
Section titled “Further reading”The RTG vcfeval command reference defines the baseline, sample selection, and evaluation intervals. It explains why coordinate overlap alone is not a variant benchmark.
The DeepVariant r1.10 training-data record identifies the training samples and held-out chromosomes. That distinction matters when interpreting performance on HG002 chromosome 20.