Algorithmadvanced
Base quality score recalibration
Also called BQSR.
Re-estimate base qualities from the observed mismatch rate at known non-variant sites, binned by reported quality, cycle and sequence context.
- Time
- Θ(n + m) worst · average · best
- Space
- Θ(k) extra
- Where
- k = the number of non-empty bins; m = the number of bases to recalibrate; n = the number of training bases
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark A. DePristo, Eric Banks, Ryan Poplin, 2011
Base quality score recalibration (BQSR) corrects the base qualities that the sequencer reports. A base of quality 30 should be wrong 1 time in 1000, but the quality tables of a machine are made for average conditions, so the real error rate drifts with the run, the lane, the position of the base in the read and the bases before it. BQSR counts the mismatches with the reference at sites that are taken to be free of true variants, in bins by read group, reported quality, cycle and context, and replaces each quality with the error rate observed in its bins. The method is the one of the GATK pipeline of DePristo et al. (2011), and the code on this page leaves out several parts of the GATK tool, listed below.
In plain words
The sequencer gives every base a score that says how much to trust it. Those scores are often a little wrong: some bases are worse than their score says, for example near the end of a read or after a G.
To fix them, look at many places in the genome where the sample is known to match the reference. There, every base that does not match is an error. Put the bases into groups by their score, by their place in the read and by the base before them, and count how often each group is wrong. Then give each base a new score that matches the error rate of its groups. Bases in a group that is wrong more often than its score says get a lower score.
The problem
Input. Mapped reads, after duplicate marking, and a set of known variant sites such as dbSNP. At each covered reference position that is not a known variant, each aligned base is one training observation : the read group , the reported quality , the cycle (the 0-based position of the base in the read), the context (the previous base and this one, as read; none for the first base), and if the base differs from the reference, else 0.
Output. A new integer quality for every base of every read, such that within each bin of the covariates the mean error probability that the new qualities give matches the observed mismatch rate.
For a bin with mismatches among observations, the empirical quality is
where the 1 and the 2 are one pseudo-mismatch and one pseudo-match, so that a bin with no mismatch gets a finite quality.
The algorithm
The model is additive on the Phred scale. With the number of observations of group and the sum of their reported error probabilities ,
where each is the gap between the empirical quality of a bin and what the terms before it predict.
FIT(observations)- 1
T ← empty count tables; S ← empty sums - 2
for each observation (g, q, c, x, μ) do - 3
add one base and μ mismatches to the bins (g), (g, q), (g, q, c) and, if x exists, (g, q, x) - 4
S[g] ← S[g] + 10^(-q/10) RECALIBRATE-BASE(T, g, q, c, x)- 5
Δ0 ← Q̂(g) - (-10 log10(S[g] / n_g)) - 6
Δ1 ← Q̂(g, q) - (q + Δ0), or 0 if the bin is empty - 7
Δ2 ← the sum over the covariates c and x of Q̂(g, q, ·) - (q + Δ0 + Δ1), each 0 if its bin is empty - 8
return q + Δ0 + Δ1 + Δ2 RECALIBRATE-READ(T, g, bases, qualities)- 9
for each base i, with cycle i and context bases[i-1..i] do r ← RECALIBRATE-BASE(T, g, q_i, i, x_i) - 10
q'_i ← round(r), clamped to the range 1 to 93
A base whose read group was not in the training data keeps its reported quality. Line L10 clamps to 93 because that is the largest quality that Phred+33 can print as one character.
Example
One read group with all bases reported as Q30. At cycle 0 there are 9998 training bases with 9 mismatches, and at cycle 1 there are 9998 with 99 mismatches. No contexts are used.
- The group has 108 mismatches in 19996 bases, so . The reported qualities predict , so .
- The bin is the whole group, so and .
- Cycle 0 has , so and the new quality is 30.
- Cycle 1 has , so and the new quality is 20.
The bases of cycle 0 were right to claim Q30, and those of cycle 1 were ten times worse than they claimed. A read "AC" with qualities 30, 30 comes out as 30, 20.
Correctness
The sums telescope. By the definition of , , so
With one covariate, the new quality is exactly the empirical quality of the base's bin. With two, it is the product of the two marginal error rates over the rate of the bin. If within a bin the true error rate is , with independent multiplicative effects of the cycle and the context, and the cycle and the context of a base are independent, then this quotient tends to with probability 1 as the training data grows, by the strong law of large numbers. The full proof is in proofs/correctness.md.
Proof: The recalibrated quality is a product of bin error rates, and it is exact for independent effectsfull
Fix one read group . The training data are base observations : reported quality , cycle , context (or none for the first base of a read) and for a mismatch with the reference, else 0. For a bin , a set of observations given by fixed values of some of , let and be its numbers of mismatches and of observations, and define
The bins are (all observations of ), , and .
Lemma 1 (counts). After lines L1 to L4, the table holds and for every bin with , and qsum holds .
Proof. Line L3 adds each observation to its four bins, and only to those: one count to , and to . Line L4 adds its reported error probability to the group sum. Observations with no context are not added to any context bin, and only those bins are skipped.
Lemma 2 (telescoping). For an observation whose bins , and are all non-empty in the training data,
Without a context, .
Proof. Write for the values of lines L5 to L7. By their definitions, , so . Then and . Line L8 returns , which is the sum in the claim. Without a context, is not added. The second form takes of both sides.
So in this plain version the global shift matters only for a base whose bin is empty in the training data. An empty or bin adds nothing, and the code falls back to the levels above. In GATK, each level is estimated with a prior centered on the level above, so the levels do not cancel in this way.
Theorem (consistency). Suppose that within the bin the true error probability of a base with cycle and context is , that the cycle and the context of a base are independent, and that every observation has a context. Let the number of training observations grow while the shares of the cycles and contexts stay fixed, and the observations stay independent given their covariates. Then tends to with probability 1 for every cycle and context with positive share.
Proof. Write and for the means over the cycles and contexts of the bin . The mismatch indicators of a bin are independent, with mean equal to the mean error probability of the bin. By the strong law of large numbers, tends to that mean, because the pseudo-counts and become negligible as . By independence of cycle and context, the three means are
By Lemma 2 and the continuity of the product and the quotient, the limit of is .
The hypotheses matter. If the effect of the cycle depends on the context, the model can only reach the product of the two marginal effects. If the cycle and the context are dependent, the marginal means no longer split as above. If the training sites contain true variants that are not masked, the mismatch counts include real differences, and the recalibrated qualities come out too low.
Rounding. recalibrate_read rounds to the nearest integer and clamps it to the range 1 to 93, the largest value that Phred+33 can print as one ASCII character. Rounding moves the quality by at most , which changes the error probability by a factor of at most .
Cost. Fitting costs expected time per observation with hash tables, so for observations, and the tables have one entry per non-empty bin. Each recalibrated base costs expected time.
Complexity
- Time. Fitting touches four bins per observation and recalibrating computes four empirical qualities per base. The bins have bounded keys (qualities up to 93, cycles up to the read length, 16 contexts, and the read groups), so arrays indexed by the key give time per step and in total. The code uses hash tables, which give the same bound in expectation.
- Space. for the non-empty bins, which is small: a few groups times 93 qualities times the read length.
- In practice. The cost is in reading the BAM file twice, once to count and once to write the new qualities.
Properties
- Exact for its model. The output is a fixed function of the counts. It is calibrated within each bin when only the cycle is used; with more covariates it is calibrated under the product model above.
- Deterministic. Given the training sites, there is no randomness.
- Two passes. All counts must be in before any base is recalibrated.
- Order of the qualities. The new quality can reorder the bases: a Q30 base at a bad cycle can get a lower quality than a Q25 base at a good one. That is the point of the method.
Variants and improvements
The GATK tool differs from this page in several ways, which the code leaves out.
- Priors on the deltas. GATK estimates each with a prior centered on the level above, so a bin with few observations stays near the coarser estimate instead of jumping to its own noisy rate. In the plain version on this page the levels cancel exactly, as above.
- Indel qualities. GATK also fits base insertion and base deletion qualities with the same covariates, which its indel-aware callers use.
- Cycle of the second read. GATK gives the cycles of the second read of a pair negative numbers, so the two reads get separate bins.
- Strand and context. For reverse-strand reads GATK takes the context in the direction of sequencing, by reverse complementing.
- Low-quality tails. Bases at the end of a read with a very low quality are not used as training data or changed.
- Binned output. To keep files small, the new qualities can be rounded to a few levels, the binning of modern Illumina instruments.
- Other recalibrators. Tools that train a statistical model, such as a logistic regression on the covariates, or that fit a monotone map from reported to observed quality, as in isotonic regression, solve the same problem.
When to use it
BQSR was a standard step of the GATK best practices for germline short variant calling, between duplicate marking and the variant caller, because callers such as Bayesian genotype calling put the base qualities straight into the genotype likelihoods. It needs a good set of known variant sites for the organism; without one, true variants count as errors. It matters less with data whose qualities are already well calibrated or binned to few levels, and with callers that learn their own error model from the reads.
Pitfalls
- Unmasked variants. A training site that is truly variant in the sample makes every alternate base count as an error. In a species with no variant database, a common workaround is to call variants once, mask the confident ones and recalibrate, sometimes for several rounds.
- Mixing read groups. Lanes and runs have their own error profiles. Wrong or missing read group tags merge them into one bin set.
- Too little data. Small targeted panels give sparse bins. The add-one counts bias the error rate of a small bin up, and a bin with few bases gives a noisy quality.
- Recalibrating twice. Running the tool on reads that were already recalibrated gives no new information and can shift the qualities further.
- Clamping and rounding. Qualities are stored as integers in 1 to 93; rounding moves the error rate by a factor of at most , which is about 1.12.
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/base-quality-score-recalibration/. The authors are listed in prov/X92GPF.jsonl.
"""A small version of base quality score recalibration (BQSR).
The input is a list of base observations at reference sites that are taken
to be free of true variants (the caller has already masked known variant
sites). Each observation is (group, q, cycle, context, mismatch): the read
group, the reported Phred quality, the 0-based position of the base in the
read, the dinucleotide made of the previous base and this base (None for the
first base), and True when the base differs from the reference.
The model is additive on the Phred scale, in the form of DePristo et al.
(2011): Q_recal = Q + d0 + d1(Q) + d2(Q, cycle) + d2(Q, context), where each
term is the gap between an empirical quality and what the terms before it
predict. The empirical quality of a bin is -10 log10((m + 1) / (n + 2)) for
m mismatches among n bases.
Left out: the Gaussian prior that GATK puts on each delta, the separate
indel qualities, the negative cycle numbers of second reads, the reverse
complement of the context for reverse-strand reads, and the masking of the
low-quality read tails.
"""
from __future__ import annotations
import math
from collections import namedtuple
from typing import Dict, Hashable, Iterable, List, Optional, Sequence, Tuple
Obs = namedtuple("Obs", ["group", "q", "cycle", "context", "mismatch"])
MAX_Q = 93
def empirical_q(m: int, n: int) -> float:
"""The Phred quality of m mismatches in n bases, with one pseudo-mismatch and one pseudo-match."""
return -10.0 * math.log10((m + 1.0) / (n + 2.0))
def covariates(bases: str) -> List[Tuple[int, Optional[str]]]:
"""(cycle, context) of each base of a read, in read order."""
return [(i, bases[i - 1:i + 1] if i > 0 else None) for i in range(len(bases))]
class Table:
"""The four count tables and the deltas of the fitted model."""
def __init__(self) -> None:
self.counts: Dict[Tuple, List[int]] = {}
self.qsum: Dict[Hashable, float] = {}
def _add(self, key: Tuple, mm: bool) -> None:
c = self.counts.setdefault(key, [0, 0])
c[0] += int(mm)
c[1] += 1
def eq(self, key: Tuple) -> Optional[float]:
c = self.counts.get(key)
return empirical_q(c[0], c[1]) if c else None
def d0(self, group: Hashable) -> float:
n = self.counts[("rg", group)][1]
reported = -10.0 * math.log10(self.qsum[group] / n)
return self.eq(("rg", group)) - reported
def d1(self, group: Hashable, q: int) -> float:
e = self.eq(("q", group, q))
return 0.0 if e is None else e - (q + self.d0(group))
def d2(self, group: Hashable, q: int, name: str, value: Hashable) -> float:
e = self.eq((name, group, q, value))
return 0.0 if e is None else e - (q + self.d0(group) + self.d1(group, q))
def fit(observations: Iterable[Obs]) -> Table:
t = Table() # @line L1
for o in observations: # @line L2
t._add(("rg", o.group), o.mismatch) # @line L3
t._add(("q", o.group, o.q), o.mismatch)
t._add(("cycle", o.group, o.q, o.cycle), o.mismatch)
if o.context is not None:
t._add(("context", o.group, o.q, o.context), o.mismatch)
t.qsum[o.group] = t.qsum.get(o.group, 0.0) + 10.0 ** (-o.q / 10.0) # @line L4
return t
def recalibrated_q(t: Table, group: Hashable, q: int, cycle: int, context: Optional[str]) -> float:
"""The new quality on the Phred scale, before rounding. Unseen bins add nothing."""
if ("rg", group) not in t.counts:
return float(q)
d0 = t.d0(group) # @line L5
d1 = t.d1(group, q) # @line L6
d2 = t.d2(group, q, "cycle", cycle) # @line L7
if context is not None:
d2 += t.d2(group, q, "context", context)
return q + d0 + d1 + d2 # @line L8
def recalibrate_read(t: Table, group: Hashable, bases: str, quals: Sequence[int]) -> List[int]:
"""New integer qualities for one read, rounded and clamped to 1..MAX_Q."""
out = []
for (cycle, ctx), q in zip(covariates(bases), quals):
r = recalibrated_q(t, group, q, cycle, ctx) # @line L9
out.append(max(1, min(MAX_Q, int(round(r))))) # @line L10
return out
test_base_quality_score_recalibration.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/base-quality-score-recalibration/. The authors are listed in prov/X92GPF.jsonl.
import math
import os
import random
import pytest
from base_quality_score_recalibration import (Obs, covariates, empirical_q, fit, recalibrate_read,
recalibrated_q)
def counted(group, q, cycle, context, n, m):
return [Obs(group, q, cycle, context, i < m) for i in range(n)]
def test_empirical_q():
assert abs(empirical_q(9, 9998) - 30.0) < 1e-12
assert abs(empirical_q(0, 0) - 10 * math.log10(2)) < 1e-12
def test_page_example():
obs = counted("g", 30, 0, None, 9998, 9) + counted("g", 30, 1, None, 9998, 99)
t = fit(obs)
assert abs(t.d0("g") - (-10 * math.log10(109 / 19998) - 30)) < 1e-12
assert abs(t.d0("g") - (-7.3644)) < 1e-4
assert abs(t.d1("g", 30)) < 1e-12
assert abs(recalibrated_q(t, "g", 30, 0, None) - 30) < 1e-9
assert abs(recalibrated_q(t, "g", 30, 1, None) - 20) < 1e-9
assert recalibrate_read(t, "g", "AC", [30, 30]) == [30, 20]
# A group or a bin that was never seen keeps the reported quality or adds nothing.
assert recalibrated_q(t, "other", 25, 0, None) == 25
assert abs(recalibrated_q(t, "g", 30, 7, None) - (30 + t.d0("g"))) < 1e-9
def test_one_covariate_gives_the_bin_quality():
# With no context, the sum telescopes to the empirical quality of the (q, cycle) bin.
rng = random.Random(3)
obs = [Obs("g", rng.choice((10, 20, 30)), rng.randrange(5), None, rng.random() < 0.02)
for _ in range(5000)]
t = fit(obs)
for q in (10, 20, 30):
for c in range(5):
key = ("cycle", "g", q, c)
if key in t.counts:
m, n = t.counts[key]
assert abs(recalibrated_q(t, "g", q, c, None) - empirical_q(m, n)) < 1e-9
def test_two_covariates_telescope():
# Q + d0 + d1 is the quality of the q bin, so the sum is Qe(q, cycle) + Qe(q, context) - Qe(q).
rng = random.Random(8)
obs = simulate(rng, 300)
t = fit(obs)
for o in obs[:2000]:
if o.context is None:
continue
def e(key):
m, n = t.counts[key]
return empirical_q(m, n)
want = e(("cycle", "lane1", o.q, o.cycle)) + e(("context", "lane1", o.q, o.context)) - e(("q", "lane1", o.q))
assert abs(recalibrated_q(t, o.group, o.q, o.cycle, o.context) - want) < 1e-9
def test_covariates():
assert covariates("ACG") == [(0, None), (1, "AC"), (2, "CG")]
def simulate(rng, n_reads, length=40):
"""Reads whose true error rate grows with the cycle and is higher after a G."""
obs = []
for _ in range(n_reads):
bases = "".join(rng.choice("ACGT") for _ in range(length))
for (cycle, ctx), b in zip(covariates(bases), bases):
q = rng.choice((20, 30, 40))
p = 10 ** (-q / 10) * (1 + cycle / 8) * (3 if ctx and ctx[0] == "G" else 1)
obs.append(Obs("lane1", q, cycle, ctx, rng.random() < min(p, 0.5)))
return obs
def log_loss(obs, qual):
s = 0.0
for o in obs:
p = 10 ** (-qual(o) / 10)
s -= math.log(p if o.mismatch else 1 - p)
return s / len(obs)
def test_recalibration_improves_calibration():
rng = random.Random(11)
train, test = simulate(rng, 4000), simulate(rng, 2000)
t = fit(train)
reported = log_loss(test, lambda o: o.q)
recal = log_loss(test, lambda o: max(1, min(93, round(recalibrated_q(t, o.group, o.q, o.cycle, o.context)))))
assert recal < reported
# The reported Q30 bases are near Q23 in truth. The add-one counts in the small cycle bins
# push the estimated error rate up a little; the bias shrinks as the training data grows.
q30 = [o for o in test if o.q == 30]
true_p = sum(1e-3 * (1 + o.cycle / 8) * (3 if o.context and o.context[0] == "G" else 1) for o in q30) / len(q30)
mean_p = sum(10 ** (-recalibrated_q(t, o.group, o.q, o.cycle, o.context) / 10) for o in q30) / len(q30)
assert 30 + 10 * math.log10(true_p) > 5
assert abs(-10 * math.log10(true_p) - -10 * math.log10(mean_p)) < 1.5
def test_clamping():
t = fit(counted("g", 40, 0, None, 50, 40))
assert recalibrate_read(t, "g", "A", [40]) == [1]
t = fit(counted("g", 40, 0, None, 50, 50))
assert recalibrated_q(t, "g", 40, 0, None) < 1 and recalibrate_read(t, "g", "A", [40]) == [1]
t = fit(counted("g", 2, 0, None, 10 ** 5, 0))
assert recalibrate_read(t, "g", "A", [2]) == [50]
if __name__ == "__main__":
raise SystemExit(pytest.main([os.path.abspath(__file__), "-q"]))
History
That base qualities should match the observed error rate goes back to phred, whose quality values were checked against the errors observed in reads of known sequence (Ewing and Green, 1998). For short reads, the recalibrator ran in the GATK framework of McKenna et al. (2010), and DePristo et al. (2011) described it as part of their framework: the covariates read group, reported quality, machine cycle and dinucleotide, the masking of the sites in dbSNP 129, and the additive model on the Phred scale. GATK 4 splits it into two tools, one that builds the tables and one that applies them.
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 base quality score recalibration and its supplementary methods (the covariates, the dbSNP masking and the additive model on the Phred scale)
- Aaron McKenna, Matthew Hanna, Eric Banks and others, The Genome Analysis Toolkit, a MapReduce framework for analyzing next-generation DNA sequencing data, Genome Research 20(9), 2010, pp. 1297 to 1303 (the GATK framework of walkers in which the recalibrator runs)
- Brent Ewing and Phil Green, Base-calling of automated sequencer traces using phred. II. Error probabilities, Genome Research 8(3), 1998, pp. 186 to 194 (quality values as calibrated error probabilities, checked against observed errors)
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 X92GPF Edit this page History Report an error Markdown