Filtering
A raw call set is sensitive on purpose, and it pays for that in false calls. Filtering marks the records whose annotations look like an artifact. This page runs three filtering routes on the same sarek run and counts what each one removes. In the first you choose the thresholds, in the second a trained network sets them, and in the third the caller has already decided.
Each route gets the same quick check, the transition to transversion ratio of the SNVs before and after. Whether a filter removed false calls and kept true ones is a question for the truth set, which the Benchmarking page answers with precision and recall.
Ti/Tv as a first check
Section titled “Ti/Tv as a first check”A transition swaps A and G or C and T, and every other substitution is a transversion. Each base has one possible transition and two possible transversions, so random substitutions give a ratio near 0.5, while Wang et al. 2015 put real human SNVs at about 3.0 in the exome and about 2.0 outside it. A filter that removes errors should push Ti/Tv up.
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.
VC=/opt/data/variant_callingHC="$VC/haplotypecaller/HG002.haplotypecaller.vcf.gz"TRUTH=/opt/data/truth/hg002_giab_v4_2_1_chr20_region.vcf.gz
# Print ts, tv and ts/tv for the biallelic SNVs of a VCF, the records with a# one-base REF and a one-base ALT. Extra arguments go to bcftools view.tstv() { bcftools view -m2 -M2 -i 'strlen(REF)=1 && strlen(ALT)=1' "$@" \ | bcftools stats - \ | awk -F'\t' '$1 == "TSTV" {print "ts=" $3, "tv=" $4, "ts/tv=" $5}'}
tstv "$TRUTH"tstv "$HC"ts=945 tv=429 ts/tv=2.20ts=996 tv=452 ts/tv=2.20The GIAB truth set for this region has 945 transitions and 429 transversions, a ratio of 2.20, and the raw HaplotypeCaller SNVs match it, so a filter on them has little room to raise the ratio. Ti/Tv also says nothing about indels.
Route 1: GATK hard filters with bcftools
Section titled “Route 1: GATK hard filters with bcftools”Hard filtering applies fixed thresholds to the caller’s annotations. GATK offers it for call sets too small to train VQSR, its statistical filter, as one sample on one megabase is, and gives separate starting thresholds for SNVs and indels in its hard filtering article and its filtering overview.
| Filter name | SNV threshold | Indel threshold |
|---|---|---|
QD2 |
QD < 2.0 |
QD < 2.0 |
QUAL30 |
QUAL < 30.0 |
QUAL < 30.0 |
SOR3 |
SOR > 3.0 |
not used |
FS60, FS200 |
FS > 60.0 |
FS > 200.0 |
MQ40 |
MQ < 40.0 |
not used |
MQRankSum-12.5 |
MQRankSum < -12.5 |
not used |
ReadPosRankSum-8, ReadPosRankSum-20 |
ReadPosRankSum < -8.0 |
ReadPosRankSum < -20.0 |
bcftools filter does the job of GATK VariantFiltration. One call per threshold with
-m+ appends each failed name to FILTER, so a record that fails two reads QD2;SOR3.
A record that lacks an annotation, such as a homozygous call with no MQRankSum, passes
that filter.
First split the raw file. Records with only SNV alleles take the SNV thresholds, and every record with an indel allele, the few mixed records included, takes the indel thresholds.
bcftools view --no-version -V indels,mnps,other -Oz -o snvs.vcf.gz "$HC"bcftools view --no-version -v indels,mnps,other -Oz -o indels.vcf.gz "$HC"bcftools view -H snvs.vcf.gz | wc -lbcftools view -H indels.vcf.gz | wc -l1450357bcftools filter --no-version -m+ -s QD2 -e 'INFO/QD < 2.0' snvs.vcf.gz \ | bcftools filter --no-version -m+ -s QUAL30 -e 'QUAL < 30.0' \ | bcftools filter --no-version -m+ -s SOR3 -e 'INFO/SOR > 3.0' \ | bcftools filter --no-version -m+ -s FS60 -e 'INFO/FS > 60.0' \ | bcftools filter --no-version -m+ -s MQ40 -e 'INFO/MQ < 40.0' \ | bcftools filter --no-version -m+ -s MQRankSum-12.5 \ -e 'INFO/MQRankSum < -12.5' \ | bcftools filter --no-version -m+ -s ReadPosRankSum-8 \ -e 'INFO/ReadPosRankSum < -8.0' -Oz -o snvs.hard.vcf.gzbcftools query -f '%FILTER\n' snvs.hard.vcf.gz | sort | uniq -c
# The clustered G to A calls from the Variant calling pagebcftools query -i 'POS >= 10915545 && POS <= 10915568' \ -f '%POS\t%QD\t%SOR\t%FILTER\n' snvs.hard.vcf.gz 1433 PASS 3 QD2 2 QD2;SOR3 12 SOR310915545 4.33 1.981 PASS10915549 4.33 1.981 PASS10915553 2.8 1.609 PASS10915559 2.11 2.215 PASS10915564 1.73 2.262 QD210915568 1.4 2.041 QD2bcftools filter --no-version -m+ -s QD2 -e 'INFO/QD < 2.0' indels.vcf.gz \ | bcftools filter --no-version -m+ -s QUAL30 -e 'QUAL < 30.0' \ | bcftools filter --no-version -m+ -s FS200 -e 'INFO/FS > 200.0' \ | bcftools filter --no-version -m+ -s ReadPosRankSum-20 \ -e 'INFO/ReadPosRankSum < -20.0' -Oz -o indels.hard.vcf.gzbcftools query -f '%FILTER\n' indels.hard.vcf.gz | sort | uniq -c
# Ti/Tv of the SNVs that pasststv -f PASS snvs.hard.vcf.gz 357 PASSts=984 tv=447 ts/tv=2.20The SNV filters remove 17 of 1,450 records, 12 for strand bias alone, 3 for a low QD and 2 for both, and the indel filters remove none of the 357. QUAL30 cannot fire, because HaplotypeCaller wrote nothing below its own threshold of 30, and no record trips MQ40, FS60 or the rank sum filters.
The QD2 cut is a fixed line through a continuum. The
Variant calling page flags six G to A calls in an
AAAG repeat, from 10,915,545 to 10,915,568. QD2 removes the two at QD 1.73 and 1.4 and
keeps the four with QD values from 2.11 to 4.33, so it takes the worst of a bad pattern
and leaves the rest. The Ti/Tv of the passing SNVs stays at 2.20.
Route 2: CNNScoreVariants and FilterVariantTranches
Section titled “Route 2: CNNScoreVariants and FilterVariantTranches”Sarek scores each HaplotypeCaller record with GATK CNNScoreVariants, marks the low
scorers with FilterVariantTranches, and writes the result as
HG002.haplotypecaller.filtered.vcf.gz. Both commands are in the header of that file.
CNN="$VC/haplotypecaller/HG002.haplotypecaller.filtered.vcf.gz"bcftools view --no-version -h "$CNN" \ | grep '^##GATKCommandLine=<ID=CNNScoreVariants' \ | grep -oE -e '--tensor-type [^ ]+' -e '--info-annotation-keys [^ ]+'bcftools view --no-version -h "$CNN" \ | grep '^##GATKCommandLine=<ID=FilterVariantTranches' \ | grep -oE -e '--info-key [^ ]+' -e '--snp-tranche [^ ]+' \ -e '--indel-tranche [^ ]+'bcftools view --no-version -h "$CNN" | grep -E '^##(FILTER|INFO=<ID=CNN_1D)'--tensor-type reference--info-annotation-keys MQ--info-annotation-keys DP--info-annotation-keys SOR--info-annotation-keys FS--info-annotation-keys QD--info-annotation-keys MQRankSum--info-annotation-keys ReadPosRankSum--info-key CNN_1D--snp-tranche 99.95--indel-tranche 99.4##FILTER=<ID=PASS,Description="All filters passed">##FILTER=<ID=CNN_1D_INDEL_Tranche_99.40_100.00,Description="INDEL truth resource sensitivity between 99.40 and 100.00 for info key CNN_1D">##FILTER=<ID=CNN_1D_SNP_Tranche_99.95_100.00,Description="SNP truth resource sensitivity between 99.95 and 100.00 for info key CNN_1D">##FILTER=<ID=LowQual,Description="Low quality">##INFO=<ID=CNN_1D,Number=1,Type=Float,Description="Log odds of being a true variant versus being false under the trained 1D Convolutional Neural Network">CNNScoreVariants runs a convolutional network over the reference sequence around each
record, combined with the seven annotations listed. GATK calls this the 1D model, since
--tensor-type reference reads no alignments, and its CNN_1D score is the log odds that
the record is a true variant. The
CNNScoreVariants source
notes that “The default models were trained on single-sample VCFs”, and this is one.
FilterVariantTranches places the SNV cut where 99.95 percent of the SNVs at sites in the resource files, dbSNP and the Mills indels here, score above it, and the indel cut at 99.4 percent. Records below the cut get the tranche name as their FILTER. The FilterVariantTranches source says these defaults “maximize the F1 score (the harmonic mean of sensitivity and precision) for whole genome human data but may need to be tweaked for different datasets”.
bcftools query -f '%FILTER\n' "$CNN" | sort | uniq -ctstv -f PASS "$CNN"
# The records the tranches removedbcftools query -e 'FILTER="PASS"' \ -f '%POS\t%REF\t%ALT\t%QUAL\t%CNN_1D\t%QD\t%SOR\t%MQ\t%MQRankSum\n' "$CNN" 7 CNN_1D_INDEL_Tranche_99.40_100.00 5 CNN_1D_SNP_Tranche_99.95_100.00 1795 PASSts=993 tv=450 ts/tv=2.2110020371 T G 1398.64 -6.483 20.27 0.968 43.24 -8.01510043652 CT C 72.6 -4.267 14.52 0.223 60 010224292 TGCAG T 55.6 -6.448 6.18 1.911 60 010224298 C T 52.64 -6 5.26 1.609 60 010432789 C CA 58.6 -4.197 7.33 0.148 60 010518532 TCC T 132.6 -4.906 5.1 0.962 59.66 -0.70410518535 TTCCTTCCTTCCTTC T 132.6 -5.357 5.1 0.962 59.67 -0.70410569175 A AT 122.6 -4.151 10.22 0.307 60 010579666 T C 80.64 -6.974 2.02 4.796 60 010899507 C T 434.03 -5.739 9.23 0.892 60 .10899557 TTTC T 73.6 -5.604 4.6 2.788 60 010938840 A C 93.64 -7.667 2.4 5.132 60 0The tranches remove 5 SNVs and 7 indels, and the passing SNVs reach a Ti/Tv of 2.21. The SNV at 10,938,840 looks bad on any measure, with a QD of 2.4 and an SOR of 5.132. The one at 10,020,371 passes every hard filter with a QUAL of 1398.64, but its MQ of 43.24 and MQRankSum of -8.015 say that its ALT reads map worse than its REF reads. The indels include the homopolymer insertion at 10,432,789 from the Variant calling page.
# Records removed by both routes, matched on position and allelesbcftools query -e 'FILTER="PASS"' -f '%CHROM:%POS:%REF:%ALT\n' "$CNN" \ | sort > cnn_removed.txtfor file in snvs.hard.vcf.gz indels.hard.vcf.gz; do bcftools query -e 'FILTER="PASS"' -f '%CHROM:%POS:%REF:%ALT\n' "$file"done | sort > hard_removed.txtcomm -12 hard_removed.txt cnn_removed.txtchr20:10579666:T:Cchr20:10938840:A:COnly the two SNVs with strand bias at 10,579,666 and 10,938,840 fall to both routes. The hard filters test one annotation at a time against a fixed line, while the network weighs all seven with the sequence context. A record a little off on several counts, like the one at 10,020,371, can fail one route and pass the other.
Route 3: the caller’s own FILTER column
Section titled “Route 3: the caller’s own FILTER column”DeepVariant and freebayes need no extra filtering tool, because their own output already says which records to keep.
DeepVariant
Section titled “DeepVariant”DV="$VC/deepvariant/HG002.deepvariant.vcf.gz"bcftools view --no-version -h "$DV" | grep '^##FILTER'bcftools query -f '%FILTER\t[%GT]\n' "$DV" | sort | uniq -c
# The highest GQ among NoCall records, then the lowest among RefCall recordsbcftools query -i 'FILTER="NoCall"' -f '[%GQ]\n' "$DV" | sort -n | tail -n 1bcftools query -i 'FILTER="RefCall"' -f '[%GQ]\n' "$DV" | sort -n | head -n 1
tstv "$DV"tstv -f PASS "$DV"##FILTER=<ID=PASS,Description="All filters passed">##FILTER=<ID=RefCall,Description="Genotyping model thinks this site is reference.">##FILTER=<ID=LowQual,Description="Confidence in this variant being real is below calling threshold.">##FILTER=<ID=NoCall,Description="Site has depth=0 resulting in no call."> 59 NoCall ./. 1079 PASS 0/1 669 PASS 1/1 40 PASS 1/2 163 RefCall 0/01920ts=1048 tv=514 ts/tv=2.04ts=988 tv=449 ts/tv=2.20DeepVariant writes every candidate site it evaluated, including the ones its network
called reference. Its file holds 1,788 PASS records, 163 RefCall records with the
genotype 0/0 and 59 NoCall records with ./.. The header describes NoCall as a site with depth 0, which
these records are not. In the
postprocess_variants source,
a RefCall whose GQ is below --cnn_homref_call_min_gq, 20 by default, becomes ./. with
the NoCall label, and the run agrees, with a highest NoCall GQ of 19 and a lowest RefCall
GQ of 20. Neither label is a quality filter, since the network has already decided these
sites carry no variant. Keeping the PASS records is the whole filtering step, and it lifts
Ti/Tv from 2.04 to 2.20.
freebayes
Section titled “freebayes”FB="$VC/freebayes/HG002.freebayes.vcf.gz"FB_QUAL30="$VC/freebayes/HG002.freebayes.filtered.vcf.gz"bcftools view --no-version -h "$FB_QUAL30" | grep '^##filter'bcftools view -H "$FB" | wc -lbcftools view -H "$FB_QUAL30" | wc -lbcftools view -H -i 'QUAL > 30' "$FB" | wc -lbcftools query -f '[%GT]\n' "$FB" | sort | uniq -cbcftools query -f '[%GT]\n' "$FB_QUAL30" | sort | uniq -c
tstv "$FB"tstv "$FB_QUAL30"##filter="QUAL > 30"213617131713 382 0/0 1058 0/1 639 1/1 57 1/2 1019 0/1 637 1/1 57 1/2ts=1054 tv=699 ts/tv=1.51ts=937 tv=426 ts/tv=2.20Sarek writes the freebayes calls twice. The raw file has 2,136 records, and 382 of them
are 0/0 sites where freebayes saw some ALT reads and still genotyped the sample as
reference. The second file is vcflib vcffilter with QUAL > 30, as its header records,
and the same expression in bcftools keeps the same 1,713 records. That filter deletes
records instead of marking them. It removes 423, every 0/0 among them, and Ti/Tv rises
from 1.51 to 2.20.
The routes side by side
Section titled “The routes side by side”The tabs repeat the work in R and Python. The first block applies the GATK thresholds to the raw HaplotypeCaller file, and the second builds one table for all four routes. The two languages print the same numbers, and those numbers match bcftools.
suppressPackageStartupMessages({ library(VariantAnnotation) library(ggplot2)})
vc_dir <- "/opt/data/variant_calling"hc_path <- file.path( vc_dir, "haplotypecaller", "HG002.haplotypecaller.vcf.gz")info_fields <- c("QD", "FS", "SOR", "MQ", "MQRankSum", "ReadPosRankSum")hc <- readVcf(hc_path, param = ScanVcfParam(info = info_fields, geno = NA))annotations <- data.frame(QUAL = qual(hc), as.data.frame(info(hc)))
# The GATK thresholds, in the order the bcftools chain applies them.snv_rules <- data.frame( name = c( "QD2", "QUAL30", "SOR3", "FS60", "MQ40", "MQRankSum-12.5", "ReadPosRankSum-8" ), field = c("QD", "QUAL", "SOR", "FS", "MQ", "MQRankSum", "ReadPosRankSum"), direction = c("<", "<", ">", ">", "<", "<", "<"), threshold = c(2, 30, 3, 60, 40, -12.5, -8))indel_rules <- data.frame( name = c("QD2", "QUAL30", "FS200", "ReadPosRankSum-20"), field = c("QD", "QUAL", "FS", "ReadPosRankSum"), direction = c("<", "<", ">", "<"), threshold = c(2, 30, 200, -20))
#' Flag the records that fail one hard filter.#'#' @param values The annotation values, NA where a record lacks one.#' @param direction "<" to fail values below the threshold, ">" above it.#' @param threshold The threshold value.#' @return A logical vector. A missing annotation never fails, as in#' bcftools.FailsRule <- function(values, direction, threshold) { if (direction == "<") { failed <- values < threshold } else { failed <- values > threshold } !is.na(failed) & failed}
#' Give each record the FILTER value that a set of hard filters assigns.#'#' @param annotations A data frame with one column per annotation.#' @param rules A data frame of filter names, fields, directions and#' thresholds.#' @return A character vector of PASS, or of failed names joined by ";".ApplyRules <- function(annotations, rules) { labels <- rep("", nrow(annotations)) for (i in seq_len(nrow(rules))) { failed <- FailsRule( annotations[[rules$field[i]]], rules$direction[i], rules$threshold[i] ) labels[failed] <- ifelse( labels[failed] == "", rules$name[i], paste(labels[failed], rules$name[i], sep = ";") ) } labels[labels == ""] <- "PASS" labels}
# VariantAnnotation reads the * allele as an empty string, so drop it before# typing each record.alt_width <- nchar(alt(hc))alt_width <- alt_width[alt_width > 0]is_snv <- nchar(ref(hc)) == 1 & all(alt_width == 1)
hard_filter <- character(nrow(annotations))hard_filter[is_snv] <- ApplyRules(annotations[is_snv, ], snv_rules)hard_filter[!is_snv] <- ApplyRules(annotations[!is_snv, ], indel_rules)
for (set in c("SNV", "indel")) { in_set <- if (set == "SNV") is_snv else !is_snv cat(sprintf("%s records: %d\n", set, sum(in_set))) counts <- table(hard_filter[in_set]) for (label in sort(names(counts), method = "radix")) { cat(sprintf(" %s %d\n", label, counts[[label]])) }}SNV records: 1450 PASS 1433 QD2 3 QD2;SOR3 2 SOR3 12indel records: 357 PASS 357import jsonfrom collections import Counterfrom pathlib import Path
import pandas as pdfrom cyvcf2 import VCF
VC_DIR = "/opt/data/variant_calling"HC_PATH = f"{VC_DIR}/haplotypecaller/HG002.haplotypecaller.vcf.gz"INFO_FIELDS = ["QD", "FS", "SOR", "MQ", "MQRankSum", "ReadPosRankSum"]
# The GATK thresholds, in the order the bcftools chain applies them.SNV_RULES = [ ("QD2", "QD", "<", 2.0), ("QUAL30", "QUAL", "<", 30.0), ("SOR3", "SOR", ">", 3.0), ("FS60", "FS", ">", 60.0), ("MQ40", "MQ", "<", 40.0), ("MQRankSum-12.5", "MQRankSum", "<", -12.5), ("ReadPosRankSum-8", "ReadPosRankSum", "<", -8.0),]INDEL_RULES = [ ("QD2", "QD", "<", 2.0), ("QUAL30", "QUAL", "<", 30.0), ("FS200", "FS", ">", 200.0), ("ReadPosRankSum-20", "ReadPosRankSum", "<", -20.0),]
def fails_rule(value, direction, threshold): """Check one annotation value against one hard filter.
Args: value: The annotation value, or None when the record lacks it. direction: "<" to fail values below the threshold, ">" above it. threshold: The threshold value.
Returns: True when the value fails. A missing value never fails, as in bcftools. """ if value is None: return False if direction == "<": return value < threshold return value > threshold
def apply_rules(record, rules): """Give one record the FILTER value that a set of hard filters assigns.
Args: record: A mapping from annotation name to value. rules: Tuples of filter name, field, direction and threshold.
Returns: "PASS", or the names of the failed filters joined by ";". """ failed = [ name for name, field, direction, threshold in rules if fails_rule(record[field], direction, threshold) ] return ";".join(failed) or "PASS"
def is_snv_record(ref, alts): """Check whether a record carries SNV alleles only.
Args: ref: The REF allele. alts: The ALT alleles of the record.
Returns: True when REF and every ALT other than * are one base long. """ called = [alt for alt in alts if alt != "*"] return len(ref) == 1 and all(len(alt) == 1 for alt in called)
records = []for variant in VCF(HC_PATH): record = {field: variant.INFO.get(field) for field in INFO_FIELDS} record["QUAL"] = variant.QUAL record["is_snv"] = is_snv_record(variant.REF, variant.ALT) rules = SNV_RULES if record["is_snv"] else INDEL_RULES record["hard_filter"] = apply_rules(record, rules) records.append(record)hc = pd.DataFrame(records)
for name, in_set in [("SNV", hc["is_snv"]), ("indel", ~hc["is_snv"])]: print(f"{name} records: {in_set.sum()}") counts = Counter(hc.loc[in_set, "hard_filter"]) for label in sorted(counts): print(f" {label} {counts[label]}")SNV records: 1450 PASS 1433 QD2 3 QD2;SOR3 2 SOR3 12indel records: 357 PASS 357#' Read the alleles and the FILTER value of every record in a VCF.#'#' @param path Path to a bgzipped VCF.#' @return A data frame with ref, alt and filter columns. Several ALT alleles#' are joined by commas, and the * allele reads as an empty string.ReadAlleles <- function(path) { vcf <- readVcf(path, param = ScanVcfParam(info = NA, geno = NA)) data.frame( ref = as.character(ref(vcf)), alt = unstrsplit(as(alt(vcf), "CharacterList"), sep = ","), filter = filt(vcf) )}
#' Compute Ti/Tv over the biallelic SNVs.#'#' @param alleles A data frame from ReadAlleles().#' @return Transitions divided by transversions among the records with a#' one-base REF and a single one-base ALT.TiTv <- function(alleles) { is_snv <- nchar(alleles$ref) == 1 & nchar(alleles$alt) == 1 change <- paste0(alleles$ref[is_snv], alleles$alt[is_snv]) transitions <- sum(change %in% c("AG", "GA", "CT", "TC")) transitions / (sum(is_snv) - transitions)}
hc_alleles <- ReadAlleles(hc_path)cnn_alleles <- ReadAlleles(file.path( vc_dir, "haplotypecaller", "HG002.haplotypecaller.filtered.vcf.gz"))dv_alleles <- ReadAlleles(file.path( vc_dir, "deepvariant", "HG002.deepvariant.vcf.gz"))fb_alleles <- ReadAlleles(file.path( vc_dir, "freebayes", "HG002.freebayes.vcf.gz"))fb_kept <- ReadAlleles(file.path( vc_dir, "freebayes", "HG002.freebayes.filtered.vcf.gz"))
# Each route pairs the records before the filter with the records it keeps.routes <- list( "HaplotypeCaller, hard filters" = list( hc_alleles, hc_alleles[hard_filter == "PASS", ] ), "HaplotypeCaller, CNN tranches" = list( cnn_alleles, cnn_alleles[cnn_alleles$filter == "PASS", ] ), "DeepVariant, FILTER column" = list( dv_alleles, dv_alleles[dv_alleles$filter == "PASS", ] ), "freebayes, QUAL > 30" = list(fb_alleles, fb_kept))route_keys <- c("hard_filters", "cnn_tranches", "deepvariant", "freebayes")
# The gate compares these values with the Python tab.metrics <- list( snv_records = sum(is_snv), snv_pass = sum(hard_filter[is_snv] == "PASS"), snv_qd2 = sum(grepl("QD2", hard_filter[is_snv])), snv_sor3 = sum(grepl("SOR3", hard_filter[is_snv])), indel_records = sum(!is_snv), indel_pass = sum(hard_filter[!is_snv] == "PASS"))
cat(sprintf( "%-30s%7s%7s%8s%12s%11s\n", "route", "before", "kept", "removed", "titv_before", "titv_kept"))for (i in seq_along(routes)) { before <- routes[[i]][[1]] kept <- routes[[i]][[2]] cat(sprintf( "%-30s%7d%7d%8d%12.2f%11.2f\n", names(routes)[i], nrow(before), nrow(kept), nrow(before) - nrow(kept), TiTv(before), TiTv(kept) )) metrics[[paste0(route_keys[i], "_before")]] <- nrow(before) metrics[[paste0(route_keys[i], "_kept")]] <- nrow(kept) metrics[[paste0(route_keys[i], "_titv_before")]] <- TiTv(before) metrics[[paste0(route_keys[i], "_titv_kept")]] <- TiTv(kept)}
dir.create("outputs", showWarnings = FALSE, recursive = TRUE)jsonlite::write_json( metrics, "outputs/filtering_metrics_r.json", auto_unbox = TRUE, digits = NA)route before kept removed titv_before titv_keptHaplotypeCaller, hard filters 1807 1790 17 2.20 2.20HaplotypeCaller, CNN tranches 1807 1795 12 2.20 2.21DeepVariant, FILTER column 2010 1788 222 2.04 2.20freebayes, QUAL > 30 2136 1713 423 1.51 2.20def read_alleles(path): """Read the alleles and the FILTER value of every record in a VCF.
Args: path: Path to a bgzipped VCF.
Returns: A data frame with ref, alt and filter columns. Several ALT alleles are joined by commas, and an empty FILTER reads as ".". """ rows = [ { "ref": variant.REF, "alt": ",".join(variant.ALT), "filter": ";".join(variant.FILTERS) or ".", } for variant in VCF(path) ] return pd.DataFrame(rows)
def ti_tv(alleles): """Compute Ti/Tv over the biallelic SNVs.
Args: alleles: A data frame from read_alleles().
Returns: Transitions divided by transversions among the records with a one-base REF and a single one-base ALT other than *. """ is_snv = ( (alleles["ref"].str.len() == 1) & (alleles["alt"].str.len() == 1) & (alleles["alt"] != "*") ) change = alleles.loc[is_snv, "ref"] + alleles.loc[is_snv, "alt"] transitions = change.isin(["AG", "GA", "CT", "TC"]).sum() return transitions / (is_snv.sum() - transitions)
hc_alleles = read_alleles(HC_PATH)cnn_alleles = read_alleles( f"{VC_DIR}/haplotypecaller/HG002.haplotypecaller.filtered.vcf.gz")dv_alleles = read_alleles(f"{VC_DIR}/deepvariant/HG002.deepvariant.vcf.gz")fb_alleles = read_alleles(f"{VC_DIR}/freebayes/HG002.freebayes.vcf.gz")fb_kept = read_alleles( f"{VC_DIR}/freebayes/HG002.freebayes.filtered.vcf.gz")
# Each route pairs the records before the filter with the records it keeps.routes = { "HaplotypeCaller, hard filters": ( hc_alleles, hc_alleles[hc["hard_filter"] == "PASS"] ), "HaplotypeCaller, CNN tranches": ( cnn_alleles, cnn_alleles[cnn_alleles["filter"] == "PASS"] ), "DeepVariant, FILTER column": ( dv_alleles, dv_alleles[dv_alleles["filter"] == "PASS"] ), "freebayes, QUAL > 30": (fb_alleles, fb_kept),}ROUTE_KEYS = ["hard_filters", "cnn_tranches", "deepvariant", "freebayes"]
# The gate compares these values with the R tab.snv_filter = hc.loc[hc["is_snv"], "hard_filter"]indel_filter = hc.loc[~hc["is_snv"], "hard_filter"]metrics = { "snv_records": len(snv_filter), "snv_pass": int((snv_filter == "PASS").sum()), "snv_qd2": int(snv_filter.str.contains("QD2").sum()), "snv_sor3": int(snv_filter.str.contains("SOR3").sum()), "indel_records": len(indel_filter), "indel_pass": int((indel_filter == "PASS").sum()),}
print( f"{'route':<30}{'before':>7}{'kept':>7}{'removed':>8}" f"{'titv_before':>12}{'titv_kept':>11}")for key, (route, (before, kept)) in zip(ROUTE_KEYS, routes.items()): print( f"{route:<30}{len(before):>7}{len(kept):>7}" f"{len(before) - len(kept):>8}" f"{ti_tv(before):>12.2f}{ti_tv(kept):>11.2f}" ) metrics[f"{key}_before"] = len(before) metrics[f"{key}_kept"] = len(kept) metrics[f"{key}_titv_before"] = float(ti_tv(before)) metrics[f"{key}_titv_kept"] = float(ti_tv(kept))
Path("outputs").mkdir(exist_ok=True)Path("outputs/filtering_metrics_python.json").write_text( json.dumps(metrics, indent=2) + "\n")route before kept removed titv_before titv_keptHaplotypeCaller, hard filters 1807 1790 17 2.20 2.20HaplotypeCaller, CNN tranches 1807 1795 12 2.20 2.21DeepVariant, FILTER column 2010 1788 222 2.04 2.20freebayes, QUAL > 30 2136 1713 423 1.51 2.20The route that removes the most records is not the strictest one. DeepVariant and freebayes start from files that hold the candidates they rejected, so most of what their filters remove was never a call. The two HaplotypeCaller routes start from 1,807 records that already cleared a QUAL of 30, and they remove 17 and 12. Every route ends at a Ti/Tv of 2.20 or 2.21, next to the 2.20 of the truth set. Ti/Tv can tell a file of rejected candidates from a call set, but it cannot rank four call sets that all look like real variants. Precision and recall can.
Where the SNV filters cut
Section titled “Where the SNV filters cut”The plot puts every SNV record of the raw file on its QD and SOR, the two annotations that removed records here, with the GATK thresholds as dashed lines.
snv_points <- data.frame( QD = annotations$QD[is_snv], SOR = annotations$SOR[is_snv], outcome = factor( ifelse(hard_filter[is_snv] == "PASS", "PASS", "filtered"), levels = c("PASS", "filtered") ))# Draw the filtered records last, so they sit on top.snv_points <- snv_points[order(snv_points$outcome), ]
filter_plot <- ggplot(snv_points, aes(x = QD, y = SOR, colour = outcome)) + geom_point(size = 1.4, alpha = 0.7) + geom_vline(xintercept = 2, linetype = "dashed", colour = "grey40") + geom_hline(yintercept = 3, linetype = "dashed", colour = "grey40") + scale_colour_manual( values = c(PASS = "#2a78d6", filtered = "#eb6834"), name = NULL ) + labs(x = "QD", y = "SOR") + theme_minimal(base_size = 12) + theme(panel.grid.minor = element_blank(), legend.position = "top")
dir.create("outputs", showWarnings = FALSE, recursive = TRUE)ggsave( "outputs/filtering_qd_sor_r.png", plot = filter_plot, width = 7, height = 5, dpi = 150, bg = "white")
import matplotlib.pyplot as plt
snv_points = hc[hc["is_snv"]]passed = snv_points["hard_filter"] == "PASS"
figure, axis = plt.subplots(figsize=(7, 5))axis.scatter( snv_points.loc[passed, "QD"], snv_points.loc[passed, "SOR"], s=8, alpha=0.7, color="#2a78d6", label="PASS",)axis.scatter( snv_points.loc[~passed, "QD"], snv_points.loc[~passed, "SOR"], s=8, alpha=0.9, color="#eb6834", label="filtered",)axis.axvline(2, linestyle="--", color="0.4", linewidth=1)axis.axhline(3, linestyle="--", color="0.4", linewidth=1)axis.set_xlabel("QD")axis.set_ylabel("SOR")axis.spines[["top", "right"]].set_visible(False)axis.legend(frameon=False, loc="upper right")figure.tight_layout()
Path("outputs").mkdir(exist_ok=True)figure.savefig("outputs/filtering_qd_sor_python.png", dpi=150)
The left cloud is the heterozygous calls. The right one, around a QD of 30, is the homozygous calls, whose QD values the QualByDepth cap from the Variant calling page moved there.
How filtering fails
Section titled “How filtering fails”- Thresholds carry the assumptions of the data they were set on. The GATK values are generic and the tranche defaults are tuned for whole genome human data, so an exome, a panel or another species needs its own look at the annotations, as in the plot above.
- A missing value passes. Most homozygous calls have no rank sums, so a rank sum filter looks applied while it skips them.
- Deleting is final and marking is not.
bcftools filter -skeeps every record and writes the reason into FILTER, whilebcftools view -f PASSand the freebayes route drop records, so keep the raw file. - Ti/Tv cannot judge indels, and indels are where the two HaplotypeCaller routes disagree, with no indel removed by the hard filters and seven by the tranches.
Next steps
Section titled “Next steps”The Benchmarking page scores these call sets against the GIAB truth set, which tells you how many of the removed records were real.
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 GATK QualByDepth implementation defines the depth-normalized quality annotation. It gives the denominator needed to interpret a QD threshold.
The BCFtools filtering reference defines expressions, filter labels, and allele-selection operations. Those rules determine how the hard-filter routes retain or label records.