Algorithm Search⌘K

Algorithmadvanced

Lander-Green algorithm

Also called Lander-Green HMM, multipoint linkage HMM.

Computes multipoint pedigree likelihoods with a hidden Markov model over inheritance vectors along the chromosome. Linear in the markers, exponential in the meioses.

Time
Θ(M 2^b (b + n)) worst · average · best
Space
Θ(M 2^b) extra
Where
M = the number of markers; b = the number of meioses (twice the number of non-founders); n = the number of people
Properties
deterministicexactofflineiterative
Origin
Eric S. Lander, Philip Green, 1987

The Lander-Green algorithm computes the likelihood of marker data on a pedigree for many linked markers at once. Its hidden state at each marker is the inheritance vector, one bit per meiosis saying whether the parent passed on its paternal or its maternal gene. Along the chromosome these vectors form a Markov chain, so the forward-backward algorithm gives the likelihood and the posterior of every vector. The cost is linear in the number of markers and exponential in the number of meioses, the opposite trade from the Elston-Stewart algorithm.

In plain words

In a family tree, each child got one of two genes from the father and one of two from the mother. Writing down these choices for every child gives a short string of bits. If we knew the bits, we would know which genes are copies of the same gene from a grandparent, and the chance of the marker data would be easy to work out. We do not know them, but along the chromosome they change only where a crossover happened, and crossovers are rare between close markers. So the bits behave like the hidden states of a hidden Markov model: they change from marker to marker with a known small chance, and each marker gives evidence about them. A forward sweep along the chromosome adds up over all bit strings at all markers, and a backward sweep tells how likely each string is at each point.

The problem

Input. A pedigree with ff founders and kk non-founders, so b=2kb = 2k meioses. For each of MM ordered markers on one chromosome: the allele frequencies qjq_j and the unordered genotypes DjD_j of the typed people. For each pair of adjacent markers: the recombination fraction θj\theta_j, for example θ=12(1−e−2d)\theta = \tfrac12 (1 - e^{-2d}) for a map distance of dd Morgans under the Haldane map function.

Model. The inheritance vector Vj∈{0,1}bV_j \in \{0, 1\}^b at marker jj is uniform at the first marker. Between markers jj and j+1j + 1, each bit flips with probability θj\theta_j, independently (no interference). Given VjV_j, each person carries two known founder genes, and the founder genes get independent alleles with frequencies qjq_j.

Output. The likelihood L=Pr⁡(D1,…,DM)L = \Pr(D_1, \ldots, D_M) and the posterior Pr⁡(Vj=v∣D1,…,DM)\Pr(V_j = v \mid D_1, \ldots, D_M) for every marker jj and vector vv. From the posterior follow the identity by descent probabilities of any pair of relatives at every marker.

The algorithm

The emission ej(v)=Pr⁡(Dj∣Vj=v)e_j(v) = \Pr(D_j \mid V_j = v) is computed on a small graph: its nodes are the founder genes, and each typed person is an edge between the two founder genes that it carries under vv. In a connected part of this graph, the allele of one gene fixes the alleles of all others, so there are at most two fitting assignments. The transition matrix A(u,v)=θh(u,v)(1−θ)b−h(u,v)A(u, v) = \theta^{h(u, v)} (1 - \theta)^{b - h(u, v)}, with hh the Hamming distance, is a Kronecker product of bb matrices of size 2×22 \times 2. So it acts on a vector one bit at a time.

  1. LANDER-GREEN(pedigree, D, q, θ)
  2. 1e_j(v) ← P(D_j | V_j = v) for each marker j and vector v, by the founder gene graph
  3. 2α(v) ← 2^-b · e_1(v) for each v
  4. 3for j ← 1 to M do
  5. 4if j > 1 then α ← A(θ_{j-1}) α, applied one bit at a time
  6. 5α(v) ← α(v) · e_j(v) for each v
  7. 6c_j ← sum of α; if c_j = 0 then fail (Mendel error); α_j ← α / c_j
  8. 7log L ← sum over j of log c_j
  9. 8β_M ← 1; for j ← M - 1 down to 1 do β_j ← A(θ_j) (e_{j+1} · β_{j+1}) / c_{j+1}
  10. 9post_j(v) ← α_j(v) · β_j(v), and post_M ← α_M

The scaling by cjc_j in line L6 keeps the numbers in range on long chromosomes and gives the log-likelihood directly.

Example

Take a father with genotype 1/2, a mother with 3/4, and two children who are both 1/3, at a marker with four alleles of frequency 1/41/4. The vector has 4 bits: the paternal and maternal choices of child A and of child B, so 16 vectors.

  • Both children got allele 1 from the father and allele 3 from the mother. So under a fitting vector the paternal bits of A and B are equal, and so are the maternal bits. Four of the 16 vectors fit, one for each choice of which gene of each parent carries the allele 1 or 3.
  • Under each of them the four founder genes have fixed alleles, so e1(v)=(1/4)4=1/256e_1(v) = (1/4)^4 = 1/256, and L=4⋅2−4⋅(1/256)=1/1024L = 4 \cdot 2^{-4} \cdot (1/256) = 1/1024.
  • Under every fitting vector the sibs share both founder genes, so they are IBD 2 at this marker with probability 1.

Add an untyped marker at θ=0.1\theta = 0.1 from the first. The sibs still share the paternal gene when both or neither of their paternal meioses recombine, with probability 0.92+0.12=0.820.9^2 + 0.1^2 = 0.82, and the same holds for the maternal gene. So at the second marker the sibs are IBD 2 with probability 0.822=0.67240.82^2 = 0.6724, IBD 1 with probability 2⋅0.82⋅0.18=0.29522 \cdot 0.82 \cdot 0.18 = 0.2952 and IBD 0 with probability 0.182=0.03240.18^2 = 0.0324. The implementation returns these numbers.

Correctness

The vectors form a Markov chain, and the data at a marker depend only on the vector there, so the model is a hidden Markov model. The emission is right because a founder gene graph with one fixed allele has at most one fitting assignment per connected part, which the search finds and checks. The transition is right because AA is the Kronecker product of the 2×22 \times 2 flip matrices, so applying them bit by bit is the full product. By induction, αj\alpha_j is the posterior of VjV_j given the data up to marker jj and cjc_j is the probability of DjD_j given the earlier data, so ∏jcj=L\prod_j c_j = L by the chain rule. The backward pass gives the rest, and the product αjβj\alpha_j \beta_j is the full posterior because the past and the future data are independent given VjV_j. The full proof is below.

Proof: The Lander-Green recursion returns the multipoint likelihood and the posterior of the inheritance vectorsfull

The model. A pedigree has kk non-founders and so b=2kb = 2k meioses. At marker j∈{1,…,M}j \in \{1, \ldots, M\} the inheritance vector Vj∈{0,1}bV_j \in \{0, 1\}^b records, for each meiosis, whether the parent passed its paternal or its maternal gene. Each founder ii has two founder genes (i,0)(i, 0) and (i,1)(i, 1), and VjV_j fixes, for each person, the two founder genes that the person carries. The assumptions are:

  1. V1V_1 is uniform on {0,1}b\{0, 1\}^b (Mendel's first law).
  2. Given VjV_j, each bit of Vj+1V_{j+1} differs from the bit of VjV_j with probability θj\theta_j, independently of the other bits and of V1,…,Vj−1V_1, \ldots, V_{j-1} (no interference, the same θj\theta_j in both sexes).
  3. At marker jj, the founder genes get independent alleles with the frequencies qjq_j, independently over markers (linkage equilibrium) and of the vectors.

Let DjD_j be the genotypes of the typed people at marker jj and ej(v)=Pr⁡(Dj∣Vj=v)e_j(v) = \Pr(D_j \mid V_j = v). Then (Vj)(V_j) is a Markov chain and DjD_j depends only on VjV_j: a hidden Markov model. The likelihood is

L=∑v1,…,vM2−be1(v1)∏j=2MAj−1(vj−1,vj) ej(vj),Aj(u,v)=θjh(u,v)(1−θj)b−h(u,v),L = \sum_{v_1, \ldots, v_M} 2^{-b} e_1(v_1) \prod_{j=2}^{M} A_{j-1}(v_{j-1}, v_j) \, e_j(v_j), \qquad A_j(u, v) = \theta_j^{h(u, v)} (1 - \theta_j)^{b - h(u, v)},

where hh is the Hamming distance.

Lemma 1 (emission). The function emission returns ej(v)e_j(v).

Proof. Fix vv. By assumption 3, ej(v)e_j(v) is the sum over all labellings xx of the founder genes with alleles of ∏uqj(xu)\prod_u q_j(x_u), restricted to the labellings under which every typed person shows its genotype. Build the graph Γ\Gamma whose nodes are the founder genes and with one edge {u,w}\{u, w\} for each typed person who carries uu and ww, labelled with the person's unordered genotype {a,b}\{a, b\}. A person who carries the same founder gene twice gives a loop at uu. A labelling fits the data exactly when, for each edge, {xu,xw}={a,b}\{x_u, x_w\} = \{a, b\} as multisets. This condition is a product of conditions on the components of Γ\Gamma, and the founder genes outside Γ\Gamma are free. So the sum factors into a product over the components, times ∑aqj(a)=1\sum_a q_j(a) = 1 for each free gene.

In one component, choose a start node ss with an edge labelled {a,b}\{a, b\}. A fitting labelling has xs∈{a,b}x_s \in \{a, b\}. Given xsx_s, each edge {u,w}\{u, w\} with xux_u known forces xwx_w: it is the other element of the multiset when xux_u is in it, and no labelling fits when xux_u is not in it. The component is connected, so the search reaches every node, and the labelling is unique if it exists. The search also checks every edge, including the loops and the edges that close cycles. So the component has at most two fitting labellings, one for each value of xsx_s, and the code adds the weight of each one that passes all checks. If a component has none, ej(v)=0e_j(v) = 0. □\square

Lemma 2 (transition). The function transition returns AjxA_j x for a vector xx of length 2b2^b.

Proof. Write B=(1−θθθ1−θ)B = \begin{pmatrix} 1 - \theta & \theta \\ \theta & 1 - \theta \end{pmatrix}. Since Aj(u,v)=∏t=1bB(ut,vt)A_j(u, v) = \prod_{t=1}^{b} B(u_t, v_t), AjA_j is the Kronecker product of bb copies of BB, which is the product of the bb commuting matrices I⊗⋯⊗B⊗⋯⊗II \otimes \cdots \otimes B \otimes \cdots \otimes I with BB at position tt. Pass tt of the loop replaces each pair (xv,xv+2t)(x_v, x_{v + 2^t}) with bit tt of vv equal to 0 by BB times the pair, which is the action of the factor with BB at position tt. □\square

Lemma 3 (forward pass). For each jj, after line L6, cj=Pr⁡(Dj∣D1,…,Dj−1)c_j = \Pr(D_j \mid D_1, \ldots, D_{j-1}) and αj(v)=Pr⁡(Vj=v∣D1,…,Dj)\alpha_j(v) = \Pr(V_j = v \mid D_1, \ldots, D_j).

Proof. By induction on jj. For j=1j = 1, line L2 gives 2−be1(v)=Pr⁡(V1=v,D1)2^{-b} e_1(v) = \Pr(V_1 = v, D_1), and its sum is c1=Pr⁡(D1)c_1 = \Pr(D_1). Dividing by c1c_1 gives the posterior. For j>1j > 1, by the Markov property and since D1,…,Dj−1D_1, \ldots, D_{j-1} depend on VjV_j only through Vj−1V_{j-1},

Pr⁡(Vj=v∣D1..j−1)=∑uαj−1(u)Aj−1(u,v).\Pr(V_j = v \mid D_{1..j-1}) = \sum_u \alpha_{j-1}(u) A_{j-1}(u, v).

Aj−1A_{j-1} is symmetric, so this is (Aj−1αj−1)(v)(A_{j-1} \alpha_{j-1})(v), which line L4 computes by Lemma 2. Line L5 multiplies by ej(v)=Pr⁡(Dj∣Vj=v,D1..j−1)e_j(v) = \Pr(D_j \mid V_j = v, D_{1..j-1}) to get Pr⁡(Vj=v,Dj∣D1..j−1)\Pr(V_j = v, D_j \mid D_{1..j-1}), whose sum over vv is cjc_j. Dividing gives αj\alpha_j. □\square

Theorem 1. Line L7 returns log⁡L\log L.

Proof. By the chain rule L=Pr⁡(D1,…,DM)=∏jPr⁡(Dj∣D1..j−1)=∏jcjL = \Pr(D_1, \ldots, D_M) = \prod_j \Pr(D_j \mid D_{1..j-1}) = \prod_j c_j by Lemma 3. □\square

If some cj=0c_j = 0, then L=0L = 0: no inheritance vector fits the data at marker jj, which is a Mendelian inconsistency, and the code raises an error.

Theorem 2. Line L9 sets postj(v)=Pr⁡(Vj=v∣D1,…,DM)\text{post}_j(v) = \Pr(V_j = v \mid D_1, \ldots, D_M).

Proof. Let βj(v)=Pr⁡(Dj+1..M∣Vj=v)/∏i>jci\beta_j(v) = \Pr(D_{j+1..M} \mid V_j = v) / \prod_{i > j} c_i, so βM=1\beta_M = 1. By the Markov property

Pr⁡(Dj+1..M∣Vj=v)=∑uAj(v,u) ej+1(u)Pr⁡(Dj+2..M∣Vj+1=u),\Pr(D_{j+1..M} \mid V_j = v) = \sum_u A_j(v, u) \, e_{j+1}(u) \Pr(D_{j+2..M} \mid V_{j+1} = u),

so βj=Aj(ej+1βj+1)/cj+1\beta_j = A_j (e_{j+1} \beta_{j+1}) / c_{j+1}, with the product taken entry by entry. This is line L8, by Lemma 2 and the symmetry of AjA_j. Given VjV_j, the future data are independent of the past data, so

Pr⁡(Vj=v∣D1..M)=Pr⁡(Vj=v∣D1..j)Pr⁡(Dj+1..M∣Vj=v)Pr⁡(Dj+1..M∣D1..j)=αj(v)βj(v),\Pr(V_j = v \mid D_{1..M}) = \frac{\Pr(V_j = v \mid D_{1..j}) \Pr(D_{j+1..M} \mid V_j = v)}{\Pr(D_{j+1..M} \mid D_{1..j})} = \alpha_j(v) \beta_j(v),

because Pr⁡(Dj+1..M∣D1..j)=∏i>jci\Pr(D_{j+1..M} \mid D_{1..j}) = \prod_{i > j} c_i by the chain rule. □\square

The IBD probabilities of two people at marker jj follow: for each vv, the number of founder genes that they share is a function of vv, and ibd_distribution sums postj(v)\text{post}_j(v) over the vectors with each count.

Complexity

  • Time. Line L1 builds the gene flow for each of the 2b2^b vectors in O(n)O(n) and checks each marker in O(n)O(n), so Θ(M2bn)\Theta(M 2^b n). The bitwise transition of lines L4 and L8 costs Θ(b2b)\Theta(b 2^b) per marker against 4b4^b for a dense matrix product. The total is Θ(M2b(b+n))\Theta(M 2^b (b + n)).
  • Space. Θ(M2b)\Theta(M 2^b) for the emissions, the forward vectors and the posteriors. A two-pass version that recomputes the emissions needs less.
  • The limit. With b=2kb = 2k, the state space doubles with every meiosis. At b=30b = 30 one vector of probabilities already has about 10910^9 entries, so the method fits small and medium pedigrees.
  • Founder symmetry. Swapping the two genes of a founder does not change the probability of the data, so the choices of one child of each founder can be fixed. Kruglyak and coworkers (1996) give 2k−f2k - f bits of real information, and the state space shrinks by 2f2^f.

Properties

  • Exact. The likelihood is the exact sum over all 2bM2^{bM} paths of vectors.
  • Multipoint. All markers contribute at once, so missing genotypes and markers with few alleles are filled in by their neighbours.
  • IBD at every point. The posterior gives the IBD distribution of any pair of relatives at any marker, which is the input of nonparametric linkage.
  • Unlinked markers factor. With θj=1/2\theta_j = 1/2, the flip matrix makes the vector uniform, and the likelihood is the product of single-marker likelihoods.
  • Model assumptions. No interference, linkage equilibrium between markers in founders, and a known map. All three are assumed in the emission or the transition.

Variants and improvements

  • Trait locus. For parametric linkage, a trait locus with penetrances is placed between markers, and the likelihood ratio against θ=1/2\theta = 1/2 gives the LOD score, a likelihood ratio test on a log⁡10\log_{10} scale.
  • GENEHUNTER. Kruglyak, Daly, Reeve-Daly and Lander (1996) used the vector HMM for both parametric and nonparametric linkage, with founder symmetry and a fast transition.
  • Sparse gene flow trees. Merlin (Abecasis and coworkers) stores the emissions and posteriors as trees that merge vectors with the same value, which saves time and memory on dense maps.
  • Most likely vectors. The Viterbi algorithm on the same chain gives the most likely inheritance path, which shows the crossovers and helps find genotyping errors.
  • Sampling. For large pedigrees, Markov chain Monte Carlo over descent graphs replaces the exact sum (Lange, Chapter 9).

When to use it

  • Multipoint linkage analysis in small and medium pedigrees with dense marker maps.
  • Estimating IBD sharing of relatives along the chromosome, for example sib pairs in affected sib pair studies or relatives in a kinship coefficient study.
  • Finding crossovers and Mendel errors in family genotype data.
  • When the pedigree is too large, use the Elston-Stewart algorithm for few loci, or sampling methods.

Pitfalls

  • Exponential in pedigree size. Each extra non-founder multiplies the state space by 4. Check 2b2^b before a run.
  • Linkage disequilibrium. Dense SNP maps break the assumption of independent markers in founders. Untyped founders then make the shared haplotypes look like extra IBD, which inflates linkage evidence. Thin the markers or model the haplotypes.
  • Underflow. Without the scaling of line L6, the forward vector underflows after a few hundred markers.
  • Map errors. Wrong genetic distances distort the transitions. Too short a distance hides real crossovers and can make good data look like errors.
  • Genotyping errors. A single error can make cj=0c_j = 0 and stop the computation. Programs add a small error rate to the emission.

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.

lander_green_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lander-green-algorithm/. The authors are listed in prov/13J1K1.jsonl.
"""The Lander-Green algorithm: a hidden Markov model over inheritance vectors.

A pedigree maps each person to (father, mother), or to (None, None) for a
founder. The non-founders, in the order of nonfounders(ped), are n_0, ...,
n_(k-1). An inheritance vector is an integer v of 2k bits. Bit 2t says which
gene of the father n_t got (0 for the father's paternal gene, 1 for his
maternal gene), and bit 2t + 1 says the same for the mother.

Each founder i has two founder genes, (i, 0) and (i, 1). Given v, every gene
of every person is a copy of one founder gene. Marker data: markers[j] maps a
typed person to an unordered genotype (a, b) of allele indices at marker j,
and freqs[j] are the allele frequencies at marker j. Founder genes get
independent alleles with these frequencies (linkage equilibrium, and
Hardy-Weinberg proportions in founders).

thetas[j] is the recombination fraction between markers j and j + 1, the
same in both sexes. Without interference, the bits of v change
independently from one marker to the next, each with probability thetas[j].
"""

from __future__ import annotations

import math
from typing import Dict, Hashable, List, Mapping, Optional, Sequence, Tuple

Person = Hashable
Pedigree = Mapping[Person, Tuple[Optional[Person], Optional[Person]]]


def haldane_theta(d: float) -> float:
    """Recombination fraction for a map distance d in Morgans (Haldane, no interference)."""
    return 0.5 * (1.0 - math.exp(-2.0 * d))


def topological(ped: Pedigree) -> List[Person]:
    """The people with every parent before each child."""
    done, order = set(), []
    for start in ped:
        stack = [(start, False)]
        while stack:
            p, expanded = stack.pop()
            if p in done:
                continue
            f, m = ped[p]
            if expanded or f is None:
                done.add(p)
                order.append(p)
                continue
            stack.append((p, True))
            for q in (m, f):
                if q not in done:
                    stack.append((q, False))
    return order


def nonfounders(ped: Pedigree) -> List[Person]:
    return [p for p in topological(ped) if ped[p][0] is not None]


def gene_flow(ped: Pedigree, v: int, order=None, nf_index=None) -> Dict[Person, Tuple]:
    """The two founder genes (paternal, maternal) that each person carries under v."""
    order = order or topological(ped)
    if nf_index is None:
        nf_index = {p: t for t, p in enumerate(nonfounders(ped))}
    genes: Dict[Person, Tuple] = {}
    for p in order:
        f, m = ped[p]
        if f is None:
            genes[p] = ((p, 0), (p, 1))
        else:
            t = nf_index[p]
            genes[p] = (genes[f][(v >> (2 * t)) & 1], genes[m][(v >> (2 * t + 1)) & 1])
    return genes


def emission(genes: Mapping[Person, Tuple], typed: Mapping[Person, Tuple[int, int]],
             freqs: Sequence[float]) -> float:
    """P(marker genotypes | inheritance vector), by the founder gene graph.

    Each typed person is an edge between its two founder genes, labeled with
    its unordered genotype. In each connected component the allele of one
    gene fixes all the others, so a component has at most two consistent
    allele assignments. The result is the product over components of the sum
    over these assignments of the product of the allele frequencies.
    """
    adj: Dict[tuple, List[Tuple[tuple, Tuple[int, int]]]] = {}
    for p, (a, b) in typed.items():
        u, w = genes[p]
        adj.setdefault(u, []).append((w, (a, b)))
        if w != u:
            adj.setdefault(w, []).append((u, (a, b)))
    seen = set()
    prob = 1.0
    for start in adj:
        if start in seen:
            continue
        comp_total = 0.0
        for x in sorted(set(adj[start][0][1])):
            allele = {start: x}
            stack = [start]
            ok = True
            while stack and ok:
                u = stack.pop()
                xu = allele[u]
                for w, (a, b) in adj[u]:
                    if xu == a:
                        need = b
                    elif xu == b:
                        need = a
                    else:
                        ok = False
                        break
                    if w in allele:
                        if allele[w] != need:
                            ok = False
                            break
                    else:
                        allele[w] = need
                        stack.append(w)
            if ok:
                term = 1.0
                for g in allele.values():
                    term *= freqs[g]
                comp_total += term
        if comp_total == 0.0:
            return 0.0
        # Mark the whole component as seen with a plain search on adj.
        stack = [start]
        seen.add(start)
        while stack:
            u = stack.pop()
            for w, _ in adj[u]:
                if w not in seen:
                    seen.add(w)
                    stack.append(w)
        prob *= comp_total
    return prob


def transition(vec: List[float], bits: int, theta: float) -> List[float]:
    """Apply the 2^bits by 2^bits transition matrix, one bit at a time."""
    out = list(vec)
    keep = 1.0 - theta
    for b in range(bits):
        step = 1 << b
        for v in range(len(out)):
            if v & step:
                continue
            x, y = out[v], out[v | step]
            out[v] = keep * x + theta * y
            out[v | step] = theta * x + keep * y
    return out


def emissions(ped: Pedigree, markers: Sequence[Mapping[Person, Tuple[int, int]]],
              freqs: Sequence[Sequence[float]]) -> List[List[float]]:
    """e[j][v] = P(data at marker j | inheritance vector v), for all j and v."""
    order = topological(ped)
    nf = nonfounders(ped)
    nf_index = {p: t for t, p in enumerate(nf)}
    bits = 2 * len(nf)
    flows = [gene_flow(ped, v, order, nf_index) for v in range(1 << bits)]
    return [[emission(flows[v], markers[j], freqs[j]) for v in range(1 << bits)]
            for j in range(len(markers))]


def lander_green(ped: Pedigree, markers, freqs, thetas):
    """Forward and backward passes with scaling.

    Returns (log_likelihood, posterior), where posterior[j][v] is
    P(inheritance vector v at marker j | all marker data).
    """
    nf = nonfounders(ped)
    bits = 2 * len(nf)
    size = 1 << bits
    M = len(markers)
    if len(thetas) != M - 1:
        raise ValueError("need one recombination fraction between each pair of markers")
    e = emissions(ped, markers, freqs)  # @line L1
    alpha: List[List[float]] = []
    scale: List[float] = []
    cur = [e[0][v] / size for v in range(size)]  # @line L2
    for j in range(M):  # @line L3
        if j > 0:
            pred = transition(alpha[-1], bits, thetas[j - 1])  # @line L4
            cur = [pred[v] * e[j][v] for v in range(size)]  # @line L5
        c = sum(cur)
        if c == 0.0:
            raise ValueError(f"the data at marker {j} are inconsistent with Mendel's laws")
        scale.append(c)  # @line L6
        alpha.append([x / c for x in cur])
    loglik = sum(math.log(c) for c in scale)  # @line L7
    beta = [1.0] * size
    post = [None] * M
    post[M - 1] = list(alpha[M - 1])
    for j in range(M - 2, -1, -1):  # @line L8
        tmp = [e[j + 1][v] * beta[v] for v in range(size)]
        beta = transition(tmp, bits, thetas[j])
        beta = [b / scale[j + 1] for b in beta]
        post[j] = [alpha[j][v] * beta[v] for v in range(size)]  # @line L9
    return loglik, post


def ibd_distribution(ped: Pedigree, post_j: Sequence[float], a: Person, b: Person) -> List[float]:
    """P(a and b share 0, 1 or 2 founder genes) at one marker, from the posterior."""
    order = topological(ped)
    nf_index = {p: t for t, p in enumerate(nonfounders(ped))}
    out = [0.0, 0.0, 0.0]
    for v, pv in enumerate(post_j):
        if pv == 0.0:
            continue
        g = gene_flow(ped, v, order, nf_index)
        ga, gb = list(g[a]), list(g[b])
        shared = 0
        for x in ga:
            if x in gb:
                gb.remove(x)
                shared += 1
        out[shared] += pv
    return out
test_lander_green_algorithm.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lander-green-algorithm/. The authors are listed in prov/13J1K1.jsonl.

import itertools
import math
import random

import pytest

from lander_green_algorithm import (
    emission,
    gene_flow,
    haldane_theta,
    ibd_distribution,
    lander_green,
    nonfounders,
    topological,
    transition,
)

NUCLEAR = {"F": (None, None), "M": (None, None), "A": ("F", "M"), "B": ("F", "M")}
THREE_GEN = {"GF": (None, None), "GM": (None, None), "C": ("GF", "GM"),
             "S": (None, None), "K1": ("C", "S"), "K2": ("S", "C")}


def founders(ped):
    return [p for p in ped if ped[p][0] is None]


def brute_emission(ped, v, typed, freqs):
    """Sum over all allele labels of all founder genes."""
    genes = gene_flow(ped, v)
    fg = [(p, s) for p in founders(ped) for s in (0, 1)]
    total = 0.0
    for labels in itertools.product(range(len(freqs)), repeat=len(fg)):
        lab = dict(zip(fg, labels))
        ok = all(sorted((lab[genes[p][0]], lab[genes[p][1]])) == sorted(g) for p, g in typed.items())
        if ok:
            term = 1.0
            for x in labels:
                term *= freqs[x]
            total += term
    return total


def brute_likelihood(ped, markers, freqs, thetas):
    """Sum over all paths of inheritance vectors, with brute-force emissions."""
    bits = 2 * len(nonfounders(ped))
    size = 1 << bits
    e = [[brute_emission(ped, v, markers[j], freqs[j]) for v in range(size)] for j in range(len(markers))]
    total = 0.0
    for path in itertools.product(range(size), repeat=len(markers)):
        p = e[0][path[0]] / size
        for j in range(1, len(markers)):
            flips = bin(path[j] ^ path[j - 1]).count("1")
            p *= thetas[j - 1] ** flips * (1 - thetas[j - 1]) ** (bits - flips) * e[j][path[j]]
        total += p
    return total


def genotype_brute_single_marker(ped, typed, freqs):
    """One marker: sum over unordered genotypes with Hardy-Weinberg founders and Mendel."""
    k = len(freqs)
    genos = [(a, b) for a in range(k) for b in range(a, k)]
    order = topological(ped)
    total = 0.0
    for assign in itertools.product(range(len(genos)), repeat=len(order)):
        g = {p: genos[assign[t]] for t, p in enumerate(order)}
        if any(tuple(sorted(typed[p])) != g[p] for p in typed):
            continue
        term = 1.0
        for p in order:
            f, m = ped[p]
            a, b = g[p]
            if f is None:
                term *= freqs[a] * freqs[b] * (1 if a == b else 2)
            else:
                cnt = 0
                for x in g[f]:
                    for y in g[m]:
                        if tuple(sorted((x, y))) == (a, b):
                            cnt += 1
                term *= cnt / 4
        total += term
    return total


def simulate(rng, ped, n_markers, n_alleles, thetas, untyped=()):
    """Marker data from the model: random founder alleles and a Markov path of vectors."""
    bits = 2 * len(nonfounders(ped))
    freqs = []
    for _ in range(n_markers):
        w = [rng.random() + 0.2 for _ in range(n_alleles)]
        s = sum(w)
        freqs.append([x / s for x in w])
    v = rng.randrange(1 << bits)
    markers = []
    for j in range(n_markers):
        if j > 0:
            for b in range(bits):
                if rng.random() < thetas[j - 1]:
                    v ^= 1 << b
        genes = gene_flow(ped, v)
        lab = {}
        for p in founders(ped):
            for s in (0, 1):
                lab[(p, s)] = rng.choices(range(n_alleles), weights=freqs[j])[0]
        markers.append({p: (lab[genes[p][0]], lab[genes[p][1]]) for p in ped if p not in untyped})
    return markers, freqs


def test_haldane_and_transition():
    assert haldane_theta(0.0) == 0.0
    assert abs(haldane_theta(0.1) - 0.0906346) < 1e-7
    # The bitwise update equals the full matrix product.
    rng = random.Random(2)
    bits, theta = 3, 0.13
    x = [rng.random() for _ in range(8)]
    full = []
    for u in range(8):
        s = 0.0
        for v in range(8):
            fl = bin(u ^ v).count("1")
            s += theta ** fl * (1 - theta) ** (bits - fl) * x[v]
        full.append(s)
    fast = transition(x, bits, theta)
    assert max(abs(a - b) for a, b in zip(full, fast)) < 1e-14


def test_emission_against_founder_allele_sum():
    rng = random.Random(4)
    for ped in (NUCLEAR, THREE_GEN):
        bits = 2 * len(nonfounders(ped))
        markers, freqs = simulate(rng, ped, 3, 3, [0.2, 0.2], untyped=("GF",))
        for j in range(3):
            for v in range(1 << bits):
                a = emission(gene_flow(ped, v), markers[j], freqs[j])
                b = brute_emission(ped, v, markers[j], freqs[j])
                assert abs(a - b) <= 1e-12


def test_single_marker_against_genotype_sum():
    rng = random.Random(9)
    for ped, untyped in ((NUCLEAR, ()), (THREE_GEN, ("C",))):
        markers, freqs = simulate(rng, ped, 1, 3, [], untyped=untyped)
        ll, _ = lander_green(ped, markers, freqs, [])
        ref = genotype_brute_single_marker(ped, markers[0], freqs[0])
        assert abs(math.exp(ll) - ref) <= 1e-12 * ref


def test_multipoint_against_brute_force_paths():
    rng = random.Random(21)
    cases = ((NUCLEAR, 3, [0.1, 0.3], ()), (THREE_GEN, 2, [0.05], ("GF", "GM")))
    for ped, M, thetas, untyped in cases:
        markers, freqs = simulate(rng, ped, M, 2, thetas, untyped=untyped)
        ll, post = lander_green(ped, markers, freqs, thetas)
        ref = brute_likelihood(ped, markers, freqs, thetas)
        assert abs(ll - math.log(ref)) < 1e-10
        for pj in post:
            assert abs(sum(pj) - 1.0) < 1e-12


def test_unlinked_markers_factor():
    rng = random.Random(33)
    markers, freqs = simulate(rng, THREE_GEN, 3, 3, [0.5, 0.5])
    ll, _ = lander_green(THREE_GEN, markers, freqs, [0.5, 0.5])
    single = sum(lander_green(THREE_GEN, [markers[j]], [freqs[j]], [])[0] for j in range(3))
    assert abs(ll - single) < 1e-10


def test_ibd_of_relatives_without_data():
    ped = {"F": (None, None), "M": (None, None), "M2": (None, None),
           "A": ("F", "M"), "B": ("F", "M"), "H": ("F", "M2")}
    _, post = lander_green(ped, [{}], [[1.0]], [])
    sib = ibd_distribution(ped, post[0], "A", "B")
    half = ibd_distribution(ped, post[0], "A", "H")
    par = ibd_distribution(ped, post[0], "F", "A")
    assert [round(x, 12) for x in sib] == [0.25, 0.5, 0.25]
    assert [round(x, 12) for x in half] == [0.5, 0.5, 0.0]
    assert [round(x, 12) for x in par] == [0.0, 1.0, 0.0]


def test_sib_pair_example_of_the_page():
    # Parents 1/2 and 3/4, both children 1/3: the sibs share both genes for sure.
    markers = [{"F": (0, 1), "M": (2, 3), "A": (0, 2), "B": (0, 2)},
               {}]
    freqs = [[0.25] * 4, [1.0]]
    ll, post = lander_green(NUCLEAR, markers, freqs, [0.1])
    # Four of the 16 vectors fit (the phase of each parent is free), each with
    # founder allele probability (1/4)^4.
    assert abs(math.exp(ll) - 4 * 0.25 ** 4 / 16) < 1e-15
    assert [round(x, 12) for x in ibd_distribution(NUCLEAR, post[0], "A", "B")] == [0.0, 0.0, 1.0]
    p2 = ibd_distribution(NUCLEAR, post[1], "A", "B")
    # Each sib keeps the same gene from a parent when both or neither recombine.
    same = 0.9 ** 2 + 0.1 ** 2
    assert abs(p2[2] - same ** 2) < 1e-12
    assert abs(p2[1] - 2 * same * (1 - same)) < 1e-12


def test_mendel_error_raises():
    markers = [{"F": (0, 0), "M": (0, 0), "A": (1, 1)}]
    with pytest.raises(ValueError):
        lander_green(NUCLEAR, markers, [[0.5, 0.5]], [])

History

Eric Lander and Philip Green (1987) saw that the inheritance pattern of a pedigree along the chromosome is a Markov chain, and they used this to build multilocus linkage maps with dozens of markers in three-generation families, in time linear in the number of loci. The Elston-Stewart method was exponential in the number of loci, so this changed what multipoint linkage could do. Kruglyak and coworkers (1996) put the method into GENEHUNTER, and later programs such as Merlin made it faster on dense maps.

References

  1. Eric S. Lander and Philip Green, Construction of multilocus genetic linkage maps in humans, Proceedings of the National Academy of Sciences USA 84(8), 1987, pp. 2363-2367 (the inheritance vectors as hidden states along the chromosome, and the computation linear in the number of loci)
  2. Kruglyak, Daly, Reeve-Daly and Lander 1996, pp. 1347-1363 (the inheritance vector, founder symmetry with 2n - f bits of entropy, and IBD sharing at every point of the map)
  3. Kenneth Lange, Mathematical and Statistical Methods for Genetic Analysis, 2nd edition, Springer, 2002, Chapter 9, Descent Graph Methods

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