Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 P1P_1, P2P_2, P3P_3 with the tree ((P1,P2),P3)((P_1, P_2), P_3) and an outgroup OO. Call the allele of the outgroup A and the other allele B. At an ABBA site, P2P_2 and P3P_3 share B; at a BABA site, P1P_1 and P3P_3 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 P2P_2 and P3P_3. The statistic is D=(ABBA−BABA)/(ABBA+BABA)D = (\text{ABBA} - \text{BABA}) / (\text{ABBA} + \text{BABA}), 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 DD 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 nn biallelic sites, the frequency p1s,p2s,p3s,p4sp_{1s}, p_{2s}, p_{3s}, p_{4s} of allele B (the allele that the outgroup does not usually carry) in samples of P1P_1, P2P_2, P3P_3 and OO at site ss. For one sequence per group, each frequency is 0 or 1. A partition of the sites into gg blocks of adjacent sites.

The counts. Site ss adds

ABBAs=(1−p1s) p2s p3s(1−p4s),BABAs=p1s(1−p2s) p3s(1−p4s)\text{ABBA}_s = (1 - p_{1s})\, p_{2s}\, p_{3s} (1 - p_{4s}), \qquad \text{BABA}_s = p_{1s} (1 - p_{2s})\, p_{3s} (1 - p_{4s})

to the two counts; these are the probabilities that one sequence drawn from each group shows the pattern. Then

D=∑s(ABBAs−BABAs)∑s(ABBAs+BABAs).D = \frac{\sum_s (\text{ABBA}_s - \text{BABA}_s)}{\sum_s (\text{ABBA}_s + \text{BABA}_s)}.

The numerator is ∑s(p2s−p1s) p3s(1−p4s)\sum_s (p_{2s} - p_{1s})\, p_{3s} (1 - p_{4s}). When the outgroup carries only A, this is the f-statistic f4(P2,P1;P3,O)=∑s(p2s−p1s)(p3s−p4s)f_4(P_2, P_1; P_3, O) = \sum_s (p_{2s} - p_{1s})(p_{3s} - p_{4s}), so DD is a normalized f4f_4.

Output. DD, its standard error SE^\widehat{\mathrm{SE}} and Z=D/SE^Z = D / \widehat{\mathrm{SE}}. A common rule calls ∣Z∣>3|Z| > 3 significant.

The algorithm

  1. ABBA-BABA(p_1, p_2, p_3, p_4, blocks)
  2. 1for each block j = 1..g do
  3. 2for each site s in block j: compute ABBA_s and BABA_s
  4. 3a_j ← Σ of ABBA_s over block j
  5. 4b_j ← Σ of BABA_s over block j
  6. 5A ← Σ_j a_j; B ← Σ_j b_j; D ← (A - B) / (A + B)
  7. 6for each block j: D_j ← ((A - a_j) - (B - b_j)) / ((A - a_j) + (B - b_j))
  8. 7SE ← sqrt((g - 1)/g · Σ_j (D_j - mean of D_j)²)
  9. 8Z ← D / SE
  10. 9return D, SE, Z

Lines L1 to L4 make one pass over the sites. Line L6 is the delete-one jackknife: the value of DD with block jj left out comes from the totals in O(1)O(1) 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 DD for each left-out block with a generic jackknife, which costs O(g2)O(g^2) instead of O(g)O(g) 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 P1P_1 and P2P_2 swaps the two counts and changes the sign of DD.

The jackknife. Four blocks with (aj,bj)=(3,1),(2,2),(4,0),(1,1)(a_j, b_j) = (3, 1), (2, 2), (4, 0), (1, 1) give A=10A = 10, B=4B = 4 and D=6/14=0.4286D = 6/14 = 0.4286. Leaving out each block gives Dj=0.4,0.6,0.2,0.5D_j = 0.4, 0.6, 0.2, 0.5, with mean 0.4250.425. The squared deviations sum to 0.08750.0875, so SE^=0.75⋅0.0875=0.256\widehat{\mathrm{SE}} = \sqrt{0.75 \cdot 0.0875} = 0.256 and Z=1.67Z = 1.67. Even a large DD 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 D=−0.022D = -0.022 and Z=−1.37Z = -1.37. When 10 percent of the sites of P2P_2 came from P3P_3, the counts were 1749 and 1413, with D=0.106D = 0.106 and Z=6.5Z = 6.5.

Correctness

The arithmetic is direct: lines L1 to L5 compute the sums in the definition, line L6 computes DD on the data without block jj 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 P1P_1, P2P_2, P3P_3 follows the multispecies coalescent. The lineages of P1P_1 and P2P_2 either join in the ancestor of P1P_1 and P2P_2, and then no branch of the gene tree separates {2,3}\{2, 3\} or {1,3}\{1, 3\} 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 E[ABBA]=E[BABA]E[\text{ABBA}] = E[\text{BABA}]. Because DD is a ratio, its mean is only close to 0, and the normal law of ZZ 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 s=1,…,ns = 1, \ldots, n carry frequencies p1s,…,p4s∈[0,1]p_{1s}, \ldots, p_{4s} \in [0, 1] of allele B in samples of P1,P2,P3,OP_1, P_2, P_3, O. The blocks J1,…,JgJ_1, \ldots, J_g partition the sites. ABBAs=(1−p1s)p2sp3s(1−p4s)\text{ABBA}_s = (1 - p_{1s}) p_{2s} p_{3s} (1 - p_{4s}) and BABAs=p1s(1−p2s)p3s(1−p4s)\text{BABA}_s = p_{1s} (1 - p_{2s}) p_{3s} (1 - p_{4s}).

Lemma 1 (single sequences). If every pis∈{0,1}p_{is} \in \{0, 1\} and p4s=0p_{4s} = 0, then ABBAs=1\text{ABBA}_s = 1 exactly when the site has the pattern ABBA (with A the allele of OO), and 0 otherwise; the same holds for BABA.

Proof. With p4s=0p_{4s} = 0, the product (1−p1s)p2sp3s(1 - p_{1s}) p_{2s} p_{3s} is 1 exactly when p1s=0p_{1s} = 0 and p2s=p3s=1p_{2s} = p_{3s} = 1, that is, when P1P_1 has the allele of OO and P2P_2 and P3P_3 have the other allele. The BABA case is the same with P1P_1 and P2P_2 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 OO. □\square

Lemma 2 (sampling). Draw one sequence from each sample, independently, each carrying B with probability pisp_{is}. Then P(pattern ABBA at s)=ABBAsP(\text{pattern ABBA at } s) = \text{ABBA}_s and P(BABA at s)=BABAsP(\text{BABA at } s) = \text{BABA}_s.

Proof. The four draws are independent, and ABBA means A in P1P_1, B in P2P_2, B in P3P_3 and A in OO. Multiply the four probabilities. □\square

Lemma 3 (the numerator). ABBAs−BABAs=(p2s−p1s)p3s(1−p4s)\text{ABBA}_s - \text{BABA}_s = (p_{2s} - p_{1s}) p_{3s} (1 - p_{4s}). If p4s=0p_{4s} = 0, this equals (p2s−p1s)(p3s−p4s)(p_{2s} - p_{1s})(p_{3s} - p_{4s}), the summand of f4(P2,P1;P3,O)f_4(P_2, P_1; P_3, O).

Proof. (1−p1)p2−p1(1−p2)=p2−p1(1 - p_1) p_2 - p_1 (1 - p_2) = p_2 - p_1. □\square

Lemma 4 (leave-one-out values). Let aj=∑s∈JjABBAsa_j = \sum_{s \in J_j} \text{ABBA}_s, bj=∑s∈JjBABAsb_j = \sum_{s \in J_j} \text{BABA}_s, A=∑jajA = \sum_j a_j and B=∑jbjB = \sum_j b_j. The value of DD on the sites outside JjJ_j is ((A−aj)−(B−bj))/((A−aj)+(B−bj))((A - a_j) - (B - b_j)) / ((A - a_j) + (B - b_j)).

Proof. The sums over the sites outside JjJ_j are A−ajA - a_j and B−bjB - b_j, because the blocks are disjoint and cover all sites. □\square

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 g−1g∑j(D(j)−Dˉ(⋅))2\frac{g - 1}{g} \sum_j (D_{(j)} - \bar D_{(\cdot)})^2.

Lemma 5 (scaling of the jackknife). If the statistic is the mean of gg block values x1,…,xgx_1, \ldots, x_g, the jackknife variance equals s2/gs^2 / g, where s2=1g−1∑j(xj−xˉ)2s^2 = \frac{1}{g - 1} \sum_j (x_j - \bar x)^2 is the sample variance.

Proof. The value without block jj is xˉ(j)=(gxˉ−xj)/(g−1)\bar x_{(j)} = (g \bar x - x_j)/(g - 1), so xˉ(j)−xˉ(⋅)=−(xj−xˉ)/(g−1)\bar x_{(j)} - \bar x_{(\cdot)} = -(x_j - \bar x)/(g - 1), where xˉ(⋅)=xˉ\bar x_{(\cdot)} = \bar x. Then g−1g∑j(xj−xˉ)2/(g−1)2=1g(g−1)∑j(xj−xˉ)2=s2/g\frac{g - 1}{g} \sum_j (x_j - \bar x)^2 / (g - 1)^2 = \frac{1}{g (g - 1)} \sum_j (x_j - \bar x)^2 = s^2 / g. □\square

So the factor (g−1)/g(g - 1)/g makes the jackknife agree with the usual standard error in the linear case. For the ratio DD, 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 P1P_1, P2P_2, P3P_3 and OO, with the copies of P1P_1 and P2P_2 sampled at the same time. The populations form the rooted tree (((P1,P2),P3),O)(((P_1, P_2), P_3), O) 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, P(ABBA)=P(BABA)P(\text{ABBA}) = P(\text{BABA}).

Proof. With one mutation at the site, the pattern is set by the branch ee of the gene tree that carries the mutation: the copies below ee carry B, the others A. An ABBA site needs a branch whose set of copies below it is {2,3}\{2, 3\} (or, for an unrooted reading with OO below the mutation, {1,O}\{1, O\}; both split {2,3}\{2, 3\} from {1,O}\{1, O\}). BABA needs a branch that splits {1,3}\{1, 3\} from {2,O}\{2, O\}.

Let CC be the event that the lineages of P1P_1 and P2P_2 coalesce in the ancestral population of P1P_1 and P2P_2. On CC, copies 1 and 2 form a clade in the gene tree, so no branch splits {2,3}\{2, 3\} from {1,O}\{1, O\}, and no branch splits {1,3}\{1, 3\} from {2,O}\{2, O\}. Both patterns have probability 0 on CC.

On the complement of CC, lineages 1 and 2 enter the ancestral population of P1P_1, P2P_2 and P3P_3 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 P1P_1 and P2P_2, and these times are equal, and under CcC^c the two lineages then stay apart in the ancestor of P1P_1 and P2P_2 for the same length of time. So the map that swaps labels 1 and 2 preserves the law of the whole history on CcC^c, and it maps the event "the mutation splits {2,3}\{2, 3\} from {1,O}\{1, O\}" onto the event "the mutation splits {1,3}\{1, 3\} from {2,O}\{2, O\}". The two events have the same probability. □\square

With frequency data, Lemma 2 writes E[ABBAs−BABAs]E[\text{ABBA}_s - \text{BABA}_s], 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 DD is 0. The theorem uses each assumption of the null model: gene flow into P2P_2 from P3P_3, structure in the ancestor of P1P_1 and P2P_2 that places P2P_2 closer to P3P_3, or a mutation rate that differs between the lineages of P1P_1 and P2P_2 all break the exchange of labels, and then E[ABBA]≠E[BABA]E[\text{ABBA}] \ne E[\text{BABA}] is possible.

Complexity

  • Counts. One pass over the sites: O(n)O(n) time.
  • Jackknife. O(g)O(g) with the totals of line L5. The block sums take O(g)O(g) space.
  • Many tests. For all choices of (P1,P2,P3)(P_1, P_2, P_3) among rr groups, compute the allele frequencies once and each DD in O(n)O(n): O(r3n)O(r^3 n) in total.

Properties

  • Sign. D>0D > 0 means P2P_2 and P3P_3 share more derived alleles than P1P_1 and P3P_3. The test does not say which way the gene flow went.
  • Range. −1≤D≤1-1 \le D \le 1. Its size depends on the time since the split and on the amount of incomplete lineage sorting, so DD is not an estimate of the admixed fraction.
  • Antisymmetry. Swapping P1P_1 and P2P_2 changes the sign of DD and of ZZ.
  • 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 DD.

Variants and improvements

  • Frequencies. The form with pisp_{is} uses all sampled sequences and reduces the variance (Durand and coauthors 2011).
  • The admixed fraction. Martin, Davey and Jiggins (2015) define fdf_d, which compares the observed numerator with the value under complete gene flow, as an estimate of the admixed fraction in a window. f4f_4 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 DFOILD_{\text{FOIL}} statistics for five taxa.
  • Admixture graphs. Several f4f_4 and DD 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 fdf_d.

Pitfalls

  • The null model is narrow. Structure in the common ancestor of P1P_1 and P2P_2, for example a subdivided ancestral population in which P2P_2 split from a deme closer to P3P_3, can give D≠0D \ne 0 with no gene flow after the split (Eriksson and Manica 2012). A significant ZZ 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 DD.
  • 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 SE^\widehat{\mathrm{SE}} too small and ZZ too large.
  • Windows. In small windows DD 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 P1P_1 and P2P_2 are not sister groups, DD 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.

abba_baba.pyI0RawGitHub
# 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 DD under the null model and under gene flow, and the form with allele frequencies. Patterson and coauthors (2012) wrote DD as a normalized f4f_4 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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.

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