Algorithm Search⌘K

Algorithmadvanced

Extended haplotype homozygosity

Also called EHH, integrated haplotype score, iHS.

Detect recent positive selection by how far haplotypes carrying an allele stay identical around it, compared with the other allele.

Time
Θ(n m) worstO(n m) averageΘ(n + m) best
Space
Θ(n + m) extra
Where
m = the number of markers; n = the number of haplotypes
Properties
deterministicexactofflineiterative
Origin
Pardis C. Sabeti, David E. Reich, Eric S. Lander, Benjamin F. Voight, Jonathan K. Pritchard, 2002

Extended haplotype homozygosity (EHH) measures how far around a marker the haplotypes that carry one allele stay identical. For the carriers of allele aa at a core marker, EHH at a marker jj is the fraction of pairs of carriers whose haplotypes are identical at every marker from the core to jj. It is 1 at the core and decreases with distance, because recombination and mutation break the shared haplotypes. A new allele that a selective sweep has pushed to high frequency in a short time sits on long shared haplotypes, so its EHH decays slowly; a neutral allele at the same frequency is usually old, and its EHH decays fast. Sabeti and coauthors defined EHH in 2002. Voight and coauthors in 2006 took the area under the EHH curve of each allele (the integrated EHH, iHH) and used the log ratio of the two areas, standardized by allele frequency, as a genome-wide scan for recent selection.

In plain words

Look at many copies of a chromosome from one population, each a string of 0s and 1s at the marker sites. Pick a site and collect the copies that carry the new allele there. Walk outward from the site, one marker at a time, and ask: what fraction of pairs of these copies are still identical over the whole stretch so far? That fraction is EHH.

If the allele is old, recombination over many generations has cut its copies into many short pieces, and EHH falls quickly. If the allele rose fast because it helped its carriers, there was little time for recombination, and the copies still share one long stretch. Comparing the area under the curve for the new allele with that for the old allele at the same site gives one number per site.

The problem

Input. Phased haplotypes h1,…,hnh_1, \ldots, h_n of mm biallelic markers, with allele 0 (ancestral) or 1 (derived) at each, the map positions x1<⋯<xmx_1 < \cdots < x_m of the markers (genetic distance is best, physical distance is common), a core marker cc, an allele aa with at least two carriers, and a cutoff ϵ≥0\epsilon \ge 0 (often 0.05).

Output. With C={i:hi[c]=a}C = \{i : h_i[c] = a\} and k=∣C∣≥2k = |C| \ge 2, the curve

EHHa(j)=#{{i,i′}⊆C:hi[t]=hi′[t] for all t between c and j}(k2),j=1,…,m,\mathrm{EHH}_a(j) = \frac{\#\{\{i, i'\} \subseteq C : h_i[t] = h_{i'}[t] \text{ for all } t \text{ between } c \text{ and } j\}}{\binom{k}{2}}, \qquad j = 1, \ldots, m,

and the integrated EHH iHHa\mathrm{iHH}_a: the trapezoid area under EHHa\mathrm{EHH}_a over the positions, taken outward from the core on each side and stopped at the first marker where EHHa<ϵ\mathrm{EHH}_a < \epsilon. The score of the core is ln⁡(iHH0/iHH1)\ln(\mathrm{iHH}_0 / \mathrm{iHH}_1). Voight and coauthors standardize it: from the score of each marker, subtract the mean and divide by the standard deviation of the scores of all markers with a similar derived allele frequency.

The algorithm

The carriers are split into classes of identical extended haplotypes, and the classes are refined one marker at a time as the walk moves away from the core. A class of one haplotype adds no pair now or later, so it is dropped.

  1. EHH(H, x, c, a, ε)
  2. 1C ← the haplotypes with allele a at the core c; k ← |C| (at least 2)
  3. 2E[j] ← 0 for every marker j; E[c] ← 1
  4. 3for each side d in (+1, −1) do
  5. 4classes ← [C]; j ← c + d
  6. 5while 1 ≤ j ≤ m and classes is not empty do
  7. 6split each class by the allele at j and keep the parts with 2 or more haplotypes
  8. 7E[j] ← Σ over classes K of C(|K|, 2) / C(k, 2); j ← j + d
  9. 8iHH ← on each side, add (E[j] + E[j − d]) / 2 · |x[j] − x[j − d]| for j = c + d, c + 2d, ... up to the first j with E[j] < ε
  10. 9return E and iHH

The score of the core is ln⁡(iHH0/iHH1)\ln(\mathrm{iHH}_0 / \mathrm{iHH}_1), with two calls of EHH, one for each allele. The implementation also reports, for each side, whether the data ended before EHH fell under ϵ\epsilon. The area of such a marker is cut short, and scans often leave such markers out.

Example

Eight haplotypes with five markers at positions 0, 0.1, 0.2, 0.3 and 0.4 (in centimorgans), and the core at the middle marker 3:

haplotype 1 2 3 (core) 4 5
1 0 1 1 0 1
2 0 1 1 0 1
3 0 1 1 0 0
4 1 1 1 0 1
5 0 0 0 1 0
6 1 0 0 0 1
7 0 1 0 1 1
8 1 0 0 0 0

Derived allele 1. The carriers are haplotypes 1 to 4, with (42)=6\binom{4}{2} = 6 pairs. At marker 4 all have 0, so EHH stays 1. At marker 5, haplotype 3 differs, and the class {1,2,4}\{1, 2, 4\} keeps 3 pairs: EHH =1/2= 1/2. On the left, marker 2 keeps all four, and at marker 1 haplotype 4 differs: EHH =1/2= 1/2. The curve is (1/2,1,1,1,1/2)(1/2, 1, 1, 1, 1/2).

Ancestral allele 0. The carriers are haplotypes 5 to 8. At marker 4 the classes are {5,7}\{5, 7\} and {6,8}\{6, 8\}: EHH =2/6=1/3= 2/6 = 1/3. At marker 5 both classes split: EHH =0= 0. On the left, marker 2 leaves {5,6,8}\{5, 6, 8\}: EHH =3/6=1/2= 3/6 = 1/2, and marker 1 leaves {6,8}\{6, 8\}: EHH =1/6= 1/6. The curve is (1/6,1/2,1,1/3,0)(1/6, 1/2, 1, 1/3, 0).

Areas with ϵ=0.05\epsilon = 0.05. For allele 1, each side gives 1+12⋅0.1+1+0.52⋅0.1=0.175\frac{1 + 1}{2} \cdot 0.1 + \frac{1 + 0.5}{2} \cdot 0.1 = 0.175, so iHH1=0.35\mathrm{iHH}_1 = 0.35, and the data end before EHH falls under 0.05. For allele 0, the left side gives 0.075+0.5+1/62⋅0.1=0.10830.075 + \frac{0.5 + 1/6}{2} \cdot 0.1 = 0.1083, and the right side gives 1+1/32⋅0.1=0.0667\frac{1 + 1/3}{2} \cdot 0.1 = 0.0667 and stops at marker 5, where EHH is 0. So iHH0=0.175\mathrm{iHH}_0 = 0.175 and the score is ln⁡(0.175/0.35)=ln⁡0.5=−0.693\ln(0.175 / 0.35) = \ln 0.5 = -0.693: the derived allele sits on longer shared haplotypes.

Correctness

The proof keeps one invariant on each side: after the walk has processed marker jj, the list of classes holds exactly the classes, of size 2 or more, of the relation "identical at every marker from the core to jj" on the carriers. Line L6 keeps the invariant, because two carriers are identical up to jj exactly when they are identical up to the marker before jj and have the same allele at jj. A pair of carriers that are identical up to jj lies in one class, so line L7 counts each such pair once, and the sum over classes of (∣K∣2)\binom{|K|}{2} is the numerator of the definition. When the list is empty, no pair is identical up to jj, so no pair is identical further out, and the zeros of line L2 are correct for the markers that the walk does not reach. Line L8 is the trapezoid rule on the points it visits. The full proof is below.

Proof: EHH returns the fraction of carrier pairs identical from the core to each marker, and the trapezoid area of that curvefull

Setting. Haplotypes h1,…,hnh_1, \ldots, h_n have mm markers each, at positions x1<⋯<xmx_1 < \cdots < x_m. The core is cc, the allele is aa, the carriers are C={i:hi[c]=a}C = \{i : h_i[c] = a\}, and k=∣C∣≥2k = |C| \ge 2. For a marker jj, let I(j)I(j) be the set of markers between cc and jj, with both ends included. Two carriers ii and i′i' are jj-equal when they have the same allele at every marker of I(j)I(j). This is an equivalence relation on CC, and EHH(j)\mathrm{EHH}(j) is the number of unordered jj-equal pairs over (k2)\binom{k}{2}.

Lemma 1 (refinement). Let dd be +1+1 or −1-1, let jj be the core or a marker between the core and j+dj + d, and let j′=j+dj' = j + d be a marker. Then ii and i′i' are j′j'-equal exactly when they are jj-equal and have the same allele at j′j'.

Proof. I(j′)=I(j)∪{j′}I(j') = I(j) \cup \{j'\}. □\square

Lemma 2 (the invariant). On one side dd, after line L7 has run for the marker jj, the list of classes holds exactly the classes of the jj-equal relation that have two or more members, each one once.

Proof. By induction over the markers of the side. Before the first pass, the list is [C][C], which is right: all carriers have allele aa at the core, and I(c)={c}I(c) = \{c\}, so CC is the only class, and it has k≥2k \ge 2 members.

Suppose the list holds the classes of the jj-equal relation with two or more members, and line L6 runs for j′=j+dj' = j + d. By Lemma 1, every class of the j′j'-equal relation is the set of members of one class KK of the jj-equal relation that share one allele at j′j'. A class of the j′j'-equal relation with two or more members is inside such a KK, which then also has two or more members, so KK is in the list, and line L6 forms that part and keeps it. Every part that line L6 keeps has two or more members and is a class of the j′j'-equal relation. Parts of different classes KK are disjoint, so no class is listed twice. □\square

Lemma 3 (the value at the markers the walk reaches). Line L2 gives E[c]=1=EHH(c)E[c] = 1 = \mathrm{EHH}(c), and line L7 sets E[j]=EHH(j)E[j] = \mathrm{EHH}(j) for every marker jj that the walk reaches.

Proof. At the core, all (k2)\binom{k}{2} pairs are cc-equal, so EHH(c)=1\mathrm{EHH}(c) = 1. For a marker jj of the walk, a jj-equal pair lies in one class of the jj-equal relation, and that class then has two or more members. A class of ss members holds (s2)\binom{s}{2} pairs of its own members, and all of them are jj-equal. So, by Lemma 2, the sum of (∣K∣2)\binom{|K|}{2} over the list is the number of jj-equal pairs, and line L7 divides it by (k2)\binom{k}{2}. □\square

Lemma 4 (the markers the walk does not reach). If the walk on side dd stops at a marker jj because the list is empty, then EHH(t)=0\mathrm{EHH}(t) = 0 for every marker tt that is further from the core than j−dj - d on that side. This is the value that line L2 left there.

Proof. The list became empty when line L6 ran for j−dj - d, so by Lemma 2 no pair is (j−d)(j-d)-equal. For such a tt, I(j−d)I(j - d) is a subset of I(t)I(t), so a tt-equal pair would also be (j−d)(j-d)-equal. There is none. □\square

Lemma 5 (the curve is monotone). EHH(c)=1\mathrm{EHH}(c) = 1, and EHH\mathrm{EHH} does not increase as the marker moves away from the core on either side.

Proof. By Lemma 1, every j′j'-equal pair is also jj-equal, so the numerator does not increase. □\square

Lemma 6 (the area). On one side dd, line L8 adds the term (E[j]+E[j−d])⋅∣xj−xj−d∣/2(E[j] + E[j-d]) \cdot |x_j - x_{j-d}| / 2 for the markers j=c+d,c+2d,…j = c + d, c + 2d, \ldots, in this order, and stops before the first marker with E[j]<ϵE[j] < \epsilon, or at the end of the marker list. The total is the integral, from xcx_c to the position of the last marker it added, of the piecewise linear function that passes through the points (xt,E[t])(x_t, E[t]).

Proof. The loop of line L8 visits the markers of the side in order from the core and stops at the first jj with E[j]<ϵE[j] < \epsilon without adding its term, so the markers it adds are exactly those listed. The term of jj is the area of the trapezoid with the parallel sides E[j−d]E[j-d] and E[j]E[j] and the width ∣xj−xj−d∣|x_j - x_{j-d}|, which is the integral of the linear piece between the two positions. The pieces are next to each other and cover the interval from xcx_c to the last added position, so the sum is the integral over that interval. □\square

Theorem. For input haplotypes of one length, a core marker cc and an allele aa with k≥2k \ge 2 carriers, EHH returns the array EE with E[j]=EHH(j)E[j] = \mathrm{EHH}(j) for every marker jj, and the number iHH, which is the sum over the two sides of the integral of Lemma 6. The values are exact rational numbers, because every step uses only integer counts and one division by (k2)\binom{k}{2}.

Proof. Line L1 forms CC by one pass over the core column and rejects k<2k < 2. Lines L3 to L7 run the walk on both sides, and each side sets the values of its own markers only. By Lemma 3 the markers that the walk reaches get EHH\mathrm{EHH}, and by Lemma 4 the others already hold their correct value 0 from line L2. The core gets 1 at line L2 and no walk changes it, because each walk starts at c+dc + d. So EE is the EHH curve. Line L8 then returns the area of Lemma 6 for each side, and iHH is their sum. The implementation keeps the counts as integers and the values as fractions, so no rounding takes place. □\square

The score. For a core marker where both alleles have two or more carriers and both areas are positive, the score is ln⁡(iHH0/iHH1)\ln(\mathrm{iHH}_0 / \mathrm{iHH}_1), from one call of EHH per allele. It is 0 when the two curves give equal areas, negative when the derived allele has the larger area, and positive when the ancestral allele does.

A check of the scale. Suppose the nn haplotypes are independent and every marker of every haplotype is 0 or 1 with probability one half each, independently. Fix the core allele of the carriers. Two carriers agree at a given marker away from the core with probability one half, independently over the markers, so each pair is jj-equal with probability 2−∣I(j)∣+12^{-|I(j)| + 1}, that is 2−r2^{-r} for a marker rr steps from the core. By linearity over the (k2)\binom{k}{2} pairs, the mean of EHH\mathrm{EHH} at that marker is 2−r2^{-r}. The tests use this to check the curve against its exact mean.

Complexity

  • Time for one curve. Line L1 reads one column: Θ(n)\Theta(n). Each marker on the walk reads the allele of every haplotype that is still in a class, at most k≤nk \le n, so the walk costs O(nm)O(n m). It is Θ(nm)\Theta(n m) when the carriers share haplotypes over the whole region, for example when all are identical. When the classes empty fast, the walk stops after a few markers, and the cost is Θ(n+m)\Theta(n + m) with the zeros of line L2.
  • Area. Line L8 visits each marker at most once: O(m)O(m).
  • A genome scan. A score for every marker needs mm curves. With the walk of each curve stopped at the cutoff, the cost is the sum of the lengths of the walks, which is usually much less than nm2n m^2 in real data.
  • Space. The classes hold each carrier at most once, and E has mm entries: Θ(n+m)\Theta(n + m).

Properties

  • Values. EHHa(c)=1\mathrm{EHH}_a(c) = 1, and EHHa\mathrm{EHH}_a does not increase as jj moves away from the core, because the relation only gets finer.
  • Meaning. EHHa(j)\mathrm{EHH}_a(j) is the probability that two carriers drawn without replacement are identical from the core to jj. If the haplotypes are independent and the markers are independent fair coins, its mean at jj markers from the core is 2−j2^{-j}.
  • Allele frequency matters. Under neutrality, the expected length of the shared haplotypes of an allele depends on its frequency. This is why the score is standardized within frequency bins and not across the whole genome.
  • Both alleles in one sample. The two alleles share the same local recombination rate and the same demographic history, so their comparison removes much of the effect of these factors.
  • Sign. A large negative score marks a derived allele on unusually long haplotypes; a large positive score marks an ancestral allele on unusually long haplotypes. Scans often rank markers by the absolute value of the standardized score.

Variants and improvements

  • Core haplotypes. Sabeti and coauthors used as cores short haplotypes of several close markers, not single markers, and compared the EHH of one core haplotype with the combined EHH of the other core haplotypes (the relative EHH).
  • Between populations. Sabeti and coauthors in 2007 compared the integrated EHH of the same marker in two populations (XP-EHH); Tang, Thornton and Stoneking defined a similar statistic (Rsb). These find sweeps that are complete or almost complete in one population, where the within-population score has little power because one allele is rare.
  • Haplotype counting statistics. The number of distinct haplotypes and the haplotype homozygosity in a window (for example the H12 statistic of Garud and coauthors) find soft sweeps, where several haplotypes carry the favoured allele.
  • Unphased data. Some programs compute versions of these statistics from unphased genotypes.
  • Fast software. Programs such as rehh and selscan compute EHH and the scores for whole genomes, with different truncation rules and different ways to handle gaps in the marker map.

When to use it

Use it to scan phased data from one population for recent and incomplete sweeps, where a favoured allele is at intermediate or high frequency and has not yet fixed. It finds only recent selection, because recombination breaks the long haplotypes within a number of generations of the order of one over the recombination rate of the region. This is a much shorter time scale than that of tests on divergence between species, such as the McDonald-Kreitman test. For complete sweeps, use comparisons between populations or the site frequency spectrum.

Pitfalls

  • Phasing errors. Switch errors in haplotype phasing break long haplotypes and lower EHH.
  • Recombination rate. EHH decays slowly in regions of low recombination even without selection. Use genetic map positions, or compare the two alleles at the same marker.
  • Ancestral allele. The sign of the score depends on knowing which allele is ancestral, which usually comes from an outgroup and can be wrong.
  • Rare alleles. With few carriers, EHH has few pairs and is very noisy. Scans leave out markers with a minor allele frequency below a threshold, such as 5%.
  • Edges and gaps. At the end of a chromosome, or near a large gap between markers, the area is cut short or made too large. Mark such markers and treat them apart.
  • Demography. Bottlenecks and admixture make long haplotypes too. The standardized score is an outlier measure, not a test with a known null distribution; check outliers with simulations under a fitted demographic model, for example with coalescent simulation.
  • Missing data. The method needs a full haplotype matrix. Impute or remove missing calls before the scan.

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.

extended_haplotype_homozygosity.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-haplotype-homozygosity/. The authors are listed in prov/DC6Q95.jsonl.
"""Extended haplotype homozygosity (Sabeti and coauthors 2002) and the
integrated EHH log ratio of Voight and coauthors (2006).

Input: phased haplotypes as equal-length sequences of 0 and 1 (0 is the
ancestral allele, 1 the derived allele), the map positions of the markers in
increasing order, and the index of the core marker.

EHH. For the carriers of allele a at the core, EHH at marker j is the
fraction of pairs of carriers that are identical at every marker from the
core to j (both ends included). It is 1 at the core and does not increase
when j moves away from the core.

Integrated EHH. On each side, the area under EHH by the trapezoid rule over
the map positions, from the core outward, over the segments whose outer end
has EHH >= cutoff; the sum stops at the first marker with EHH < cutoff. The
flags reached_left and reached_right say that the data ended before EHH fell
under the cutoff. Programs differ in this truncation rule.

Score. ln(iHH of the ancestral allele / iHH of the derived allele). It is
negative when the derived allele sits on long shared haplotypes. The
standardized score subtracts the mean and divides by the standard deviation
of the scores of markers with a similar derived allele frequency.
"""

from __future__ import annotations

import math
from fractions import Fraction
from math import comb
from typing import List, NamedTuple, Sequence


class IHH(NamedTuple):
    value: float
    reached_left: bool
    reached_right: bool


def carriers(haps: Sequence[Sequence[int]], core: int, allele: int) -> List[int]:
    """The indices of the haplotypes with the given allele at the core."""
    return [i for i, h in enumerate(haps) if h[core] == allele]


def ehh_curve(haps: Sequence[Sequence[int]], core: int, allele: int) -> List[Fraction]:
    """EHH of the carriers of allele at every marker, as exact fractions."""
    if not haps:
        raise ValueError("need haplotypes")
    m = len(haps[0])
    if any(len(h) != m for h in haps) or not 0 <= core < m:
        raise ValueError("haplotypes must have one length and core must be a marker")
    group = carriers(haps, core, allele)  # @line L1
    k = len(group)
    if k < 2:
        raise ValueError("need at least two carriers of the allele")
    pairs = comb(k, 2)
    e = [Fraction(0)] * m  # @line L2
    e[core] = Fraction(1)
    for step in (1, -1):  # @line L3
        classes = [group]  # @line L4
        j = core + step
        while 0 <= j < m and classes:  # @line L5
            split = []
            for cls in classes:  # @line L6
                parts = {}
                for i in cls:
                    parts.setdefault(haps[i][j], []).append(i)
                split.extend(p for p in parts.values() if len(p) >= 2)
            classes = split
            e[j] = Fraction(sum(comb(len(c), 2) for c in classes), pairs)  # @line L7
            j += step
    return e


def integrated_ehh(e: Sequence[Fraction], positions: Sequence[float], core: int,
                   cutoff: float = 0.05) -> IHH:
    """The trapezoid area under the EHH curve e, truncated at the cutoff."""
    if len(e) != len(positions):
        raise ValueError("one position per marker")
    if any(positions[i] >= positions[i + 1] for i in range(len(positions) - 1)):
        raise ValueError("positions must increase")
    area = 0.0
    reached = []
    for step in (-1, 1):
        j = core + step
        done = False
        while 0 <= j < len(e):  # @line L8
            if e[j] < cutoff:
                done = True
                break
            area += (float(e[j]) + float(e[j - step])) / 2.0 * abs(positions[j] - positions[j - step])
            j += step
        reached.append(not done)
    return IHH(area, reached[0], reached[1])  # @line L9


def ihh_log_ratio(haps: Sequence[Sequence[int]], positions: Sequence[float], core: int,
                  cutoff: float = 0.05) -> float:
    """ln(iHH of allele 0 / iHH of allele 1) at the core marker."""
    a = integrated_ehh(ehh_curve(haps, core, 0), positions, core, cutoff).value
    d = integrated_ehh(ehh_curve(haps, core, 1), positions, core, cutoff).value
    if a <= 0.0 or d <= 0.0:
        raise ValueError("an integrated EHH is 0; the log ratio is not defined")
    return math.log(a / d)


def standardize(scores: Sequence[float], freqs: Sequence[float], n_bins: int = 20) -> List[float]:
    """(score - bin mean) / bin standard deviation, with bins of equal width in
    the derived allele frequency. A bin with fewer than two scores, or with
    standard deviation 0, gives nan for its markers."""
    if len(scores) != len(freqs):
        raise ValueError("one frequency per score")
    bins = [min(int(f * n_bins), n_bins - 1) for f in freqs]
    out = [math.nan] * len(scores)
    for b in set(bins):
        idx = [i for i, x in enumerate(bins) if x == b]
        if len(idx) < 2:
            continue
        mean = sum(scores[i] for i in idx) / len(idx)
        sd = math.sqrt(sum((scores[i] - mean) ** 2 for i in idx) / (len(idx) - 1))
        if sd == 0.0:
            continue
        for i in idx:
            out[i] = (scores[i] - mean) / sd
    return out
test_extended_haplotype_homozygosity.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-haplotype-homozygosity/. The authors are listed in prov/DC6Q95.jsonl.

import math
import random
from fractions import Fraction
from itertools import combinations

import pytest

from extended_haplotype_homozygosity import (carriers, ehh_curve, ihh_log_ratio, integrated_ehh,
                                             standardize)

EXAMPLE = ["01101", "01101", "01100", "11101", "00010", "10001", "01011", "10000"]
HAPS = [[int(c) for c in h] for h in EXAMPLE]
POS = [0.0, 0.1, 0.2, 0.3, 0.4]


def brute_ehh(haps, core, allele, j):
    """The fraction of pairs of carriers identical at all markers between core and j."""
    group = carriers(haps, core, allele)
    lo, hi = min(core, j), max(core, j)
    pairs = list(combinations(group, 2))
    same = sum(1 for a, b in pairs if haps[a][lo:hi + 1] == haps[b][lo:hi + 1])
    return Fraction(same, len(pairs))


def random_haps(rng, n, m, p=0.5):
    return [[1 if rng.random() < p else 0 for _ in range(m)] for _ in range(n)]


def test_example_curves():
    assert ehh_curve(HAPS, 2, 1) == [Fraction(1, 2), 1, 1, 1, Fraction(1, 2)]
    assert ehh_curve(HAPS, 2, 0) == [Fraction(1, 6), Fraction(1, 2), 1, Fraction(1, 3), 0]
    d = integrated_ehh(ehh_curve(HAPS, 2, 1), POS, 2)
    a = integrated_ehh(ehh_curve(HAPS, 2, 0), POS, 2)
    assert d.value == pytest.approx(0.35) and d.reached_left and d.reached_right
    assert a.value == pytest.approx(0.175) and a.reached_left and not a.reached_right
    assert ihh_log_ratio(HAPS, POS, 2) == pytest.approx(math.log(0.5))


def test_against_brute_force():
    rng = random.Random(2002)
    for _ in range(200):
        n, m = rng.randrange(3, 12), rng.randrange(1, 9)
        haps = random_haps(rng, n, m, rng.choice([0.2, 0.5, 0.8]))
        core = rng.randrange(m)
        for allele in (0, 1):
            if len(carriers(haps, core, allele)) < 2:
                with pytest.raises(ValueError):
                    ehh_curve(haps, core, allele)
                continue
            e = ehh_curve(haps, core, allele)
            assert e == [brute_ehh(haps, core, allele, j) for j in range(m)]
            # 1 at the core, and never larger away from it.
            assert e[core] == 1
            assert all(e[j] >= e[j - 1] for j in range(1, core + 1))
            assert all(e[j] <= e[j - 1] for j in range(core + 1, m))


def test_integration_rule():
    e = [Fraction(1, 10), Fraction(1, 2), Fraction(1), Fraction(1, 2), Fraction(1, 50), Fraction(1, 50)]
    pos = [0.0, 1.0, 3.0, 4.0, 6.0, 7.0]
    r = integrated_ehh(e, pos, 2)
    # Left: (1 + 1/2)/2 * 2 + (1/2 + 1/10)/2 * 1; right: (1 + 1/2)/2 * 1, then stop at 1/50.
    assert r.value == pytest.approx(1.5 + 0.3 + 0.75)
    assert r.reached_left and not r.reached_right
    assert integrated_ehh(e, pos, 2, cutoff=0.0).value == pytest.approx(1.5 + 0.3 + 0.75 + 0.52 + 0.02)
    with pytest.raises(ValueError):
        integrated_ehh(e, [0.0, 1.0, 1.0, 2.0, 3.0, 4.0], 2)


def test_mean_under_independent_markers():
    # With independent fair markers, two carriers agree at j markers next to
    # the core with probability 2^-j, so the mean of EHH is 2^-j exactly.
    rng = random.Random(7)
    reps, n, m, core = 400, 20, 6, 0
    sums = [[] for _ in range(m)]
    for _ in range(reps):
        haps = random_haps(rng, n, m)
        for h in haps:
            h[core] = 1
        e = ehh_curve(haps, core, 1)
        for j in range(m):
            sums[j].append(float(e[j]))
    for j in range(1, m):
        xs = sums[j]
        mean = sum(xs) / reps
        sd = math.sqrt(sum((x - mean) ** 2 for x in xs) / (reps - 1))
        assert abs(mean - 2.0 ** -j) <= 4 * sd / math.sqrt(reps) + 1e-12


def sweep_sample(rng, n_derived, n_ancestral, m, core, rate):
    """Derived carriers copy one founder haplotype; each copy keeps it on each
    side up to a break after an exponential number of markers, and has random
    alleles beyond. Ancestral carriers have random alleles."""
    founder = [rng.randrange(2) for _ in range(m)]
    haps = []
    for _ in range(n_derived):
        h = [rng.randrange(2) for _ in range(m)]
        left = core - int(rng.expovariate(rate))
        right = core + int(rng.expovariate(rate))
        for j in range(max(0, left), min(m, right + 1)):
            h[j] = founder[j]
        h[core] = 1
        haps.append(h)
    for _ in range(n_ancestral):
        h = [rng.randrange(2) for _ in range(m)]
        h[core] = 0
        haps.append(h)
    return haps


def test_sweep_gives_negative_scores():
    rng = random.Random(42)
    m, core = 41, 20
    pos = [0.01 * j for j in range(m)]
    scores = [ihh_log_ratio(sweep_sample(rng, 15, 15, m, core, 0.1), pos, core) for _ in range(40)]
    assert sum(1 for s in scores if s < 0) >= 36
    assert sum(scores) / len(scores) < -1.0


def test_standardize():
    rng = random.Random(5)
    freqs = [rng.random() for _ in range(400)]
    scores = [rng.gauss(3 * f, 1 + f) for f in freqs]
    z = standardize(scores, freqs, n_bins=4)
    for b in range(4):
        zs = [z[i] for i in range(400) if min(int(freqs[i] * 4), 3) == b]
        mean = sum(zs) / len(zs)
        var = sum((x - mean) ** 2 for x in zs) / (len(zs) - 1)
        assert abs(mean) < 1e-9 and abs(var - 1) < 1e-9
    lone = standardize([1.0, 2.0, 5.0], [0.1, 0.12, 0.9], n_bins=2)
    assert math.isnan(lone[2]) and lone[0] == pytest.approx(-math.sqrt(0.5))

History

Sabeti and coauthors introduced EHH in 2002 and used it to show recent selection on haplotypes of G6PD and of the CD40 ligand gene, which are linked to resistance to malaria. Voight and coauthors in 2006 integrated EHH over the genetic map, took the log ratio for the ancestral and derived alleles of each marker, standardized it by frequency, and made a genome-wide map of candidate sweeps from the HapMap data. Later work extended the idea to comparisons between populations and to soft sweeps.

References

  1. Pardis C. Sabeti and coauthors, Detecting recent positive selection in the human genome from haplotype structure, Nature 419(6909), 2002, pp. 832-837 (the definition of EHH for a core haplotype and its decay with distance)
  2. Benjamin F. Voight, Sridhar Kudaravalli, Xiaoquan Wen and Jonathan K. Pritchard, A map of recent positive selection in the human genome, PLoS Biology 4(3), 2006, e72, Materials and Methods (the integrated EHH of each allele, the log ratio and its standardization in frequency bins)

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
  • at least three sources
  • a scene preset for the example