Algorithmadvanced
Variant quality score recalibration
Also called VQSR.
Fit a Gaussian mixture to the annotations of calls at trusted sites, and score each call by its log likelihood ratio under good and bad models.
- Time
- O(I N K d + N log N) worst · averageO(N K d + N log N) best
- Space
- O(N K + K d) extra
- Where
- I = the number of EM iterations; K = the number of mixture components; N = the number of calls; d = the number of annotations
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark A. DePristo, Eric Banks, Ryan Poplin, 2011
Variant quality score recalibration (VQSR) filters a set of raw variant calls by learning what good calls look like. Each call comes with annotations, numbers such as the quality by depth (QD) and the strand bias (FS) that the caller computes from the reads. VQSR fits a Gaussian mixture model to the annotations of the calls at trusted sites, fits a second mixture to the calls that look least like them, and scores every call by the log ratio of the two densities. It then picks the score threshold that keeps a chosen share, such as 99%, of the calls at a set of truth sites. The method is the one of the GATK pipeline of DePristo et al. (2011); the code on this page is a reduced version, and the parts it leaves out are listed below.
In plain words
A variant caller finds many possible variants, and some are mistakes. Each one has a few measurements, such as how strong the evidence is per read and whether the reads all come from one strand.
Take the calls that sit at places where a variant is already known to exist. Their measurements show what real variants look like. Then take the calls that look least like those; they show what mistakes look like. Give every call a score: high if it looks like the real ones and not like the mistakes. Last, choose the lowest score you accept so that you keep, for example, 99 of every 100 known real variants. Calls below that score are marked as filtered.
The problem
Input. raw calls, each with an annotation vector ; a training subset of calls at trusted sites; a truth subset, often the same or a smaller one; and a target sensitivity .
Output. A score for every call, a threshold , and a filter decision , such that at least the share of the truth calls pass, and calls that look like artifacts score low.
For SNPs, GATK's documentation uses annotations such as QD, MQ, MQRankSum, ReadPosRankSum, FS and SOR, and training resources for humans such as HapMap, Omni and high-confidence 1000 Genomes sites. These are choices of the GATK workflow, not parts of the method.
The algorithm
VQSR(x_1, ..., x_N, training set T, truth set U, sensitivity σ)- 1
p+ ← a K+ component Gaussian mixture fitted by EM to {x_i : i ∈ T} - 2
λ_i ← ln p+(x_i) for every call i - 3
B ← the max(K-, ⌊βN⌋) calls of smallest λ_i - 4
p- ← a K- component Gaussian mixture fitted by EM to {x_i : i ∈ B} - 5
s_i ← λ_i - ln p-(x_i) for every call i - 6
τ ← the largest t such that at least the share σ of {s_i : i ∈ U} is at least t - 7
pass_i ← (s_i ≥ τ) for every call i - 8
return s, τ, pass
The mixtures have diagonal covariances, with a floor on each variance so that a component cannot shrink onto one point. EM starts from random calls as the means and the overall variance; the code fixes the seed. The share of calls that train the bad model is 10% by default in the code. The score is what GATK writes as VQSLOD, a log odds that the call is real against that it is an artifact, up to the ratio of the priors.
Line L6 sorts the truth scores in decreasing order and takes the entry at rank .
Example
The test of the code simulates 900 calls with two annotations, QD and FS. The 700 real calls are in two clusters, at QD about 12 and 25, with FS near 0 to 3. The 200 artifacts have QD about 4 and FS about 18. Half of the real calls, 356 of them, form both the training set and the truth set. With , and :
| target sensitivity | threshold | truth calls kept | real calls kept | artifacts kept |
|---|---|---|---|---|
| 90% | 37.56 | 321 of 356 | 625 of 700 | 0 of 200 |
| 99% | 31.77 | 353 of 356 | 693 of 700 | 0 of 200 |
| 100% | 27.16 | 356 of 356 | 700 of 700 | 0 of 200 |
The share of the real calls that pass tracks the share of the truth calls, because the truth calls are a random half of the real ones. In this simple case the two groups are well apart, and even the 100% tranche keeps no artifact. In real data the classes overlap, and the higher tranches let in more false calls.
A small case of line L6: truth scores 5, 1, 3, 2 and . Sorted in decreasing order they are 5, 3, 2, 1, and the entry at rank is 2, so keeps three of the four.
Correctness
The method is a heuristic classifier, so its correctness has two parts that can be proved. First, each EM iteration of lines L1 and L4 does not lower the likelihood of its data: the E step makes a lower bound tight by Jensen's inequality, and the M step maximizes the bound, also with the floor on the variances. So the fit converges to a stationary value of the likelihood, which may be a local maximum. With one component, the fit is the sample mean and variance. Second, the threshold of line L6 keeps at least the share of the truth calls, and no larger threshold does. The full proof is in proofs/correctness.md. That the filter removes artifacts is not a theorem; it depends on the annotations and the training sites.
Proof: EM never lowers the likelihood, and the threshold keeps the target share of the truth setfull
A call is a vector of annotation values. A diagonal Gaussian mixture with components has weights with , means and variances , and density
The procedure has three parts: fit a mixture to the training calls (line L1), fit a mixture to the calls that scores worst (lines L2 to L4), and score each call by (line L5). Then it picks the threshold (line L6) and filters (line L7). Lines L2, L3, L5 and L7 compute what they say, with log_density evaluating by the log-sum-exp identity with . What needs proof is the fitting step and the threshold.
The fitting step
fit_gmm runs EM on data , with each variance kept at least at a floor . Let .
Theorem 1. Each EM round gives .
Proof. The E step computes the responsibilities , where is the density of component . For any , write , with primes for the parameters . By Jensen's inequality for the concave logarithm,
with equality at , where the ratio inside is for every . So if the M step gives with , then .
The M step maximizes over the allowed parameters. With , the terms in the weights are , which under is largest at (Gibbs' inequality). The terms of component and coordinate are
For fixed this is largest at the weighted mean . With that mean and , the function increases for and decreases after, so its largest value under is at . These are the updates of the code. A component with below gets weight 0 and keeps its old mean and variance; its terms in are then times bounded numbers, which the code drops, and the change in is of the order of times the size of the terms.
The test of the implementation checks that the traced log-likelihood never drops by more than a relative . Theorem 1 does not say that EM finds the global maximum. The result depends on the start, which the code draws from a seeded random generator.
Corollary. With , the M step after the first round gives the sample mean and the sample variance with divisor (floored at ), and no later round changes them. These are the maximum likelihood estimates of one diagonal Gaussian.
Proof. With one component, for every , and the updates are the plain mean and variance. They do not depend on , so the next round gives the same values.
The threshold
For a list of scores of the truth-set calls and a target , let and let be the scores in decreasing order.
Theorem 2. tranche_threshold returns , which is the largest such that at least of the scores are . So the filter of line L7 keeps at least the share of the truth-set calls, and no higher threshold does.
Proof. The code sorts the scores in decreasing order and returns entry . The scores include , so there are at least of them. For , every score is among , since the others are at most , so there are at most of them. The kept share is at least .
The code subtracts inside the ceiling so that a product such as that comes out a little above 99 in floating point still gives .
What the guarantee covers. Theorem 2 is about the truth set, and it holds for any scores. The share of all true variants that pass, and the share of false calls that pass, depend on how well the two mixtures separate the calls, which no theorem here bounds. In the simulation test the two kinds of calls come from separated clusters, and both shares come out as wanted.
Cost
One EM round costs for points, so fitting costs for rounds. Scoring all calls costs , and the sorts cost .
Complexity
- Time. One EM iteration costs for points, so each fit costs for iterations. Line L3 and line L6 sort, . The fits dominate.
- Space. for the responsibilities of EM and for the mixture.
Properties
- Not deterministic in general. EM starts from random points and can reach different local maxima; fixing the seed makes a run repeatable.
- Calibrated to sensitivity, not to precision. The tranche fixes the share of truth calls kept. The share of false calls among those kept is not controlled, and it depends on how the artifacts fall in the annotation space.
- Needs many calls. The mixtures need enough training calls to fit, which is why GATK's documentation suggests hard filters for small call sets, such as a single exome.
- Ranking. The score orders the calls, so one fit gives every tranche.
Variants and improvements
The GATK tool differs from this page in several ways, which the code leaves out.
- Variational Bayes. GATK fits a Bayesian Gaussian mixture by variational inference, with priors on the means and covariances, which can switch off components it does not need (Bishop 2006, Section 10.2).
- Full covariances. GATK uses full covariance matrices; the code uses diagonal ones.
- Separate models. SNPs and indels get separate models with their own annotations and training sets.
- Annotation scaling. GATK centers and scales each annotation before the fit.
- Several tranches. GATK writes the filter names of several tranches, such as 90, 99, 99.9 and 100, so that the user can pick one later.
- Hard filters. The simple alternative is fixed thresholds on each annotation. GATK's documentation suggests, for SNPs, filtering QD < 2.0, QUAL < 30, SOR > 3.0, FS > 60.0, MQ < 40.0, MQRankSum < -12.5 and ReadPosRankSum < -8.0. These are its rules of thumb, not results of a model.
- Other classifiers. Any classifier trained on known sites can play the same role, for example a random forest or a one-class SVM on the good calls alone. Later GATK tools also score variants with neural networks.
When to use it
Use it on large germline call sets, a whole genome or many exomes, when a good set of known variant sites exists for the species. For small call sets or species without such resources, use hard filters. The choice of the tranche is a trade between sensitivity and precision; measure both on a benchmark with precision and recall if one is available.
Pitfalls
- Training bias. The good model learns what known variants look like. Real variants of a kind that the training sites lack, such as variants in hard regions, can score low.
- Annotations with a fixed value. An annotation that is the same for most calls, such as a mapping quality of 60, makes a component collapse onto it. The variance floor guards against this; dropping the annotation from the model is the other fix.
- Depth in exomes. Depth-based annotations behave differently in targeted data, where depth varies by target, so they are often left out for exomes.
- Truth sensitivity is not true sensitivity. The tranche is measured on the truth sites, which are easier than the average real variant, so the real sensitivity is lower.
- Reading VQSLOD as a probability. The score is a log density ratio, without calibrated priors, so it ranks calls but does not give the probability that a call is real.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variant-quality-score-recalibration/. The authors are listed in prov/DTZA1Z.jsonl.
"""A small version of variant quality score recalibration (VQSR).
Each call is a vector of annotation values (for example QD, FS and MQ). A
Gaussian mixture with diagonal covariances is fitted by EM to the calls that
lie in a training set of trusted variants. A second mixture is fitted to the
calls that the first model scores worst. The score of a call is the log
ratio ln p+(x) - ln p-(x) of the two densities (GATK calls it VQSLOD). The
filter threshold is the largest score that keeps at least the target share
of the truth-set calls.
Left out: the Bayesian (variational) mixture of GATK with its priors on the
means and covariances, full covariances, the separate SNP and indel models,
the annotation transforms, and the several tranches written to the VCF.
"""
from __future__ import annotations
import math
import random
from typing import List, Sequence, Tuple
Vector = Sequence[float]
Mixture = Tuple[List[float], List[List[float]], List[List[float]]] # weights, means, variances
VAR_FLOOR = 1e-3
def _lse(xs: Sequence[float]) -> float:
m = max(xs)
if m == -math.inf:
return m
return m + math.log(sum(math.exp(x - m) for x in xs))
def _log_normal(x: Vector, mean: Vector, var: Vector) -> float:
return -0.5 * sum(math.log(2 * math.pi * v) + (a - m) ** 2 / v for a, m, v in zip(x, mean, var))
def log_density(mix: Mixture, x: Vector) -> float:
"""ln p(x) under the mixture."""
w, mu, var = mix
return _lse([math.log(w[k]) + _log_normal(x, mu[k], var[k]) for k in range(len(w)) if w[k] > 0])
def log_likelihood(mix: Mixture, data: Sequence[Vector]) -> float:
return sum(log_density(mix, x) for x in data)
def fit_gmm(data: Sequence[Vector], k: int, rng: random.Random, iters: int = 100,
tol: float = 1e-9, trace: List[float] = None) -> Mixture:
"""A k-component diagonal Gaussian mixture fitted by EM, started from k random points."""
n, d = len(data), len(data[0])
if n < k:
raise ValueError("need at least k points")
mean_all = [sum(x[j] for x in data) / n for j in range(d)]
var_all = [max(VAR_FLOOR, sum((x[j] - mean_all[j]) ** 2 for x in data) / n) for j in range(d)]
mix: Mixture = ([1.0 / k] * k, [list(data[i]) for i in rng.sample(range(n), k)],
[list(var_all) for _ in range(k)])
prev = -math.inf
for _ in range(iters):
w, mu, var = mix
resp = [] # E step: the posterior share of each component in each point
total = 0.0
for x in data:
lp = [math.log(w[c]) + _log_normal(x, mu[c], var[c]) if w[c] > 0 else -math.inf for c in range(k)]
z = _lse(lp)
total += z
resp.append([math.exp(v - z) for v in lp])
if trace is not None:
trace.append(total)
if total - prev < tol * max(1.0, abs(total)):
break
prev = total
nk = [sum(r[c] for r in resp) for c in range(k)] # M step
new_w, new_mu, new_var = [], [], []
for c in range(k):
if nk[c] < 1e-12:
new_w.append(0.0)
new_mu.append(mu[c])
new_var.append(var[c])
continue
m = [sum(r[c] * x[j] for r, x in zip(resp, data)) / nk[c] for j in range(d)]
v = [max(VAR_FLOOR, sum(r[c] * (x[j] - m[j]) ** 2 for r, x in zip(resp, data)) / nk[c])
for j in range(d)]
new_w.append(nk[c] / n)
new_mu.append(m)
new_var.append(v)
mix = (new_w, new_mu, new_var)
return mix
def vqsr(calls: Sequence[Vector], training: Sequence[bool], truth: Sequence[bool], sensitivity: float,
k_pos: int = 3, k_neg: int = 2, bad_share: float = 0.1, seed: int = 0):
"""(scores, threshold, passed) for every call."""
rng = random.Random(seed)
pos = fit_gmm([x for x, t in zip(calls, training) if t], k_pos, rng) # @line L1
lp = [log_density(pos, x) for x in calls] # @line L2
n_bad = max(k_neg, int(bad_share * len(calls)))
worst = sorted(range(len(calls)), key=lambda i: lp[i])[:n_bad] # @line L3
neg = fit_gmm([calls[i] for i in worst], k_neg, rng) # @line L4
scores = [lp[i] - log_density(neg, calls[i]) for i in range(len(calls))] # @line L5
threshold = tranche_threshold([s for s, t in zip(scores, truth) if t], sensitivity) # @line L6
passed = [s >= threshold for s in scores] # @line L7
return scores, threshold, passed # @line L8
def tranche_threshold(truth_scores: Sequence[float], sensitivity: float) -> float:
"""The largest t such that at least the share sensitivity of truth_scores is >= t."""
if not truth_scores or not 0 < sensitivity <= 1:
raise ValueError("need truth scores and 0 < sensitivity <= 1")
s = sorted(truth_scores, reverse=True)
need = math.ceil(sensitivity * len(s) - 1e-12)
return s[need - 1]
test_variant_quality_score_recalibration.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variant-quality-score-recalibration/. The authors are listed in prov/DTZA1Z.jsonl.
import math
import os
import random
import pytest
from variant_quality_score_recalibration import (fit_gmm, log_density, tranche_threshold, vqsr)
def test_tranche_threshold_against_brute_force():
rng = random.Random(1)
for _ in range(300):
s = [rng.choice((-2.0, -1.0, 0.0, 0.5, 1.0, 3.0)) for _ in range(rng.randint(1, 12))]
sens = rng.choice((0.5, 0.9, 0.99, 1.0, 1 / 3))
need = math.ceil(sens * len(s) - 1e-12)
best = max(t for t in s if sum(v >= t for v in s) >= need)
assert tranche_threshold(s, sens) == best
assert tranche_threshold([5.0, 1.0, 3.0, 2.0], 0.75) == 2.0
with pytest.raises(ValueError):
tranche_threshold([], 0.9)
def test_one_component_is_the_sample_mean_and_variance():
rng = random.Random(2)
data = [(rng.gauss(4, 2), rng.gauss(-1, 0.5)) for _ in range(300)]
w, mu, var = fit_gmm(data, 1, random.Random(0))
for j in range(2):
m = sum(x[j] for x in data) / len(data)
v = sum((x[j] - m) ** 2 for x in data) / len(data)
assert abs(mu[0][j] - m) < 1e-9 and abs(var[0][j] - v) < 1e-9
assert w == [1.0]
def test_density_matches_direct_sum():
mix = ([0.3, 0.7], [[0.0, 1.0], [2.0, -1.0]], [[1.0, 4.0], [0.5, 0.25]])
x = (0.7, 0.2)
direct = 0.0
for w, m, v in zip(*mix):
dens = 1.0
for a, mm, vv in zip(x, m, v):
dens *= math.exp(-(a - mm) ** 2 / (2 * vv)) / math.sqrt(2 * math.pi * vv)
direct += w * dens
assert abs(log_density(mix, x) - math.log(direct)) < 1e-12
def test_em_never_lowers_the_likelihood():
rng = random.Random(3)
data = [(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(150)] + \
[(rng.gauss(5, 0.5), rng.gauss(3, 2)) for _ in range(100)]
for seed in range(4):
trace = []
fit_gmm(data, 3, random.Random(seed), iters=40, trace=trace)
assert all(b >= a - 1e-7 * abs(a) for a, b in zip(trace, trace[1:]))
def simulate(rng):
"""True variants in two clusters of high QD and low FS; artifacts at low QD and high FS."""
calls, real = [], []
for _ in range(700):
c = rng.random() < 0.6
calls.append((rng.gauss(12 if c else 25, 2), abs(rng.gauss(1, 1))))
real.append(True)
for _ in range(200):
calls.append((rng.gauss(4, 2), rng.gauss(18, 5)))
real.append(False)
return calls, real
def test_filters_artifacts_at_the_target_sensitivity():
rng = random.Random(4)
calls, real = simulate(rng)
training = [r and rng.random() < 0.5 for r in real]
scores, threshold, passed = vqsr(calls, training, training, 0.99, seed=1)
truth_kept = sum(p for p, t in zip(passed, training) if t) / sum(training)
assert truth_kept >= 0.99
real_kept = sum(p for p, r in zip(passed, real) if r) / sum(real)
junk_kept = sum(p for p, r in zip(passed, real) if not r) / (len(real) - sum(real))
assert real_kept > 0.97 and junk_kept < 0.05
assert all((s >= threshold) == p for s, p in zip(scores, passed))
if __name__ == "__main__":
raise SystemExit(pytest.main([os.path.abspath(__file__), "-q"]))
History
DePristo et al. (2011) described VQSR as the last step of their framework for variant discovery, after mapping, local realignment, base quality score recalibration and genotyping. It replaced hard thresholds on each annotation with a model fitted to the calls at known sites, and it introduced the tranches by truth sensitivity. It was a standard step of the GATK best practices for germline short variants for many years.
References
- Mark A. DePristo, Eric Banks, Ryan Poplin and others, A framework for variation discovery and genotyping using next-generation DNA sequencing data, Nature Genetics 43(5), 2011, pp. 491 to 498, the section on variant quality score recalibration and its supplementary methods (the Gaussian mixture on the annotations, the training sites, the score and the tranches by truth sensitivity)
- Christopher M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006, Chapter 9, Section 9.2 (mixtures of Gaussians and their fit by EM) and Section 10.2 (the variational mixture of Gaussians)
- Arthur P. Dempster, Nan M. Laird and Donald B. Rubin, Maximum likelihood from incomplete data via the EM algorithm, Journal of the Royal Statistical Society Series B 39(1), 1977, pp. 1 to 38 (the EM algorithm and the proof that each iteration does not lower the likelihood)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DTZA1Z Edit this page History Report an error Markdown