Algorithm Search⌘K

Algorithmcore

Bayesian genotype calling

Also called Bayesian SNP calling.

Combine genotype likelihoods with a prior from allele frequency or heterozygosity, and call the genotype of highest posterior probability.

Time
Θ(n) worst · average · best
Space
Θ(1) extra
Where
n = the number of reads at the site
Properties
deterministicexactonlineiterative
Origin
Heng Li, Jue Ruan, Richard Durbin, 2008

Bayesian genotype calling decides the genotype of a sample at one site from the reads that cover it. It computes the genotype likelihood of each genotype from the bases and their qualities, multiplies it by a prior, normalizes by Bayes' theorem, and calls the genotype of highest posterior probability. The prior is what lets the method resist a few sequencing errors, and the posterior gives the confidence of the call on the Phred scale, the GQ and QUAL fields of VCF. Maq used this scheme in 2008, and it is the core of per-site callers such as bcftools and the GATK UnifiedGenotyper.

In plain words

At one place in the genome, a person can have the reference letter on both chromosomes, on one, or on neither. Each read that covers the place shows a letter, and each letter has a score that says how often such a letter is a mistake.

For each of the three choices, work out how likely the reads would be if that choice were true. Then weigh each choice by how common it is before you look at any reads: most places match the reference, so that choice starts far ahead. Pick the choice that comes out with the most weight, and report how much weight is left for the others. Little weight left means a sure call.

The problem

At a site with reference allele rr and one alternate allele aa, a diploid sample has genotype g∈{0,1,2}g \in \{0, 1, 2\}, the number of copies of aa. The data DD are the read bases and qualities of the pileup column, (b1,Q1),…,(bn,Qn)(b_1, Q_1), \dots, (b_n, Q_n). Given a prior π(g)\pi(g), find the posterior P(g∣D)P(g \mid D), the genotype g^\hat g that maximizes it, and

GQ=−10log⁡10(1−P(g^∣D)),QUAL=−10log⁡10P(g=0∣D).\mathrm{GQ} = -10 \log_{10}\bigl(1 - P(\hat g \mid D)\bigr), \qquad \mathrm{QUAL} = -10 \log_{10} P(g = 0 \mid D).

The model is that of genotype likelihood: a base of quality QQ has error rate e=10−Q/10e = 10^{-Q/10}, it shows the true allele with probability 1−e1 - e and each other base with probability e/3e/3, each read comes from either chromosome with probability 1/21/2, and the reads are independent given gg.

Priors. Two priors are common.

  • From the heterozygosity. With θ\theta the expected rate of differences between two chromosomes, π=(1−3θ/2,θ,θ/2)\pi = (1 - 3\theta/2, \theta, \theta/2). GATK's default heterozygosity is θ=0.001\theta = 0.001, about the rate for humans.
  • From an allele frequency. If the frequency of aa in the population is ff, the Hardy-Weinberg prior is π=((1−f)2,2f(1−f),f2)\pi = ((1-f)^2, 2f(1-f), f^2).

The first prior follows from the neutral site frequency spectrum for three sequences, the reference and the two chromosomes of the sample. A site is segregating with one derived copy with probability about θ\theta and with two with probability about θ/2\theta/2. Given one derived copy, it is on a chromosome of the sample with probability 2/32/3, which makes a heterozygote, and on the reference with probability 1/31/3, which makes the sample homozygous for aa. Given two, they are on the reference and one chromosome with probability 2/32/3, a heterozygote, and on both chromosomes with probability 1/31/3. So P(g=1)=23θ+23⋅θ2=θP(g = 1) = \frac{2}{3}\theta + \frac{2}{3}\cdot\frac{\theta}{2} = \theta and P(g=2)=13θ+13⋅θ2=θ/2P(g = 2) = \frac{1}{3}\theta + \frac{1}{3}\cdot\frac{\theta}{2} = \theta/2, to first order in θ\theta.

The algorithm

The sums are in logarithms, with the log-sum-exp trick, so that a deep pileup does not underflow.

  1. BAYES-GENOTYPE(pileup, r, a, π)
  2. 1λ[g] ← ln π(g) for g = 0, 1, 2
  3. 2for each read (b, Q) in the pileup do
  4. 3e ← 10^(-Q/10)
  5. 4for g ← 0 to 2 do
  6. 5λ[g] ← λ[g] + ln((g/2) P(b | a, e) + (1 - g/2) P(b | r, e))
  7. 6z ← LOG-SUM-EXP(λ[0], λ[1], λ[2])
  8. 7post[g] ← exp(λ[g] - z) for g = 0, 1, 2
  9. 8ĝ ← the g of largest λ[g], ties to the smaller g
  10. 9w ← LOG-SUM-EXP(λ[g] for g ≠ ĝ) - z
  11. 10return ĝ, post, GQ = -10 w / ln 10, QUAL = -10 (λ[0] - z) / ln 10

At line L6, λ[g]=ln⁡π(g)+ln⁡P(D∣g)\lambda[g] = \ln \pi(g) + \ln P(D \mid g), so zz is ln⁡P(D)\ln P(D) and line L7 gives the posterior. Line L9 is the log of 1−P(g^∣D)1 - P(\hat g \mid D), computed from the other two terms instead of by a subtraction, which keeps its precision when the call is sure. If the alternate allele is not given, the code takes the most common non-reference base of the pileup, with ties in ACGT order.

Example

Six reads at a site with r=Ar = A and a=Ga = G: A at qualities 30, 30, 20, and G at 30, 20, 10. The genotype likelihoods are log⁡10P(D∣g)=−7.4366,−1.8428,−9.4819\log_{10} P(D \mid g) = -7.4366, -1.8428, -9.4819, which is PL 56, 0, 76.

With the prior from θ=0.001\theta = 0.001, π=(0.9985,0.001,0.0005)\pi = (0.9985, 0.001, 0.0005), the posterior is

gg genotype posterior
0 A/A 0.002538
1 A/G 0.997462
2 G/G 1.14×10−81.14 \times 10^{-8}

The call is A/G with GQ=25.96\mathrm{GQ} = 25.96. Here QUAL is almost the same, 25.96, because nearly all of the weight that is not on A/G is on A/A. The likelihood ratio of A/G to A/A is about 4×1054 \times 10^5, but the prior ratio is 0.001/0.99850.001 / 0.9985, so the posterior ratio is about 390.

With the Hardy-Weinberg prior for f=0.3f = 0.3, a common variant, π=(0.49,0.42,0.09)\pi = (0.49, 0.42, 0.09) and the call is A/G with GQ=55.26\mathrm{GQ} = 55.26. The same reads give a surer call when the variant is known to be common.

Two more cases, with the θ\theta prior:

  • One G among ten Q30 reads. The call is A/A, with a posterior of 0.002932 for A/G. One base with a 1 in 1000 error rate, against nine reference bases, is not enough to overturn a prior of 1000 to 1 against the heterozygote.
  • Two G reads at Q30. The posteriors are 0.000148, 0.333432 and 0.666420, and the call is G/G with GQ=4.77\mathrm{GQ} = 4.77, but QUAL=38.29\mathrm{QUAL} = 38.29. The site is surely variant, but two reads cannot tell G/G from A/G.

Correctness

For one read, the probability of its base given gg is the mixture in line L5, by the law of total probability over the chromosome it came from. The reads are independent given gg, so the likelihood is the product of the read terms, which line L5 adds in logarithms. The product of the mixtures is also the sum, over all 2n2^n ways to assign the reads to the two chromosomes, of the probability of the bases under that assignment; the test checks the code against that brute force sum. After the loop, λ[g]=ln⁡(π(g)P(D∣g))\lambda[g] = \ln(\pi(g) P(D \mid g)), so lines L6 and L7 give the posterior by Bayes' theorem, line L8 the maximum a posteriori genotype, and lines L9 and L10 the stated GQ and QUAL. The full proof, which needs 0<e<10 < e < 1 for every read, is in proofs/correctness.md.

Proof: The genotype caller returns the posterior of each genotype and its MAP genotypefull

Fix a biallelic site with reference allele rr and alternate allele a≠ra \ne r in a diploid sample. The data DD are nn pairs (bi,Qi)(b_i, Q_i): the base bib_i that read ii shows at the site and its Phred quality, with ei=10−Qi/10e_i = 10^{-Q_i/10}. The genotype g∈{0,1,2}g \in \{0, 1, 2\} is the number of chromosomes that carry aa. The model has three parts.

  1. Read ii comes from one of the two chromosomes, each with probability 1/21/2, independently of the other reads.
  2. Given the allele xx of that chromosome, the read shows bib_i with probability P(bi∣x)=1−eiP(b_i \mid x) = 1 - e_i if bi=xb_i = x and ei/3e_i / 3 otherwise.
  3. Given gg, the reads are independent, and gg has the prior π=(π0,π1,π2)\pi = (\pi_0, \pi_1, \pi_2) with πg≥0\pi_g \ge 0 and ∑gπg=1\sum_g \pi_g = 1.

We assume 0<ei<10 < e_i < 1 in floating point, that is, Qi>0Q_i > 0 and not so large that eie_i underflows to 0. Then every factor below has a finite logarithm.

Lemma 1 (one read). P(bi∣g)=g2P(bi∣a)+(1−g2)P(bi∣r)P(b_i \mid g) = \frac{g}{2} P(b_i \mid a) + \bigl(1 - \frac{g}{2}\bigr) P(b_i \mid r).

Proof. Under genotype gg, gg of the two chromosomes carry aa and 2−g2 - g carry rr. By part 1 the read comes from a chromosome with aa with probability g/2g/2, and from one with rr with probability 1−g/21 - g/2. The law of total probability over the two cases gives the formula. □\square

Lemma 2 (all reads). P(D∣g)=∏i=1nP(bi∣g)P(D \mid g) = \prod_{i=1}^{n} P(b_i \mid g). The same value is the sum, over the 2n2^n maps cc from the reads to the two chromosomes, of ∏i12P(bi∣xc(i))\prod_i \frac12 P(b_i \mid x_{c(i)}), where x1,x2x_1, x_2 are the alleles of the chromosomes.

Proof. The first form is part 3 with Lemma 1. For the second form, the sum of a product over independent choices c(1),…,c(n)c(1), \ldots, c(n), where factor ii depends only on c(i)c(i), is the product of the sums: ∑c∏ifi(c(i))=∏i∑j∈{1,2}fi(j)\sum_c \prod_i f_i(c(i)) = \prod_i \sum_{j \in \{1, 2\}} f_i(j). With fi(j)=12P(bi∣xj)f_i(j) = \frac12 P(b_i \mid x_j), the inner sum is Lemma 1. □\square

The brute-force test of the implementation computes the second form.

Lemma 3 (loop invariant). After lines L2 to L5 have run for the first jj reads, lp[g]=ln⁡πg+∑i≤jln⁡P(bi∣g)\mathrm{lp}[g] = \ln \pi_g + \sum_{i \le j} \ln P(b_i \mid g) for each gg, with ln⁡0=−∞\ln 0 = -\infty.

Proof. Line L1 sets lp[g]=ln⁡πg\mathrm{lp}[g] = \ln \pi_g, which is the claim for j=0j = 0. Line L3 computes eje_j, and line L5 adds ln⁡(g2P(bj∣a)+(1−g2)P(bj∣r))\ln\bigl(\frac g2 P(b_j \mid a) + (1 - \frac g2) P(b_j \mid r)\bigr), which is ln⁡P(bj∣g)\ln P(b_j \mid g) by Lemma 1. The term is finite: P(bj∣a)P(b_j \mid a) and P(bj∣r)P(b_j \mid r) are each 1−ej1 - e_j or ej/3e_j / 3, both positive for 0<ej<10 < e_j < 1, and the term is a mixture of the two with weights that sum to 1. □\square

So after the loop, lp[g]=ln⁡(πgP(D∣g))=ln⁡P(g,D)\mathrm{lp}[g] = \ln\bigl(\pi_g P(D \mid g)\bigr) = \ln P(g, D) by Lemma 2.

Theorem. Line L7 gives post[g]=P(g∣D)\mathrm{post}[g] = P(g \mid D) for each gg. Line L8 returns a genotype of largest posterior, the smallest one if several tie. The returned GQ is −10log⁡10(1−P(g^∣D))-10 \log_{10}\bigl(1 - P(\hat g \mid D)\bigr) for the returned genotype g^\hat g, and QUAL is −10log⁡10P(g=0∣D)-10 \log_{10} P(g = 0 \mid D).

Proof. Line L6 computes z=ln⁡∑gelp[g]z = \ln \sum_g e^{\mathrm{lp}[g]} by the log-sum-exp identity ln⁡∑gexg=m+ln⁡∑gexg−m\ln \sum_g e^{x_g} = m + \ln \sum_g e^{x_g - m} with m=max⁡gxgm = \max_g x_g, which holds for any real mm. Since at least one πg>0\pi_g > 0 and every likelihood is positive, mm is finite. So z=ln⁡∑gP(g,D)=ln⁡P(D)z = \ln \sum_g P(g, D) = \ln P(D), and by Bayes' theorem elp[g]−z=P(g,D)/P(D)=P(g∣D)e^{\mathrm{lp}[g] - z} = P(g, D) / P(D) = P(g \mid D), which is line L7.

The posterior is elp[g]−ze^{\mathrm{lp}[g] - z} with the same zz for each gg, and x↦ex−zx \mapsto e^{x - z} is increasing, so the order of the posteriors is the order of the values lp[g]\mathrm{lp}[g]. Line L8 takes the largest lp[g]\mathrm{lp}[g] and breaks ties by the key −g-g, which picks the smallest gg.

Line L9 computes w=ln⁡∑g≠g^elp[g]−z=ln⁡∑g≠g^P(g∣D)=ln⁡(1−P(g^∣D))w = \ln \sum_{g \ne \hat g} e^{\mathrm{lp}[g]} - z = \ln \sum_{g \ne \hat g} P(g \mid D) = \ln\bigl(1 - P(\hat g \mid D)\bigr), and GQ is −10w/ln⁡10=−10log⁡10(1−P(g^∣D))-10 w / \ln 10 = -10 \log_{10}(1 - P(\hat g \mid D)). If every other genotype has prior 0, then w=−∞w = -\infty and GQ is +∞+\infty, the limit of the formula. In the same way QUAL is −10(lp[0]−z)/ln⁡10=−10log⁡10P(g=0∣D)-10 (\mathrm{lp}[0] - z) / \ln 10 = -10 \log_{10} P(g = 0 \mid D), and +∞+\infty if π0=0\pi_0 = 0. □\square

Numerical range. The code never forms P(D∣g)P(D \mid g) itself. Each lp[g]\mathrm{lp}[g] is a sum of nn logarithms, each between ln⁡(emin⁡/3)\ln(e_{\min}/3) and 0, so it stays a finite double for any pileup that real data give, and the subtraction of mm in log-sum-exp keeps each exponent at most 0. So a pileup of thousands of reads, whose likelihood is below the smallest positive double, still gives correct posteriors.

Cost. Each read costs a constant number of operations for the three genotypes, so the time is Θ(n)\Theta(n) and the extra space is O(1)O(1).

Choice of the alternate allele. call_site picks aa as the most common base other than rr in the pileup, before the posterior is computed. The theorem is about the posterior given that choice. It is not the posterior over all three possible alternate alleles, which would need the ten genotypes of four alleles.

Complexity

  • Time. Θ(n)\Theta(n) per site: three log terms per read. A genome at 30x has about 3×1093 \times 10^9 sites times 30 reads, so callers first skip the sites where no read differs from the reference by more than a threshold.
  • Space. Θ(1)\Theta(1) beyond the pileup, since the reads can be added one at a time.
  • More alleles. With kk alleles, a diploid has k(k+1)/2k(k+1)/2 genotypes, and the cost is Θ(nk2)\Theta(n k^2).

Properties

  • Exact for its model. The posterior is computed exactly, up to rounding. The model itself, independent reads with calibrated qualities, is an approximation.
  • Incremental. Each read adds one term to each λ[g]\lambda[g], so a caller can update the call as reads arrive.
  • Prior dominance at low depth. With no reads, the posterior is the prior and the call is A/A. As the depth grows, the likelihood dominates and the prior matters less.
  • Phred outputs. GQ uses the posterior of the called genotype. GATK writes GQ in another way, as the gap between the two smallest PL values capped at 99, so values from two callers need care.

Variants and improvements

  • Multi-sample calling. Li (2011) estimates the allele frequency ff of a site from the genotype likelihoods of all samples by expectation maximization and uses it in a Hardy-Weinberg prior, so samples with few reads borrow strength from the others.
  • Mapping quality. Many callers mix in the chance that the read is misplaced, or cap each base quality at the mapping quality of the read.
  • Indels. Per-site callers can score indels as alleles with the probability of the read given each allele, but haplotype-based calling does this better, with a pair HMM over candidate haplotypes.
  • Dependent errors. Some callers give less weight to repeated errors on the same strand at the same site, which the independent model overcounts.
  • Somatic and pooled samples. Allele fractions other than 0, 1/2 and 1 replace the three genotypes; see somatic variant calling.

When to use it

Use it for SNVs at sites where the reads are well aligned, for one or many samples, and when you need a calibrated posterior. It is fast and simple, and it is the reference point for other callers. For indels and for clusters of nearby variants, prefer haplotype-based callers. At low coverage, pass the likelihoods to population methods instead of calling hard genotypes.

Pitfalls

  • Wrong qualities. Overstated base qualities make errors look like evidence; run base quality score recalibration first.
  • Duplicates. PCR copies are not independent reads; mark them with duplicate marking.
  • Misaligned indels. Reads aligned across an indel can show false SNVs near it.
  • The prior in a population with another rate. A fixed θ=0.001\theta = 0.001 is set for humans. Another species, or a known common variant, needs another prior.
  • GQ versus QUAL. A site can be surely variant while the genotype is unsure, as in the two-read example.

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.

bayesian_genotype_calling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayesian-genotype-calling/. The authors are listed in prov/YB8C7J.jsonl.
"""Bayesian genotype calling at one biallelic site of a diploid sample.

A pileup is a list of (base, quality) pairs: the base that each read shows
at the site and its Phred base quality. The genotype g is the number of
copies of the alternate allele, 0, 1 or 2. The error model is the usual one
of the genotype likelihood page: a base is read correctly with probability
1 - e, and as each of the three other bases with probability e / 3, where
e = 10^(-Q/10). Reads are independent given the genotype, and each read
comes from either chromosome with probability 1/2.

All sums are in log space, so a deep pileup does not underflow.
"""

from __future__ import annotations

import math
from collections import namedtuple
from typing import List, Sequence, Tuple

from biostoch import logsumexp

Call = namedtuple("Call", ["genotype", "posterior", "gq", "qual", "alt"])

_LN10 = math.log(10.0)


def base_prob(base: str, allele: str, e: float) -> float:
    """P(read shows base | the read comes from a chromosome with allele)."""
    return 1.0 - e if base == allele else e / 3.0


def prior_theta(theta: float) -> List[float]:
    """The prior (1 - 3 theta / 2, theta, theta / 2) from the population mutation rate."""
    if not 0.0 <= theta <= 2.0 / 3.0:
        raise ValueError("need 0 <= theta <= 2/3")
    return [1.0 - 1.5 * theta, theta, theta / 2.0]


def prior_hwe(f: float) -> List[float]:
    """The Hardy-Weinberg prior ((1 - f)^2, 2 f (1 - f), f^2) for alternate allele frequency f."""
    if not 0.0 <= f <= 1.0:
        raise ValueError("need 0 <= f <= 1")
    return [(1.0 - f) ** 2, 2.0 * f * (1.0 - f), f * f]


def log_likelihoods(pileup: Sequence[Tuple[str, float]], ref: str, alt: str) -> List[float]:
    """ln P(D | g) for g = 0, 1, 2."""
    ll = [0.0, 0.0, 0.0]
    for b, q in pileup:
        e = 10.0 ** (-q / 10.0)
        pr, pa = base_prob(b, ref, e), base_prob(b, alt, e)
        for g in range(3):
            ll[g] += math.log((g / 2.0) * pa + (1.0 - g / 2.0) * pr)
    return ll


def call_genotype(pileup: Sequence[Tuple[str, float]], ref: str, alt: str,
                  prior: Sequence[float]) -> Call:
    """The maximum a posteriori genotype, its posterior, GQ and QUAL.

    GQ is -10 log10 of the posterior probability that the called genotype is
    wrong. QUAL is -10 log10 P(g = 0 | D), the Phred-scaled probability that
    the site is not variant. Ties in the posterior go to the smaller g.
    """
    if alt == ref:
        raise ValueError("alt must differ from ref")
    lp = [math.log(p) if p > 0 else -math.inf for p in prior]  # @line L1
    for b, q in pileup:  # @line L2
        e = 10.0 ** (-q / 10.0)  # @line L3
        pr, pa = base_prob(b, ref, e), base_prob(b, alt, e)
        for g in range(3):  # @line L4
            lp[g] += math.log((g / 2.0) * pa + (1.0 - g / 2.0) * pr)  # @line L5
    z = logsumexp(lp)  # @line L6
    post = [math.exp(x - z) for x in lp]  # @line L7
    best = max(range(3), key=lambda g: (lp[g], -g))  # @line L8
    wrong = logsumexp([lp[g] for g in range(3) if g != best]) - z  # @line L9
    gq = -10.0 * wrong / _LN10 if wrong > -math.inf else math.inf
    qual = -10.0 * (lp[0] - z) / _LN10 if lp[0] > -math.inf else math.inf
    return Call(best, post, gq, qual, alt)  # @line L10


def call_site(ref: str, pileup: Sequence[Tuple[str, float]], prior: Sequence[float]) -> Call:
    """Call one site, with the most common non-reference base as the alternate allele.

    Ties between non-reference bases go to the first in ACGT order, so a site
    with no non-reference base is tested against the first other base.
    """
    others = [b for b in "ACGT" if b != ref]
    counts = {b: 0 for b in others}
    for b, _ in pileup:
        if b in counts:
            counts[b] += 1
    alt = max(others, key=lambda b: (counts[b], -others.index(b)))
    return call_genotype(pileup, ref, alt, prior)
bioseq.py 249 lines
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small DNA utilities shared by the biology pages.

Conventions:
- DNA is a str over "ACGT", written 5' to 3'. Positions are 0-based.
- Random draws use a random.Random object that the caller passes in, and the
  order of the draws is fixed and written in each docstring, so that a seed
  gives the same output on every run.
- Alignment scores are added: pass match as a positive number and mismatch and
  gap as negative numbers. A CIGAR string uses M (a column with a base of both
  strings, equal or not), I (a base of a, the query, against a gap) and D (a
  base of b, the reference, against a gap).

This module holds no algorithm of a page: no ORF finder, no motif finder and
no caller. The functions are building blocks for the page code and its tests.
"""

from __future__ import annotations

import math
import random
from collections import namedtuple
from typing import Dict, List, Sequence, Tuple, Union

DNA = "ACGT"

_COMPLEMENT = {"A": "T", "C": "G", "G": "C", "T": "A", "N": "N",
               "a": "t", "c": "g", "g": "c", "t": "a", "n": "n"}


def revcomp(seq: str) -> str:
    """The reverse complement of seq. N maps to N; other letters raise KeyError."""
    return "".join(_COMPLEMENT[c] for c in reversed(seq))


# NCBI genetic code table 1 (the standard code), in the TCAG order of the NCBI
# listing: the first base changes slowest and the third base fastest.
_AAS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
_ORDER = "TCAG"
CODON_TABLE: Dict[str, str] = {
    a + b + c: _AAS[16 * i + 4 * j + k]
    for i, a in enumerate(_ORDER)
    for j, b in enumerate(_ORDER)
    for k, c in enumerate(_ORDER)
}
STOPS = frozenset(c for c, aa in CODON_TABLE.items() if aa == "*")


def translate(seq: str, frame: int = 0) -> str:
    """Translate seq[frame:] codon by codon with CODON_TABLE.

    frame is 0, 1 or 2. A stop codon gives "*", a codon with a letter other than
    A, C, G or T gives "X", and a last part shorter than three bases is dropped.
    The function does not look for start or stop codons.
    """
    if frame not in (0, 1, 2):
        raise ValueError("frame must be 0, 1 or 2")
    s = seq.upper()
    out = []
    for i in range(frame, len(s) - 2, 3):
        out.append(CODON_TABLE.get(s[i:i + 3], "X"))
    return "".join(out)


def random_dna(rng: random.Random, n: int, gc: float = 0.5) -> str:
    """n random bases, independent, with P(G) = P(C) = gc/2 and P(A) = P(T) = (1 - gc)/2.

    Draw order: one rng.random() per base, from left to right.
    """
    if not 0.0 <= gc <= 1.0:
        raise ValueError("gc must be in [0, 1]")
    half_gc, cut = gc / 2.0, gc + (1.0 - gc) / 2.0
    out = []
    for _ in range(n):
        u = rng.random()
        if u < half_gc:
            out.append("C")
        elif u < gc:
            out.append("G")
        elif u < cut:
            out.append("A")
        else:
            out.append("T")
    return "".join(out)


def _other_base(rng: random.Random, base: str) -> str:
    """A base other than base, uniform among the other three (one rng.choice)."""
    return rng.choice([b for b in DNA if b != base])


def mutate(rng: random.Random, seq: str, rate: float) -> str:
    """Substitute each base with probability rate, uniformly by one of the other three.

    Draw order: for each position from left to right, one rng.random(); if it is
    below rate, one rng.choice for the new base. Letters other than A, C, G and T
    are kept and use no draw. No insertions or deletions.
    """
    out = []
    for c in seq:
        if c in DNA and rng.random() < rate:
            out.append(_other_base(rng, c))
        else:
            out.append(c)
    return "".join(out)


SimRead = namedtuple("SimRead", ["read", "pos", "strand", "true_seq"])


def simulate_reads(rng: random.Random, genome: str, n: int, length: int,
                   error_rate: float) -> List[SimRead]:
    """n single-end reads of the given length from both strands of genome.

    Each item is SimRead(read, pos, strand, true_seq): pos is the 0-based start
    of the read on the forward strand of genome, strand is "+" or "-", true_seq
    is the error-free read (genome[pos:pos + length], or its reverse complement
    for "-"), and read is true_seq with substitution errors at rate error_rate.

    Draw order for each read: rng.randrange(len(genome) - length + 1) for pos,
    then rng.random() < 0.5 for the "+" strand, then the draws of mutate on
    true_seq.
    """
    if length > len(genome) or length <= 0:
        raise ValueError("need 0 < length <= len(genome)")
    reads = []
    for _ in range(n):
        pos = rng.randrange(len(genome) - length + 1)
        strand = "+" if rng.random() < 0.5 else "-"
        frag = genome[pos:pos + length]
        true_seq = frag if strand == "+" else revcomp(frag)
        reads.append(SimRead(mutate(rng, true_seq, error_rate), pos, strand, true_seq))
    return reads


def phred_to_prob(q: float) -> float:
    """Error probability of the Phred score q: p = 10^(-q/10)."""
    return 10.0 ** (-q / 10.0)


def prob_to_phred(p: float) -> float:
    """Phred score of the error probability p in (0, 1]: Q = -10 log10(p)."""
    if not 0.0 < p <= 1.0:
        raise ValueError("p must be in (0, 1]")
    return -10.0 * math.log10(p)


def hamming(a: Sequence, b: Sequence) -> int:
    """The number of positions where a and b differ; they must have the same length."""
    if len(a) != len(b):
        raise ValueError("hamming needs sequences of equal length")
    return sum(1 for x, y in zip(a, b) if x != y)


def kmers(seq: str, k: int) -> List[str]:
    """All len(seq) - k + 1 substrings of length k, from left to right (with repeats)."""
    if k <= 0:
        raise ValueError("k must be positive")
    return [seq[i:i + k] for i in range(len(seq) - k + 1)]


def gc_content(seq: str) -> float:
    """The fraction of G and C letters in seq (upper or lower case); 0.0 for an empty seq."""
    if not seq:
        return 0.0
    s = seq.upper()
    return (s.count("G") + s.count("C")) / len(s)


Number = Union[int, float]


def _cigar(ops: List[str]) -> str:
    """Run-length code a list of single-letter operations, for example MMMID to 3M1I1D."""
    out = []
    i = 0
    while i < len(ops):
        j = i
        while j < len(ops) and ops[j] == ops[i]:
            j += 1
        out.append(f"{j - i}{ops[i]}")
        i = j
    return "".join(out)


def _fill(a: str, b: str, match: Number, mismatch: Number, gap: Number, free_b_ends: bool):
    """The dynamic programming table of a linear gap alignment of a and b."""
    n, m = len(a), len(b)
    S = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        S[i][0] = i * gap
    for j in range(1, m + 1):
        S[0][j] = 0 if free_b_ends else j * gap
    for i in range(1, n + 1):
        ai = a[i - 1]
        row, up = S[i], S[i - 1]
        for j in range(1, m + 1):
            diag = up[j - 1] + (match if ai == b[j - 1] else mismatch)
            row[j] = max(diag, up[j] + gap, row[j - 1] + gap)
    return S


def _trace(S, a: str, b: str, i: int, j: int, match: Number, mismatch: Number,
           gap: Number, free_b_ends: bool) -> Tuple[List[str], int]:
    """Trace back from cell (i, j); prefer M, then I, then D. Returns the ops and the start in b."""
    ops: List[str] = []
    while i > 0 or (j > 0 and not free_b_ends):
        if i > 0 and j > 0 and S[i][j] == S[i - 1][j - 1] + (match if a[i - 1] == b[j - 1] else mismatch):
            ops.append("M")
            i, j = i - 1, j - 1
        elif i > 0 and S[i][j] == S[i - 1][j] + gap:
            ops.append("I")
            i -= 1
        else:
            ops.append("D")
            j -= 1
    ops.reverse()
    return ops, j


def global_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                 gap: Number = -1) -> Tuple[Number, str]:
    """Needleman-Wunsch alignment of all of a with all of b, with linear gaps.

    Returns (score, cigar). The cigar uses M, I (a base of a only) and D (a base of
    b only); an empty alignment gives "".
    """
    S = _fill(a, b, match, mismatch, gap, False)
    ops, _ = _trace(S, a, b, len(a), len(b), match, mismatch, gap, False)
    return S[len(a)][len(b)], _cigar(ops)


def semiglobal_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                     gap: Number = -1, with_start: bool = False):
    """Align all of a (the query) to a substring of b (the reference), with linear gaps.

    Bases of b before and after the aligned part cost nothing and are not in the
    cigar, as in SAM. Returns (score, cigar), or (score, cigar, start) with
    with_start=True, where start is the 0-based position in b of the first
    reference base of the alignment. Among best end columns the leftmost wins.
    """
    S = _fill(a, b, match, mismatch, gap, True)
    n = len(a)
    best_j = max(range(len(b) + 1), key=lambda j: (S[n][j], -j))
    ops, start = _trace(S, a, b, n, best_j, match, mismatch, gap, True)
    if with_start:
        return S[n][best_j], _cigar(ops), start
    return S[n][best_j], _cigar(ops)
biostoch.py 336 lines
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.

Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.

Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
  list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
  S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
  the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
  Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
  in `draws` draws without replacement from `total` items of which `good`
  are good.

Requires Python 3.12 or later (random.Random.binomialvariate).
"""

from __future__ import annotations

import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple

State = Tuple[int, ...]

_POISSON_PART = 30.0


# Random variates

def poisson(rng, lam: float) -> int:
    """A Poisson(lam) variate.

    For lam <= 30, inversion of the cumulative distribution with one
    rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
    independent Poisson(lam / p) variates, drawn one after the other by
    inversion (one rng.random() draw each).
    """
    if lam < 0 or math.isnan(lam):
        raise ValueError("lam must be >= 0")
    if lam == 0:
        return 0
    if lam > _POISSON_PART:
        parts = math.ceil(lam / _POISSON_PART)
        part = lam / parts
        return sum(_poisson_inversion(rng, part) for _ in range(parts))
    return _poisson_inversion(rng, lam)


def _poisson_inversion(rng, lam: float) -> int:
    u = rng.random()
    k = 0
    p = math.exp(-lam)
    cdf = p
    while u >= cdf:
        k += 1
        p *= lam / k
        if p == 0.0:
            # Rounding left u above the computed total mass; stop at the tail.
            break
        cdf += p
    return k


def binomial(rng, n: int, p: float) -> int:
    """A Binomial(n, p) variate by rng.binomialvariate (one call)."""
    if n < 0 or not 0.0 <= p <= 1.0:
        raise ValueError("need n >= 0 and 0 <= p <= 1")
    if n == 0 or p == 0.0:
        return 0
    if p == 1.0:
        return n
    return rng.binomialvariate(n, p)


def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
    """A Multinomial(n, probs) vector by conditional binomials.

    probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
    i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
    order; the last cell with positive weight gets the rest.
    """
    if n < 0:
        raise ValueError("n must be >= 0")
    w = [float(q) for q in probs]
    if any(q < 0 for q in w):
        raise ValueError("weights must be >= 0")
    total = sum(w)
    if total <= 0:
        raise ValueError("weights must have a positive sum")
    last = max(i for i, q in enumerate(w) if q > 0)
    out = [0] * len(w)
    left = n
    rest = total
    for i in range(last):
        if left == 0:
            break
        if w[i] == 0:
            continue
        x = binomial(rng, left, min(1.0, w[i] / rest))
        out[i] = x
        left -= x
        rest -= w[i]
    out[last] += left
    return out


def categorical(rng, weights: Sequence[float]) -> int:
    """An index i with probability weights[i] / sum(weights).

    One draw u = rng.random() * sum(weights), then a cumulative search from
    index 0. Indices with weight 0 are never returned.
    """
    total = 0.0
    for w in weights:
        if w < 0:
            raise ValueError("weights must be >= 0")
        total += w
    if total <= 0:
        raise ValueError("weights must have a positive sum")
    u = rng.random() * total
    acc = 0.0
    last = -1
    for i, w in enumerate(weights):
        if w > 0:
            acc += w
            last = i
            if u < acc:
                return i
    return last


def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
               propensity: Callable[[State], Sequence[float]], t_end: float,
               max_events: int = 10 ** 6):
    """Gillespie's direct method from state x0 at time 0 up to time t_end.

    Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
    stops. Otherwise it draws tau = rng.expovariate(a0) first. If
    t + tau > t_end the run stops, and no second number is drawn. Else it
    draws u = rng.random() * a0 and fires the first reaction j with
    a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.

    Returns (times, states, complete). times[0] = 0.0 and states[0] =
    tuple(x0); entry k > 0 is the time and the state just after event k.
    The state at t_end is states[-1]. complete is False only when the run
    stopped because max_events events had fired before t_end.
    """
    x = tuple(int(v) for v in x0)
    times = [0.0]
    states = [x]
    t = 0.0
    m = len(stoich)
    for _ in range(max_events):
        a = propensity(x)
        a0 = 0.0
        for v in a:
            if v < 0:
                raise ValueError("propensities must be >= 0")
            a0 += v
        if a0 <= 0.0:
            return times, states, True
        t += rng.expovariate(a0)
        if t > t_end:
            return times, states, True
        u = rng.random() * a0
        acc = 0.0
        j = -1
        for i in range(m):
            if a[i] > 0:
                acc += a[i]
                j = i
                if u < acc:
                    break
        nu = stoich[j]
        x = tuple(x[i] + nu[i] for i in range(len(x)))
        times.append(t)
        states.append(x)
    return times, states, False


# Sample statistics and test helpers

def mean_var(xs) -> Tuple[float, float]:
    """The mean and the unbiased sample variance (divisor n - 1) by the
    Welford method. The variance is 0.0 for fewer than two values."""
    n = 0
    mean = 0.0
    m2 = 0.0
    for x in xs:
        n += 1
        d = x - mean
        mean += d / n
        m2 += d * (x - mean)
    if n == 0:
        raise ValueError("empty sample")
    return mean, (m2 / (n - 1) if n > 1 else 0.0)


def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
    """True when |m - mu| <= z sqrt(var / n): a sample mean m of n
    independent values with exact mean mu and exact variance var."""
    return abs(m - mu) <= z * math.sqrt(var / n)


# Exact probability mass functions

def log_choose(n: int, k: int) -> float:
    """ln C(n, k), or -inf when k < 0 or k > n."""
    if k < 0 or k > n:
        return -math.inf
    return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)


def binom_pmf(k: int, n: int, p: float) -> float:
    """P(K = k) for K ~ Binomial(n, p)."""
    if k < 0 or k > n:
        return 0.0
    if p == 0.0:
        return 1.0 if k == 0 else 0.0
    if p == 1.0:
        return 1.0 if k == n else 0.0
    return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))


def poisson_pmf(k: int, lam: float) -> float:
    """P(K = k) for K ~ Poisson(lam)."""
    if k < 0:
        return 0.0
    if lam == 0:
        return 1.0 if k == 0 else 0.0
    return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))


def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
    """P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
    if k < 0:
        return 0.0
    if alpha == 0:
        return poisson_pmf(k, mu)
    if mu == 0:
        return 1.0 if k == 0 else 0.0
    r = 1.0 / alpha
    return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
                    + r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))


def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
    """P(K = k) for k good items in `draws` draws without replacement from
    `total` items of which `good` are good."""
    if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
        return 0.0
    return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
                    - log_choose(total, draws))


def logsumexp(xs) -> float:
    """ln(sum of exp(x)) without overflow; -inf for an empty input."""
    xs = list(xs)
    if not xs:
        return -math.inf
    top = max(xs)
    if top == -math.inf:
        return -math.inf
    if top == math.inf:
        return math.inf
    return top + math.log(sum(math.exp(x - top) for x in xs))


# Tail probabilities

def _gamma_q(a: float, x: float) -> float:
    """The regularized upper incomplete gamma function Q(a, x)."""
    if a <= 0:
        raise ValueError("a must be > 0")
    if x <= 0:
        return 1.0
    log_front = -x + a * math.log(x) - math.lgamma(a)
    if x < a + 1.0:
        # Series for P(a, x).
        ap = a
        term = 1.0 / a
        total = term
        for _ in range(100000):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * 1e-16:
                break
        return max(0.0, 1.0 - total * math.exp(log_front))
    # Continued fraction for Q(a, x), by the modified Lentz method.
    tiny = 1e-300
    b = x + 1.0 - a
    c = 1.0 / tiny
    d = 1.0 / b
    h = d
    for i in range(1, 100000):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < tiny:
            d = tiny
        c = b + an / c
        if abs(c) < tiny:
            c = tiny
        d = 1.0 / d
        delta = d * c
        h *= delta
        if abs(delta - 1.0) < 1e-16:
            break
    return math.exp(log_front) * h


def chi2_sf(x: float, df: float) -> float:
    """P(X > x) for X chi-squared with df degrees of freedom."""
    if df <= 0:
        raise ValueError("df must be > 0")
    if x <= 0:
        return 1.0
    return _gamma_q(df / 2.0, x / 2.0)


_STD_NORMAL = NormalDist()


def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
    """P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
    return _STD_NORMAL.cdf(-(x - mu) / sigma)
test_bayesian_genotype_calling.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayesian-genotype-calling/. The authors are listed in prov/YB8C7J.jsonl.

import itertools
import math
import random

from bioseq import random_dna, revcomp, simulate_reads, phred_to_prob
from biostoch import binom_pmf
from bayesian_genotype_calling import (base_prob, call_genotype, call_site, log_likelihoods,
                                       prior_hwe, prior_theta)

EXAMPLE = [("A", 30), ("A", 30), ("A", 20), ("G", 30), ("G", 20), ("G", 10)]


def brute_posterior(pileup, ref, alt, prior):
    """P(g | D) by a sum over every way to assign each read to one of the two chromosomes."""
    joint = []
    for g in range(3):
        chroms = [(ref, ref), (ref, alt), (alt, alt)][g]
        lik = 0.0
        for origin in itertools.product((0, 1), repeat=len(pileup)):
            term = 0.5 ** len(pileup)
            for (b, q), c in zip(pileup, origin):
                term *= base_prob(b, chroms[c], phred_to_prob(q))
            lik += term
        joint.append(prior[g] * lik)
    s = sum(joint)
    return [x / s for x in joint]


def test_page_example():
    ll = log_likelihoods(EXAMPLE, "A", "G")
    pl = [round(-10 * (x - max(ll)) / math.log(10)) for x in ll]
    assert pl == [56, 0, 76]
    c = call_genotype(EXAMPLE, "A", "G", prior_theta(0.001))
    assert c.genotype == 1
    assert abs(c.posterior[1] - 0.997462) < 1e-6
    assert abs(c.gq - 25.955) < 1e-3 and abs(c.qual - 25.955) < 1e-3
    c = call_genotype(EXAMPLE, "A", "G", prior_hwe(0.3))
    assert c.genotype == 1 and abs(c.gq - 55.261) < 1e-3


def test_two_reads_and_one_of_ten():
    c = call_genotype([("G", 30)] * 2, "A", "G", prior_theta(0.001))
    assert c.genotype == 2
    assert abs(c.posterior[1] - 0.333432) < 1e-6 and abs(c.posterior[2] - 0.666420) < 1e-6
    c = call_genotype([("G", 30)] + [("A", 30)] * 9, "A", "G", prior_theta(0.001))
    assert c.genotype == 0 and abs(c.posterior[1] - 0.002932) < 1e-6


def test_against_brute_force():
    rng = random.Random(7)
    for _ in range(200):
        n = rng.randint(0, 8)
        pile = [(rng.choice("AAGGC"), rng.choice((5, 10, 20, 30, 40))) for _ in range(n)]
        prior = prior_theta(rng.choice((0.001, 0.01, 0.1))) if rng.random() < 0.5 else prior_hwe(rng.random())
        c = call_genotype(pile, "A", "G", prior)
        brute = brute_posterior(pile, "A", "G", prior)
        for g in range(3):
            assert abs(c.posterior[g] - brute[g]) < 1e-9
        assert c.genotype == max(range(3), key=lambda g: (brute[g], -g)) or \
            abs(brute[c.genotype] - max(brute)) < 1e-12


def test_equal_qualities_match_binomial():
    e = phred_to_prob(20)
    for n in range(0, 12):
        for k in range(n + 1):
            pile = [("G", 20)] * k + [("A", 20)] * (n - k)
            ll = log_likelihoods(pile, "A", "G")
            for g in range(3):
                pa = (g / 2) * (1 - e) + (1 - g / 2) * (e / 3)
                pr = (g / 2) * (e / 3) + (1 - g / 2) * (1 - e)
                # pa^k pr^(n-k) = (pa + pr)^n t^k (1 - t)^(n-k) with t = pa / (pa + pr).
                expect = (pa + pr) ** n * binom_pmf(k, n, pa / (pa + pr)) / math.comb(n, k)
                assert abs(math.exp(ll[g]) - expect) <= 1e-12 * max(1.0, expect)


def test_no_reads_gives_prior_and_deep_pileup_is_finite():
    prior = prior_theta(0.001)
    c = call_genotype([], "A", "G", prior)
    assert all(abs(a - b) < 1e-15 for a, b in zip(c.posterior, prior))
    deep = [("A", 40)] * 3000 + [("G", 40)] * 3000
    c = call_genotype(deep, "A", "G", prior)
    assert c.genotype == 1 and math.isfinite(c.qual) and c.qual > 1000


def test_priors_sum_to_one():
    for t in (0.0, 0.001, 0.5):
        assert abs(sum(prior_theta(t)) - 1) < 1e-15
    for f in (0.0, 0.2, 1.0):
        assert abs(sum(prior_hwe(f)) - 1) < 1e-15


def test_recovers_simulated_variants():
    rng = random.Random(2024)
    g_len, read_len, q = 3000, 100, 20
    genome = random_dna(rng, g_len)
    sites = rng.sample(range(50, g_len - 50), 24)
    truth = {}
    hap = [list(genome), list(genome)]
    for i, s in enumerate(sites):
        alt = rng.choice([b for b in "ACGT" if b != genome[s]])
        g = 2 if i % 4 == 0 else 1
        truth[s] = (alt, g)
        hap[0][s] = alt
        if g == 2:
            hap[1][s] = alt
    piles = [[] for _ in range(g_len)]
    for h in hap:
        for r in simulate_reads(rng, "".join(h), 450, read_len, phred_to_prob(q)):
            fwd = r.read if r.strand == "+" else revcomp(r.read)
            for j, b in enumerate(fwd):
                piles[r.pos + j].append((b, q))
    called = {}
    for s in range(g_len):
        c = call_site(genome[s], piles[s], prior_theta(0.001))
        if c.genotype > 0:
            called[s] = (c.alt, c.genotype)
    assert called == truth

History

Maq (Li, Ruan and Durbin, 2008) called the consensus genotype of a sample with a Bayesian model of the bases and qualities at each site, and gave the consensus quality on the Phred scale. In 2011, Li described a framework for many samples in samtools, and DePristo et al. described the UnifiedGenotyper of GATK, both with priors of this form. The review of Nielsen et al. (2011) set out the difference between SNP calling and genotype calling and the role of the prior.

References

  1. Heng Li, Jue Ruan and Richard Durbin, Mapping short DNA sequencing reads and calling variants using mapping quality scores, Genome Research 18(11), 2008, pp. 1851 to 1858, Methods (the consensus genotype calling of Maq, with a prior on the heterozygote and the Phred-scaled consensus quality)
  2. Heng Li, A statistical framework for SNP calling, mutation discovery, association mapping and population genetical parameter estimation from sequencing data, Bioinformatics 27(21), 2011, pp. 2987 to 2993, Section 2 (genotype likelihoods, the posterior of the genotype, and the estimation of the allele frequency across samples)
  3. 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 SNP discovery and genotyping (the Bayesian model of the UnifiedGenotyper and the prior from the heterozygosity)
  4. Rasmus Nielsen, Joshua S. Paul, Anders Albrechtsen and Yun S. Song, Genotype and SNP calling from next-generation sequencing data, Nature Reviews Genetics 12(6), 2011, pp. 443 to 451, the section on probabilistic genotype calling (priors from a fixed rate or from the allele frequencies of a population)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example