Algorithmadvanced
ABBA-BABA test
Also called Patterson's D statistic, D-statistic for introgression.
Count ABBA and BABA site patterns across four taxa. An excess of one over the other signals gene flow, since incomplete sorting is symmetric.
- Time
- O(n + g) worst · average · best
- Space
- O(g) extra
- Where
- g = the number of jackknife blocks; n = the number of sites
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Richard E. Green, David Reich, Nick Patterson, Eric Y. Durand, Montgomery Slatkin, 2010
The ABBA-BABA test, also called Patterson's D statistic, tests for gene flow between groups that are not sister groups on a tree. It takes three groups , , with the tree and an outgroup . Call the allele of the outgroup A and the other allele B. At an ABBA site, and share B; at a BABA site, and share B. Both patterns come from gene trees that do not match the species tree, and under the null model of the test, which includes incomplete lineage sorting but no gene flow, the two are equally likely. An excess of ABBA points to gene flow between and . The statistic is , and its standard error comes from a block jackknife over the genome. The test is valid only under its null model: other demographic histories can also make differ from 0.
In plain words
Take two closely related groups, a third group, and a distant group that shows the old form of each variant. Along the genome, the first or the second group sometimes shares a new variant with the third group by chance, because the old variation was not sorted when the groups split. Chance favors neither of the first two groups. So the number of variants that the first group shares with the third should be about the same as the number that the second group shares with the third.
If one of the two shares clearly more, some of its genome probably came from the third group, or went into it. The test counts the two kinds of sites, takes their difference, and asks if it is larger than chance along the genome allows.
The problem
Input. For biallelic sites, the frequency of allele B (the allele that the outgroup does not usually carry) in samples of , , and at site . For one sequence per group, each frequency is 0 or 1. A partition of the sites into blocks of adjacent sites.
The counts. Site adds
to the two counts; these are the probabilities that one sequence drawn from each group shows the pattern. Then
The numerator is . When the outgroup carries only A, this is the f-statistic , so is a normalized .
Output. , its standard error and . A common rule calls significant.
The algorithm
ABBA-BABA(p_1, p_2, p_3, p_4, blocks)- 1
for each block j = 1..g do - 2
for each site s in block j: compute ABBA_s and BABA_s - 3
a_j ← Σ of ABBA_s over block j - 4
b_j ← Σ of BABA_s over block j - 5
A ← Σ_j a_j; B ← Σ_j b_j; D ← (A - B) / (A + B) - 6
for each block j: D_j ← ((A - a_j) - (B - b_j)) / ((A - a_j) + (B - b_j)) - 7
SE ← sqrt((g - 1)/g · Σ_j (D_j - mean of D_j)²) - 8
Z ← D / SE - 9
return D, SE, Z
Lines L1 to L4 make one pass over the sites. Line L6 is the delete-one jackknife: the value of with block left out comes from the totals in time. Line L7 is the jackknife variance. Sites in one block are linked and their patterns are correlated, so a standard error from independent sites would be too small. Blocks of several megabases, much longer than the range of linkage disequilibrium, are roughly independent. The code on this page recomputes for each left-out block with a generic jackknife, which costs instead of and gives the same values.
Example
Counting. With single sequences
P1 A A C G T A
P2 G A C G T T
P3 G T C A T T
O A A G A T A
site 1 is ABBA (P1 has the allele of O, P2 and P3 the other one), site 6 is ABBA too, site 3 is BBBA, site 4 is BBAA, and sites 2 and 5 are not informative. So ABBA = 2 and BABA = 0. Swapping and swaps the two counts and changes the sign of .
The jackknife. Four blocks with give , and . Leaving out each block gives , with mean . The squared deviations sum to , so and . Even a large is not significant when it rests on a few blocks that disagree.
A simulation. In 20000 sites from a model with incomplete lineage sorting and no gene flow, the counts were 1470 ABBA and 1536 BABA, with and . When 10 percent of the sites of came from , the counts were 1749 and 1413, with and .
Correctness
The arithmetic is direct: lines L1 to L5 compute the sums in the definition, line L6 computes on the data without block because the totals are additive over blocks, and line L7 is the delete-one jackknife formula. The statistical claim is the expectation under the null model. If there is no gene flow, if the ancestral populations mated at random, and if each site has had at most one mutation, then the genealogy of one sequence from each of , , follows the multispecies coalescent. The lineages of and either join in the ancestor of and , and then no branch of the gene tree separates or from the rest, so the site can be neither ABBA nor BABA. Or they do not join there, and from then on the two lineages are in the same population and the rest of the process treats them the same way. Swapping their labels maps each ABBA history to a BABA history of the same probability, so . Because is a ratio, its mean is only close to 0, and the normal law of is an approximation from many blocks. The full proof is below.
Proof: The counts, the leave-one-out values and the jackknife variance are computed exactly, and under the null model ABBA and BABA have the same expected countfull
Setting. Sites carry frequencies of allele B in samples of . The blocks partition the sites. and .
Lemma 1 (single sequences). If every and , then exactly when the site has the pattern ABBA (with A the allele of ), and 0 otherwise; the same holds for BABA.
Proof. With , the product is 1 exactly when and , that is, when has the allele of and and have the other allele. The BABA case is the same with and swapped. The function count_patterns tests the same conditions on the raw alleles, and polarize codes each allele as 1 when it differs from that of .
Lemma 2 (sampling). Draw one sequence from each sample, independently, each carrying B with probability . Then and .
Proof. The four draws are independent, and ABBA means A in , B in , B in and A in . Multiply the four probabilities.
Lemma 3 (the numerator). . If , this equals , the summand of .
Proof. .
Lemma 4 (leave-one-out values). Let , , and . The value of on the sites outside is .
Proof. The sums over the sites outside are and , because the blocks are disjoint and cover all sites.
Line L6 uses this form, and the code gets the same numbers by summing the remaining blocks. Line L7 is the delete-one jackknife variance .
Lemma 5 (scaling of the jackknife). If the statistic is the mean of block values , the jackknife variance equals , where is the sample variance.
Proof. The value without block is , so , where . Then .
So the factor makes the jackknife agree with the usual standard error in the linear case. For the ratio , the jackknife variance is a consistent estimate when the blocks are independent and many, which is an asymptotic statement, not one proved here.
The null model. One gene copy is sampled from each of , , and , with the copies of and sampled at the same time. The populations form the rooted tree with no gene flow after any split. Each ancestral population mates at random, so the lineages in it coalesce by the Kingman coalescent, with all pairs equally likely to join next. Mutations fall on the branches of the gene tree as a Poisson process whose rate does not depend on the labels of the lineages, with at most one mutation per site (infinite sites). This is the multispecies coalescent with infinite sites.
Theorem (equal expected counts). Under the null model, at every site, .
Proof. With one mutation at the site, the pattern is set by the branch of the gene tree that carries the mutation: the copies below carry B, the others A. An ABBA site needs a branch whose set of copies below it is (or, for an unrooted reading with below the mutation, ; both split from ). BABA needs a branch that splits from .
Let be the event that the lineages of and coalesce in the ancestral population of and . On , copies 1 and 2 form a clade in the gene tree, so no branch splits from , and no branch splits from . Both patterns have probability 0 on .
On the complement of , lineages 1 and 2 enter the ancestral population of , and as two distinct lineages, and from then on they are in the same populations at all times. The law of the rest of the genealogy, of the branch lengths and of the mutations is invariant under the exchange of labels 1 and 2: each coalescence picks a pair uniformly at random, the times do not depend on the labels, and the mutation rate does not depend on the labels. The history of the two lineages before they entered that population is also exchangeable: each is a single lineage from its sampling time to the split of and , and these times are equal, and under the two lineages then stay apart in the ancestor of and for the same length of time. So the map that swaps labels 1 and 2 preserves the law of the whole history on , and it maps the event "the mutation splits from " onto the event "the mutation splits from ". The two events have the same probability.
With frequency data, Lemma 2 writes , taken over the sampling of sequences from populations that follow the null model, as the difference of the probabilities in the theorem, so the expected numerator of is 0. The theorem uses each assumption of the null model: gene flow into from , structure in the ancestor of and that places closer to , or a mutation rate that differs between the lineages of and all break the exchange of labels, and then is possible.
Complexity
- Counts. One pass over the sites: time.
- Jackknife. with the totals of line L5. The block sums take space.
- Many tests. For all choices of among groups, compute the allele frequencies once and each in : in total.
Properties
- Sign. means and share more derived alleles than and . The test does not say which way the gene flow went.
- Range. . Its size depends on the time since the split and on the amount of incomplete lineage sorting, so is not an estimate of the admixed fraction.
- Antisymmetry. Swapping and changes the sign of and of .
- Robust to rate along the genome. Both patterns need a mutation on an internal branch, so a region with a high mutation rate adds to both counts in the same proportion under the null.
- Only informative sites count. BBAA sites, which match the species tree, and singletons do not enter .
Variants and improvements
- Frequencies. The form with uses all sampled sequences and reduces the variance (Durand and coauthors 2011).
- The admixed fraction. Martin, Davey and Jiggins (2015) define , which compares the observed numerator with the value under complete gene flow, as an estimate of the admixed fraction in a window. ratios give it on a genome scale.
- Weighted jackknife. With blocks of different sizes, a weighted delete-one jackknife gives each block a weight in proportion to its number of sites.
- Five or more taxa. Extensions test gene flow among more groups at once, for example the statistics for five taxa.
- Admixture graphs. Several and values at once fit an admixture graph; see the f-statistics.
When to use it
Use it to test for gene flow between a group and one of two sister groups, when an outgroup is available and the sister groups split recently enough that incomplete lineage sorting is common. It works with one genome per group. To find which regions came from the other group, use local ancestry inference or window statistics such as .
Pitfalls
- The null model is narrow. Structure in the common ancestor of and , for example a subdivided ancestral population in which split from a deme closer to , can give with no gene flow after the split (Eriksson and Manica 2012). A significant rejects the null model, not every model without gene flow.
- Unequal error rates. Sequencing errors, ancient DNA damage, or mapping that favors the reference genome add false derived alleles to one group more than the other, and that biases .
- Recurrent mutation. The null assumes each site mutated at most once. Many changes at one site, as at CpG sites or in distant groups, break the symmetry.
- Blocks too short. Blocks shorter than the range of linkage disequilibrium make too small and too large.
- Windows. In small windows has a high variance and is largest where few sites are informative, so it is a poor statistic for scanning the genome.
- The wrong tree. If and are not sister groups, measures the tree, not gene flow.
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/abba-baba-test/. The authors are listed in prov/7E0M5A.jsonl.
"""The ABBA-BABA test (Patterson's D statistic) with a block jackknife.
Four groups P1, P2, P3 and an outgroup O, with the tree ((P1, P2), P3), O.
At a biallelic site, call the allele of O "A" and the other allele "B".
ABBA: P1 has A, P2 and P3 have B. BABA: P1 and P3 have B, P2 has A.
Without gene flow and under the model of the test, the two patterns have
the same expected count, so D = (ABBA - BABA) / (ABBA + BABA) has mean
about 0. D > 0 points to gene flow between P2 and P3, and D < 0 between
P1 and P3.
With allele frequencies p1..p4 of allele B in samples of the four groups,
a site adds (1 - p1) p2 p3 (1 - p4) to ABBA and p1 (1 - p2) p3 (1 - p4)
to BABA (Durand and coauthors 2011). For single sequences with O fixed
for A, these terms are 0 or 1 and give the pattern counts.
The standard error comes from a delete-one block jackknife over blocks
of adjacent sites, which are long enough that the blocks are roughly
independent in spite of linkage.
"""
from __future__ import annotations
import math
from typing import Callable, Sequence
def count_patterns(p1: Sequence, p2: Sequence, p3: Sequence, out: Sequence) -> tuple[int, int]:
"""Count ABBA and BABA sites in four aligned sequences. A is the outgroup allele."""
abba = baba = 0
for x1, x2, x3, a in zip(p1, p2, p3, out):
if x3 == a:
continue
if x1 == a and x2 == x3:
abba += 1
elif x2 == a and x1 == x3:
baba += 1
return abba, baba
def site_terms(p1: float, p2: float, p3: float, p4: float) -> tuple[float, float]:
"""The ABBA and BABA contributions of one site from the frequencies of allele B."""
w = p3 * (1.0 - p4)
return (1.0 - p1) * p2 * w, p1 * (1.0 - p2) * w
def d_from_counts(abba: float, baba: float) -> float:
total = abba + baba
if total <= 0:
raise ValueError("no informative site")
return (abba - baba) / total
def block_sums(freqs: Sequence[tuple[float, float, float, float]], block_size: int) -> list[tuple[float, float]]:
"""ABBA and BABA sums over consecutive blocks of block_size sites (the last block may be shorter)."""
if block_size < 1:
raise ValueError("block_size must be positive")
out = []
for start in range(0, len(freqs), block_size): # @line L1
a = b = 0.0
for p1, p2, p3, p4 in freqs[start:start + block_size]:
x, y = site_terms(p1, p2, p3, p4) # @line L2
a += x # @line L3
b += y # @line L4
out.append((a, b))
return out
def block_jackknife(blocks: Sequence, stat: Callable[[Sequence], float]) -> tuple[float, float, list[float]]:
"""Delete-one jackknife: the estimate on all blocks, its standard error, and the leave-one-out values."""
g = len(blocks)
if g < 2:
raise ValueError("need at least two blocks")
full = stat(blocks)
loo = [stat(list(blocks[:j]) + list(blocks[j + 1:])) for j in range(g)] # @line L6
mean = sum(loo) / g
var = (g - 1) / g * sum((v - mean) ** 2 for v in loo) # @line L7
return full, math.sqrt(var), loo
def _d_of_blocks(blocks: Sequence[tuple[float, float]]) -> float:
return d_from_counts(sum(a for a, _ in blocks), sum(b for _, b in blocks))
def abba_baba(freqs: Sequence[tuple[float, float, float, float]], block_size: int) -> tuple[float, float, float]:
"""D, its jackknife standard error and Z = D / SE."""
blocks = block_sums(freqs, block_size)
d, se, _ = block_jackknife(blocks, _d_of_blocks) # @line L5
z = d / se if se > 0 else math.inf if d != 0 else 0.0 # @line L8
return d, se, z # @line L9
def polarize(p1: Sequence, p2: Sequence, p3: Sequence, out: Sequence) -> list[tuple[float, float, float, float]]:
"""Turn four single sequences into 0/1 frequencies of the allele that differs from the outgroup.
Sites with more than two alleles among the four are dropped."""
rows = []
for x1, x2, x3, a in zip(p1, p2, p3, out):
if len({x1, x2, x3, a}) > 2:
continue
rows.append((float(x1 != a), float(x2 != a), float(x3 != a), 0.0))
return rows
abba_baba_test.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abba-baba-test/. The authors are listed in prov/7E0M5A.jsonl.
"""Entry point named after the slug. The code is in abba_baba.py,
because the tools treat a file whose name ends in _test as a test file."""
from abba_baba import (
abba_baba,
block_jackknife,
block_sums,
count_patterns,
d_from_counts,
polarize,
site_terms,
)
__all__ = [
"abba_baba",
"block_jackknife",
"block_sums",
"count_patterns",
"d_from_counts",
"polarize",
"site_terms",
]
test_abba_baba_test.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abba-baba-test/. The authors are listed in prov/7E0M5A.jsonl.
import math
import random
import pytest
from abba_baba_test import (abba_baba, block_jackknife, block_sums, count_patterns, d_from_counts, polarize,
site_terms)
def simulate_sites(rng, n_sites, t_internal, gamma, t_intro):
"""Site patterns of four single sequences from a three-taxon gene tree model.
Species tree ((P1, P2), P3) with an internal branch of t_internal coalescent
units. With probability gamma a site's P2 lineage comes from P3 (introgression),
where it can join the P3 lineage during t_intro units before the root. A lineage
pair that does not join in time ends up in a random one of the three pairings
(incomplete lineage sorting). One derived mutation falls on the internal branch
of the gene tree with probability 0.3, else on a tip, so sites are ABBA, BABA,
BBAA or a singleton pattern.
"""
seqs = ([], [], [], [])
for _ in range(n_sites):
if rng.random() < gamma:
pair = (2, 3) if rng.random() < 1 - math.exp(-t_intro) else rng.choice([(1, 2), (1, 3), (2, 3)])
else:
pair = (1, 2) if rng.random() < 1 - math.exp(-t_internal) else rng.choice([(1, 2), (1, 3), (2, 3)])
derived = set(pair) if rng.random() < 0.3 else {rng.choice([1, 2, 3])}
for idx in range(3):
seqs[idx].append("T" if idx + 1 in derived else "C")
seqs[3].append("C")
return seqs
def brute_counts(p1, p2, p3, out):
pats = ["".join("A" if x == a else "B" for x in (y1, y2, y3, a)) for y1, y2, y3, a in zip(p1, p2, p3, out)]
return pats.count("ABBA"), pats.count("BABA")
def test_counts_by_hand():
p1 = "AACGTA"
p2 = "GACGTT"
p3 = "GTCATT"
o = "AAGATA"
# site 0: A G G | A -> ABBA ; site 1: A A T | A -> AAB.. no ; site 2: C C C | G -> BBBA no
# site 3: G G A | A -> BBAA no ; site 4: T T T | T -> no ; site 5: A T T | A -> ABBA
assert count_patterns(p1, p2, p3, o) == (2, 0)
assert count_patterns(p2, p1, p3, o) == (0, 2)
def test_counts_against_brute_force():
rng = random.Random(1)
for _ in range(20):
seqs = ["".join(rng.choice("AC") for _ in range(200)) for _ in range(4)]
assert count_patterns(*seqs) == brute_counts(*seqs)
def test_frequency_terms_match_counts():
rng = random.Random(2)
seqs = simulate_sites(rng, 500, 0.5, 0.0, 1.0)
rows = polarize(*seqs)
a = sum(site_terms(*r)[0] for r in rows)
b = sum(site_terms(*r)[1] for r in rows)
assert (a, b) == count_patterns(*seqs)
def test_frequency_terms_by_hand():
x, y = site_terms(0.2, 0.6, 0.5, 0.1)
assert x == pytest.approx(0.8 * 0.6 * 0.5 * 0.9)
assert y == pytest.approx(0.2 * 0.4 * 0.5 * 0.9)
# The numerator is p3 (1 - p4) (p2 - p1).
assert x - y == pytest.approx(0.5 * 0.9 * (0.6 - 0.2))
def test_antisymmetry():
rng = random.Random(3)
freqs = [tuple(rng.random() for _ in range(3)) + (0.0,) for _ in range(300)]
swapped = [(b, a, c, d) for a, b, c, d in freqs]
d1, se1, z1 = abba_baba(freqs, 30)
d2, se2, z2 = abba_baba(swapped, 30)
assert d1 == pytest.approx(-d2)
assert se1 == pytest.approx(se2)
assert z1 == pytest.approx(-z2)
def test_jackknife_of_mean_is_standard_error():
rng = random.Random(4)
vals = [rng.gauss(0, 1) for _ in range(12)]
est, se, loo = block_jackknife(vals, lambda xs: sum(xs) / len(xs))
mean = sum(vals) / 12
s2 = sum((v - mean) ** 2 for v in vals) / 11
assert est == pytest.approx(mean)
assert se == pytest.approx(math.sqrt(s2 / 12))
def test_jackknife_leave_one_out_values():
blocks = [(3.0, 1.0), (2.0, 2.0), (4.0, 0.0), (1.0, 1.0)]
est, se, loo = block_jackknife(blocks, lambda bs: d_from_counts(sum(a for a, _ in bs), sum(b for _, b in bs)))
assert est == pytest.approx((10 - 4) / 14)
assert loo == pytest.approx([(7 - 3) / 10, (8 - 2) / 10, (6 - 4) / 10, (9 - 3) / 12])
mean = sum(loo) / 4
assert se == pytest.approx(math.sqrt(0.75 * sum((v - mean) ** 2 for v in loo)))
def test_null_model_gives_small_z():
rng = random.Random(5)
seqs = simulate_sites(rng, 20000, 0.3, 0.0, 1.0)
d, se, z = abba_baba(polarize(*seqs), 500)
assert abs(z) < 3
abba, baba = count_patterns(*seqs)
assert abba > 300 and baba > 300 # incomplete lineage sorting makes both patterns common
def test_introgression_gives_positive_d():
rng = random.Random(6)
seqs = simulate_sites(rng, 20000, 0.3, 0.1, 1.0)
d, se, z = abba_baba(polarize(*seqs), 500)
assert d > 0.1
assert z > 5
def test_block_sums_and_errors():
freqs = [(0.0, 1.0, 1.0, 0.0)] * 5 + [(1.0, 0.0, 1.0, 0.0)] * 2
assert block_sums(freqs, 3) == [(3.0, 0.0), (2.0, 1.0), (0.0, 1.0)]
with pytest.raises(ValueError):
block_sums(freqs, 0)
with pytest.raises(ValueError):
d_from_counts(0, 0)
with pytest.raises(ValueError):
block_jackknife([(1.0, 0.0)], lambda bs: 0.0)
# Sites with three alleles are dropped.
assert polarize("AT", "CT", "GA", "AA") == [(1.0, 1.0, 0.0, 0.0)]
History
Green and coauthors (2010) compared a Neandertal genome with two modern humans and a chimpanzee. They found that non-African genomes share more derived alleles with the Neandertal than African genomes do, and gave the D statistic with a block jackknife standard error. Durand, Patterson, Reich and Slatkin (2011) derived the expectation of under the null model and under gene flow, and the form with allele frequencies. Patterson and coauthors (2012) wrote as a normalized statistic in ADMIXTOOLS. Later work studied its use in windows (Martin, Davey and Jiggins 2015) and the demographic models other than gene flow that give the same signal.
References
- Richard E. Green and coauthors, A draft sequence of the Neandertal genome, Science 328(5979), 2010, pp. 710-722 (the D statistic from ABBA and BABA counts of a Neandertal, two modern humans and a chimpanzee, with a block jackknife)
- Eric Y. Durand, Nick Patterson, David Reich and Montgomery Slatkin, Testing for ancient admixture between closely related populations, Molecular Biology and Evolution 28(8), 2011, pp. 2239-2252 (the null model, the expectation of D under incomplete lineage sorting and under gene flow, and the form with sample allele frequencies)
- Nick Patterson and coauthors, Ancient admixture in human history, Genetics 192(3), 2012, pp. 1065-1093 (the D statistic as a normalized f4 statistic, and the block jackknife standard error)
- Simon H. Martin, John W. Davey and Chris D. Jiggins, Evaluating the use of ABBA-BABA statistics to locate introgressed loci, Molecular Biology and Evolution 32(1), 2015, pp. 244-257 (D in small windows and the f_d estimator of the admixed fraction)
- Anders Eriksson and Andrea Manica, Effect of ancient population structure on the degree of polymorphism shared between modern human populations and ancient hominins, PNAS 109(35), 2012, pp. 13956-13960 (ancestral structure without later gene flow can give D different from 0)
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 7E0M5A Edit this page History Report an error Markdown