Algorithm Search⌘K

Algorithmadvanced

Elston-Stewart algorithm

Also called peeling algorithm for pedigrees, pedigree peeling.

Computes the likelihood of the phenotypes of a pedigree by peeling one nuclear family at a time. The cost is linear in the pedigree size and cubic in the number of genotypes.

Time
Θ(n G^3) worst · averageΘ(n G) best
Space
O(n G + c G^2) extra
Where
G = the number of joint genotypes of one individual; c = the largest number of children in a nuclear family; n = the number of individuals
Properties
deterministicexactofflineiterative
Origin
Robert C. Elston, John Stewart, 1971

The Elston-Stewart algorithm computes the likelihood of the phenotypes observed in a family tree (a pedigree) under a genetic model of genotype frequencies, Mendelian transmission and penetrance. The direct sum runs over all joint genotypes of the nn individuals, which is GnG^n terms. Peeling sums out one nuclear family at a time and passes a vector of GG numbers to the next family, so a pedigree without loops costs Θ(nG3)\Theta(n G^3). It is the pedigree form of dynamic programming on a tree, and the engine of classical parametric linkage analysis with few loci.

In plain words

A family tree records who is the child of whom, and for some people we know a trait, such as whether they have a disease. Each person carries a hidden genotype, and the model says how likely each genotype is in a founder, how parents pass genes to a child, and how likely the trait is for each genotype. We want the chance of all the known traits together. Trying every combination of genotypes is too slow for a large family. Peeling starts at the edges of the tree. For a family whose members are already summarized, it adds up over their genotypes and keeps only a small table for the one person who connects the family to the rest of the tree. Then it moves inward, family by family, until one person is left. The cost grows with the size of the tree, not with the number of combinations.

The problem

Input. A pedigree on a set II of nn individuals, where each person is a founder or has both parents in II, and a genetic model:

  • a prior π(g)\pi(g) of genotype g∈{1,…,G}g \in \{1, \ldots, G\} in a founder, for one autosomal locus usually the Hardy-Weinberg proportions pa2p_a^2 and 2papb2 p_a p_b;
  • a transmission table T(g∣a,b)T(g \mid a, b), the probability that parents with genotypes aa and bb have a child with genotype gg (for one locus, Mendel's laws);
  • a penetrance peni(g)\text{pen}_i(g), the probability of the phenotype of person ii given genotype gg, equal to 1 for a person with no data.

Output. The likelihood

L=∑γ∈[G]I∏i founderπ(γi)∏i non-founderT(γi∣γfi,γmi)∏i∈Ipeni(γi).L = \sum_{\gamma \in [G]^I} \prod_{i \text{ founder}} \pi(\gamma_i) \prod_{i \text{ non-founder}} T(\gamma_i \mid \gamma_{f_i}, \gamma_{m_i}) \prod_{i \in I} \text{pen}_i(\gamma_i).

The individuals with the same two parents form a nuclear family. The algorithm needs the pedigree to have no loop: the graph HH that joins each family to its parents and children must be a forest. A marriage between relatives, or two families joined at two places, makes a loop.

The algorithm

Root each component of HH at a person. Each node then sends one vector of length GG to its parent in HH:

  • a person ii sends wi(g)w_i(g), the probability of the data in its part of the tree given γi=g\gamma_i = g, including its own penetrance and prior;
  • a family FF sends MF(g)M_F(g) to the member pp that joins it to the rest of the tree, the probability of the data in its part given γp=g\gamma_p = g.
  1. PEEL(pedigree, π, T, pen)
  2. 1build the graph H of individuals and nuclear families; fail if H has a cycle
  3. 2root each component of H at a person and list its nodes in preorder
  4. 3for each node v in reverse preorder do
  5. 4if v is a person i then w_i(g) ← pen_i(g) · π(g) if i is a founder, else pen_i(g)
  6. 5w_i(g) ← w_i(g) · product of M_F(g) over the families F below i in H
  7. 6else v is a family F with father f, mother m and parent p in H
  8. 7S_c(a, b) ← sum over g of T(g | a, b) · w_c(g), for each child c of F other than p
  9. 8if p = f then M_F(g) ← sum over b of w_m(b) · product over c of S_c(g, b), and the same with roles swapped if p = m
  10. 9if p is a child then M_F(g) ← sum over a, b of w_f(a) · w_m(b) · T(g | a, b) · product over c of S_c(a, b)
  11. 10return product over the roots r of (sum over g of w_r(g))

Line L8 peels a family onto a parent, which is the step of the original paper for a family that hangs below a person. Line L9 peels a family onto a child, which is needed when the tree reaches a family from below, for example from a person who married in. Line L7 is shared by both. The reverse preorder of line L3 makes every message ready before it is used.

Example

Take a recessive disease with alleles DD (frequency 0.9) and dd (frequency 0.1). A person is affected exactly when the genotype is dddd. The genotypes in the order DD,Dd,ddDD, Dd, dd have the prior (0.81,0.18,0.01)(0.81, 0.18, 0.01). Two unaffected parents have two children: child 1 is affected and child 2 is not. The penetrance vectors are (1,1,0)(1, 1, 0) for an unaffected person and (0,0,1)(0, 0, 1) for an affected one.

Root the tree at the father. The family node is his only neighbour. Lines L4 and L5 give

person ww
mother (0.81,0.18,0)(0.81, 0.18, 0)
child 1 (0,0,1)(0, 0, 1)
child 2 (1,1,0)(1, 1, 0)

Line L7 gives S1(a,b)=T(dd∣a,b)S_1(a, b) = T(dd \mid a, b), which is 1/41/4 for Dd×DdDd \times Dd, 1/21/2 for dd×Dddd \times Dd and 0 when a parent is DDDD, and S2(a,b)=1−T(dd∣a,b)S_2(a, b) = 1 - T(dd \mid a, b). The mother cannot be dddd, so line L8 gives

MF(Dd)=0.18⋅14⋅34=0.03375,MF(dd)=0.18⋅12⋅12=0.045,MF(DD)=0.M_F(Dd) = 0.18 \cdot \tfrac14 \cdot \tfrac34 = 0.03375, \qquad M_F(dd) = 0.18 \cdot \tfrac12 \cdot \tfrac12 = 0.045, \qquad M_F(DD) = 0.

At the root, wfather=(0.81,0.18,0)⋅MF=(0,0.006075,0)w_{\text{father}} = (0.81, 0.18, 0) \cdot M_F = (0, 0.006075, 0), so line L10 returns L=0.006075=243/40000L = 0.006075 = 243/40000. This is 0.182⋅14⋅340.18^2 \cdot \tfrac14 \cdot \tfrac34: both parents must be carriers, the first child must be dddd, and the second must not. Peeling again with child 2 fixed to each genotype gives the posterior (1/3,2/3,0)(1/3, 2/3, 0), so the unaffected sib is a carrier with probability 2/32/3. The implementation returns these values in exact fractions.

Correctness

Each factor of the product in the definition of LL belongs to one node of HH: a person owns its prior and penetrance, and a family owns the transmission factors of its children. A factor owned by a node of a subtree involves only the people of the subtree and the parent of the subtree's root. By induction in reverse preorder, wiw_i is the sum of the factors of the subtree of ii over all genotypes in it with γi=g\gamma_i = g, and MFM_F is the same for a family with the genotype of its parent fixed. The induction step is the distributive law: the subtrees below a node are disjoint, so the sum of the product splits into a product of sums. Line L1 is right because a graph with NN nodes, EE edges and KK components is a forest exactly when E=N−KE = N - K. The full proof is below.

Proof: Peeling returns the likelihood of a loop-free pedigreefull

Let a pedigree have the individuals II. Each individual ii is a founder or has a father fif_i and a mother mim_i in II. The individuals with the same two parents form a nuclear family F=(f,m;CF)F = (f, m; C_F), where CFC_F is the set of children. Genotypes are the numbers 1,…,G1, \ldots, G. The model gives a founder prior π(g)\pi(g), a transmission table T(g∣a,b)T(g \mid a, b) and a penetrance peni(g)\text{pen}_i(g) for each individual (equal to 1 for every gg when ii has no data). For an assignment γ:I→[G]\gamma : I \to [G] of genotypes, put

Φ(γ)=∏i founderπ(γi)∏F∏c∈CFT(γc∣γf,γm)∏i∈Ipeni(γi).\Phi(\gamma) = \prod_{i \text{ founder}} \pi(\gamma_i) \prod_{F} \prod_{c \in C_F} T(\gamma_c \mid \gamma_f, \gamma_m) \prod_{i \in I} \text{pen}_i(\gamma_i).

The likelihood is L=∑γΦ(γ)L = \sum_\gamma \Phi(\gamma), a sum of G∣I∣G^{|I|} terms. The proof uses only the distributive law, so it holds for any non-negative or real tables.

The graph. HH is the bipartite graph whose nodes are the individuals and the families, with an edge between a family and each of its members (both parents and all children). Each factor of Φ\Phi is owned by one node: an individual ii owns π(γi)\pi(\gamma_i) (if it is a founder) and peni(γi)\text{pen}_i(\gamma_i), and a family FF owns the factors T(γc∣γf,γm)T(\gamma_c \mid \gamma_f, \gamma_m) of its children. A factor owned by FF involves only members of FF, which are the neighbours of FF in HH.

Lemma 1 (the check of line L1). A graph with NN nodes, EE edges and KK connected components is a forest if and only if E=N−KE = N - K.

Proof. A spanning forest of the graph, one spanning tree for each component, has N−KN - K edges. Every edge of the graph outside this forest closes a cycle with it, so the graph is a forest exactly when it has no such edge. □\square

So line L1 fails exactly when HH has a cycle. Such a cycle is a marriage loop or an inbreeding loop. From now on HH is a forest. Line L2 roots each component at an individual. The preorder lists each node after its parent in the forest, so the reverse preorder of line L3 reaches every child of a node before the node.

Partial sums. For a node vv, let HvH_v be its subtree, Φv\Phi_v the product of the factors owned by the nodes of HvH_v, and UvU_v the individuals of HvH_v other than the individual that the definition fixes. For an individual ii, define

Wi(g)=∑γ on UiΦi(γ)with γi=g,W_i(g) = \sum_{\gamma \text{ on } U_i} \Phi_i(\gamma) \quad \text{with } \gamma_i = g,

where UiU_i is the set of individuals of HiH_i other than ii. For a family FF whose parent in the forest is the individual pp, define

MF(g)=∑γ on UFΦF(γ)with γp=g,M_F(g) = \sum_{\gamma \text{ on } U_F} \Phi_F(\gamma) \quad \text{with } \gamma_p = g,

where UFU_F is the set of individuals of HFH_F. Note that p∉HFp \notin H_F, but the factors owned by FF involve γp\gamma_p, so MFM_F is a function of gg.

Claim. A factor owned by a node of HvH_v involves only individuals of HvH_v and the parent of vv in the forest.

Proof. An individual owns factors in its own genotype only. A family FF in HvH_v owns factors in its neighbours, which are its parent in the forest and its children in the forest. Its children are in HvH_v. Its parent is in HvH_v too, unless F=vF = v, and then the parent is the parent of vv. □\square

Lemma 2. When line L3 has processed a node, wi=Wiw_i = W_i for an individual ii, and MFM_F in the code is the MFM_F above for a family FF.

Proof. By induction in the reverse preorder.

Individual ii (lines L4 and L5). The children of ii in the forest are the families F1,…,FdF_1, \ldots, F_d in which ii is a member but which are not the parent of ii. The subtrees HF1,…,HFdH_{F_1}, \ldots, H_{F_d} are disjoint, and UiU_i is the disjoint union of the sets UFtU_{F_t}. The factors of Φi\Phi_i are those that ii owns and those of ΦF1,…,ΦFd\Phi_{F_1}, \ldots, \Phi_{F_d}. By the claim, the factors of ΦFt\Phi_{F_t} involve only UFtU_{F_t} and ii. With γi=g\gamma_i = g fixed, the sum over UiU_i is a sum over independent choices on each UFtU_{F_t} of a product of factors that each depend on one choice. By the distributive law it is the product of the separate sums:

Wi(g)=peni(g) π(g)[i founder]∏t=1dMFt(g).W_i(g) = \text{pen}_i(g) \, \pi(g)^{[i \text{ founder}]} \prod_{t=1}^{d} M_{F_t}(g).

By the induction hypothesis these MFtM_{F_t} are the vectors that the code holds, so lines L4 and L5 compute WiW_i.

Family F=(f,m;CF)F = (f, m; C_F) with parent pp in the forest (lines L6 to L9). The children of FF in the forest are its members other than pp. Their subtrees are disjoint, UFU_F is their disjoint union, and the factors of ΦF\Phi_F are the TT factors that FF owns together with the factors of Φx\Phi_x for each member x≠px \neq p. For a child c≠pc \neq p of the family and parent genotypes a,ba, b, line L7 computes

Sc(a,b)=∑gT(g∣a,b) Wc(g),S_c(a, b) = \sum_{g} T(g \mid a, b) \, W_c(g),

which is the sum over the genotype of cc and over UcU_c of the factors that involve cc or UcU_c, with the parents fixed at (a,b)(a, b).

If pp is a parent, say p=fp = f, fix γf=g\gamma_f = g. The free variables are γm\gamma_m, the genotypes of the children and the sets UmU_m and UcU_c. For a fixed γm=b\gamma_m = b, the remaining sum splits over the children, so

MF(g)=∑bWm(b)∏c∈CFSc(g,b),M_F(g) = \sum_{b} W_m(b) \prod_{c \in C_F} S_c(g, b),

which is line L8. The case p=mp = m is the same with the roles swapped.

If pp is a child, fix γp=g\gamma_p = g. The free variables are γf\gamma_f, γm\gamma_m, the genotypes of the other children and the sets below them. The factor T(g∣a,b)T(g \mid a, b) of pp stays, and for fixed (a,b)(a, b) the rest splits:

MF(g)=∑a,bWf(a) Wm(b) T(g∣a,b)∏c∈CF, c≠pSc(a,b),M_F(g) = \sum_{a, b} W_f(a) \, W_m(b) \, T(g \mid a, b) \prod_{c \in C_F, \, c \neq p} S_c(a, b),

which is line L9. In both cases the induction hypothesis gives the WW vectors that the code uses. □\square

Theorem. PEEL returns LL.

Proof. Let the components of HH have the roots r1,…,rKr_1, \ldots, r_K. Every factor of Φ\Phi is owned by exactly one node, and every node is in one component, so Φ(γ)=∏kΦrk(γ)\Phi(\gamma) = \prod_k \Phi_{r_k}(\gamma). By the claim, and because a root has no parent, Φrk\Phi_{r_k} involves only the individuals of the component of rkr_k. The individuals of II are partitioned by the components. By the distributive law,

L=∑γ∏kΦrk(γ)=∏k∑gWrk(g),L = \sum_\gamma \prod_{k} \Phi_{r_k}(\gamma) = \prod_{k} \sum_{g} W_{r_k}(g),

and by Lemma 2 this is the value of line L10. □\square

Posterior genotypes. Replacing peni\text{pen}_i by peni(h)[h=g]\text{pen}_i(h) [h = g] keeps only the terms of LL with γi=g\gamma_i = g. So the result of PEEL with this change, divided by LL, is Pr⁡(γi=g∣data)\Pr(\gamma_i = g \mid \text{data}). This is what genotype_posterior computes.

Complexity

  • Time. Each non-founder is a child in exactly one family, and line L7 costs G3G^3 for each child, so all of line L7 costs at most nG3n G^3. Lines L8 and L9 cost O(G2(c+G))O(G^2 (c + G)) for a family with cc children, and there are fewer families than people. The total is Θ(nG3)\Theta(n G^3) against GnG^n for the direct sum. A pedigree of founders only, with no families, costs Θ(nG)\Theta(n G).
  • Space. One vector per node, O(nG)O(n G), plus the tables ScS_c of one family, O(cG2)O(c G^2).
  • Many loci. For ℓ\ell linked loci a joint genotype must record the phase, so GG grows like (k(k+1)/2)ℓ(k(k+1)/2)^\ell or more for kk alleles per locus. The cost is exponential in the number of loci, which is why the Lander-Green algorithm is used for many markers.
  • Genotype elimination. Many entries of ww and MM are zero, because data rule out genotypes. Removing impossible genotypes before peeling (Lange, Chapter 7) cuts GG to a few values for most typed people.

Properties

  • Exact. No approximation: the result equals the sum of GnG^n terms. The code uses only ++ and ×\times, so it runs on exact fractions as well as floats.
  • Any genotype space. The same code serves one locus with many alleles, several loci with phased genotypes, or a major gene with a polygenic class, as long as the model has the form prior, transmission and penetrance.
  • Same answer from every root. The likelihood does not depend on the root or on the order of peeling. The order only changes the cost when the family structure is uneven.
  • Posterior genotypes. Fixing one person's genotype and peeling again gives the posterior of that genotype. A second, outward pass, as in belief propagation, gives the posteriors of all people at about twice the cost of one pass.

Variants and improvements

  • Peeling on general pedigrees. Lange and Elston (1975) and Cannings, Thompson and Skolnick (1978) peel onto sets of people (cutsets) instead of one person, which handles any pedigree. A pedigree with loops is peeled by conditioning on the genotypes of a few people that break the loops, at a factor GG per broken loop, or by a junction tree. The cost then depends on the treewidth of the graph.
  • As variable elimination. Peeling is variable elimination on the Bayesian network of the pedigree, with an elimination order given by the family structure. Felsenstein pruning is the same idea on a phylogeny, where each node has one parent.
  • Faster linkage programs. Genotype elimination and good peeling orders made linkage on large pedigrees practical in programs such as LINKAGE and VITESSE.
  • Many markers. The Lander-Green algorithm swaps the roles: it is linear in the number of markers and exponential in the number of meioses.

When to use it

  • Parametric linkage analysis on large pedigrees with one or a few loci, where the LOD score compares the likelihood at a recombination fraction θ\theta with the likelihood at θ=1/2\theta = 1/2, as in a likelihood ratio test.
  • Segregation analysis: fitting the model of a major gene (dominant, recessive, penetrances) to the trait in families.
  • Genetic counselling: the probability that a relative is a carrier, as in the example.
  • When the pedigree is too large for the 22n2^{2n} states of the Lander-Green algorithm.

Pitfalls

  • Loops. A pedigree with a loop has no tree of families, and simple peeling is wrong or impossible. The implementation rejects it. Use loop breaking or a junction tree instead.
  • Underflow. On a large pedigree the likelihood is tiny. Scale each vector and keep the log of the scale factors, as in the log-sum-exp trick.
  • Phase with many loci. For linked loci, an unordered genotype is not enough to write the transmission table. The genotype must record which alleles are on the same chromosome.
  • Wrong model. Allele frequencies and penetrances are inputs. A wrong allele frequency changes the founder prior and can inflate or deflate a LOD score, most when founders are untyped.
  • Inconsistent data. A Mendelian error in the data makes L=0L = 0. Check the data for Mendel errors before the analysis.

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.

elston_stewart_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/elston-stewart-algorithm/. The authors are listed in prov/7JJWSE.jsonl.
"""The Elston-Stewart algorithm (peeling) for the likelihood of a pedigree.

A pedigree maps each individual to a pair (father, mother). A founder has
(None, None); a non-founder has both parents in the pedigree. Individuals
with the same two parents form one nuclear family.

The genotype space is general: genotypes are the indices 0 .. G-1, prior[g]
is the probability of genotype g in a founder, trans[gf][gm][gc] is the
probability that parents with genotypes gf and gm have a child with genotype
gc, and pen[i][g] is the probability of the phenotype of individual i given
genotype g (the penetrance). An individual that is not a key of pen has no
data, which is the same as a penetrance of 1 for every genotype.

For one autosomal locus, one_locus_model() builds the unordered genotypes,
the Hardy-Weinberg prior and Mendel's transmission table.

The code uses only +, * and comparisons on the numbers, so it works with
float and with fractions.Fraction alike.
"""

from __future__ import annotations

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

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


def one_locus_model(freqs: Sequence, one=1):
    """Genotypes, founder prior and Mendelian transmission for one locus.

    freqs are the allele frequencies. The genotypes are the unordered pairs
    (a, b) with a <= b, in lexicographic order. The prior is Hardy-Weinberg:
    p_a^2 for (a, a) and 2 p_a p_b for (a, b). Each parent passes each of its
    two alleles with probability 1/2, independently of the other parent.
    """
    k = len(freqs)
    genos = [(a, b) for a in range(k) for b in range(a, k)]
    index = {g: i for i, g in enumerate(genos)}
    prior = [freqs[a] * freqs[b] * (1 if a == b else 2) for a, b in genos]
    half = one / 2
    quarter = half * half
    G = len(genos)
    zero = one - one
    trans = [[[zero] * G for _ in range(G)] for _ in range(G)]
    for i, gf in enumerate(genos):
        for j, gm in enumerate(genos):
            row = trans[i][j]
            for x in gf:
                for y in gm:
                    c = index[(min(x, y), max(x, y))]
                    row[c] += quarter
    return genos, prior, trans


def _families(ped: Pedigree):
    """The nuclear families as a dict (father, mother) -> list of children."""
    fams: Dict[Tuple[Person, Person], List[Person]] = {}
    for i, (f, m) in ped.items():
        if (f is None) != (m is None):
            raise ValueError(f"{i!r} has only one parent")
        if f is None:
            continue
        if f not in ped or m not in ped:
            raise ValueError(f"a parent of {i!r} is not in the pedigree")
        fams.setdefault((f, m), []).append(i)
    return fams


def _tree(ped: Pedigree, fams):
    """The bipartite graph of individuals and families, as a forest.

    Returns (roots, order, parent): order lists every node so that each node
    comes after its parent in the forest (a preorder), parent maps a node to
    its parent node (None for a root). A node is ('i', person) or
    ('f', (father, mother)). Raises ValueError if the graph has a cycle,
    which is a marriage or inbreeding loop of the pedigree.
    """
    adj: Dict[tuple, List[tuple]] = {("i", p): [] for p in ped}
    n_edges = 0
    for key, kids in fams.items():
        fnode = ("f", key)
        adj[fnode] = []
        for member in (key[0], key[1], *kids):
            adj[fnode].append(("i", member))
            adj[("i", member)].append(fnode)
            n_edges += 1
    parent: Dict[tuple, Optional[tuple]] = {}
    order: List[tuple] = []
    roots: List[tuple] = []
    for p in ped:
        start = ("i", p)
        if start in parent:
            continue
        roots.append(start)
        parent[start] = None
        stack = [start]
        while stack:
            v = stack.pop()
            order.append(v)  # @line L2
            for w in adj[v]:
                if w not in parent:
                    parent[w] = v
                    stack.append(w)
    if n_edges != len(adj) - len(roots):
        raise ValueError("the pedigree has a loop; peeling needs a loop-free pedigree")
    return roots, order, parent


def elston_stewart(ped: Pedigree, prior: Sequence, trans, pen: Mapping[Person, Sequence],
                   one=1):
    """The likelihood of the phenotypes of a loop-free pedigree, by peeling."""
    G = len(prior)
    zero = one - one
    ones = [one] * G
    fams = _families(ped)
    roots, order, parent = _tree(ped, fams)  # @line L1
    child_fams: Dict[Person, List[tuple]] = {}
    for node in order:
        par = parent[node]
        if node[0] == "f":
            child_fams.setdefault(par[1], []).append(node)
    w: Dict[Person, List] = {}  # the message from an individual to its parent family
    msg: Dict[tuple, List] = {}  # the message from a family to its parent individual
    total = one
    for v in reversed(order):  # @line L3
        if v[0] == "i":  # @line L4
            i = v[1]
            vec = list(pen.get(i, ones))
            if ped[i][0] is None:
                vec = [vec[g] * prior[g] for g in range(G)]
            for fnode in child_fams.get(i, ()):
                m = msg[fnode]
                vec = [vec[g] * m[g] for g in range(G)]
            w[i] = vec  # @line L5
            if parent[v] is None:
                s = zero
                for g in range(G):
                    s += vec[g]
                total = total * s  # @line L10
            continue
        f, m = v[1]  # @line L6
        kids = fams[(f, m)]
        p = parent[v][1]
        S = {}
        for c in kids:  # @line L7
            if c == p:
                continue
            wc = w[c]
            table = [[zero] * G for _ in range(G)]
            for gf in range(G):
                for gm in range(G):
                    row = trans[gf][gm]
                    s = zero
                    for gc in range(G):
                        s += row[gc] * wc[gc]
                    table[gf][gm] = s
            S[c] = table

        def kids_product(gf, gm):
            prod = one
            for table in S.values():
                prod = prod * table[gf][gm]
            return prod

        out = [zero] * G
        if p == f or p == m:  # @line L8
            other = w[m] if p == f else w[f]
            for gp in range(G):
                s = zero
                for go in range(G):
                    if other[go] == zero:
                        continue
                    gf, gm = (gp, go) if p == f else (go, gp)
                    s += other[go] * kids_product(gf, gm)
                out[gp] = s
        else:  # @line L9
            wf, wm = w[f], w[m]
            for gf in range(G):
                if wf[gf] == zero:
                    continue
                for gm in range(G):
                    if wm[gm] == zero:
                        continue
                    base = wf[gf] * wm[gm] * kids_product(gf, gm)
                    row = trans[gf][gm]
                    for gp in range(G):
                        out[gp] += base * row[gp]
        msg[v] = out
    return total


def brute_force_likelihood(ped: Pedigree, prior: Sequence, trans, pen, one=1):
    """The same likelihood as a sum over all G^n joint genotype assignments."""
    people = list(ped)
    G = len(prior)
    pos = {p: k for k, p in enumerate(people)}
    total = one - one
    assign = [0] * len(people)
    n = len(people)
    while True:
        term = one
        for k, p in enumerate(people):
            g = assign[k]
            f, m = ped[p]
            if f is None:
                term = term * prior[g]
            else:
                term = term * trans[assign[pos[f]]][assign[pos[m]]][g]
            if p in pen:
                term = term * pen[p][g]
        total += term
        k = 0
        while k < n and assign[k] == G - 1:
            assign[k] = 0
            k += 1
        if k == n:
            return total
        assign[k] += 1


def genotype_posterior(ped: Pedigree, prior: Sequence, trans, pen, person, one=1):
    """P(genotype of person = g | all phenotypes), for each g, by G + 1 peelings."""
    L = elston_stewart(ped, prior, trans, pen, one)
    base = pen.get(person, [one] * len(prior))
    zero = one - one
    post = []
    for g in range(len(prior)):
        pen_g = dict(pen)
        pen_g[person] = [base[h] if h == g else zero for h in range(len(prior))]
        post.append(elston_stewart(ped, prior, trans, pen_g, one) / L)
    return post
test_elston_stewart_algorithm.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/elston-stewart-algorithm/. The authors are listed in prov/7JJWSE.jsonl.

import random
from fractions import Fraction

import pytest

from elston_stewart_algorithm import (
    brute_force_likelihood,
    elston_stewart,
    genotype_posterior,
    one_locus_model,
)


def random_pedigree(rng, n_people):
    """A random loop-free pedigree: each new family joins the old ones at one person."""
    ped = {"F0": (None, None), "M0": (None, None)}
    couples = [("F0", "M0")]
    k = 0
    while len(ped) < n_people:
        if rng.random() < 0.5 or len(ped) == 2:
            f, m = rng.choice(couples)
        else:
            x = rng.choice([p for p in ped if ped[p][0] is not None] or list(ped))
            k += 1
            s = f"S{k}"
            ped[s] = (None, None)
            f, m = (x, s) if rng.random() < 0.5 else (s, x)
            couples.append((f, m))
            if len(ped) >= n_people:
                break
        k += 1
        ped[f"C{k}"] = (f, m)
    # A spouse without children would sit alone; give every couple a child.
    for f, m in couples:
        if not any(v == (f, m) for v in ped.values()):
            k += 1
            ped[f"C{k}"] = (f, m)
    return ped


def random_pen(rng, ped, G, frac=False, missing=0.3):
    pen = {}
    for p in ped:
        if rng.random() < missing:
            continue
        if frac:
            pen[p] = [Fraction(rng.randint(0, 4), 4) for _ in range(G)]
        else:
            pen[p] = [rng.random() for _ in range(G)]
    return pen


def test_mendel_table_rows_sum_to_one():
    genos, prior, trans = one_locus_model([Fraction(1, 2), Fraction(1, 3), Fraction(1, 6)], Fraction(1))
    assert len(genos) == 6
    assert sum(prior) == 1
    for row in trans:
        for cell in row:
            assert sum(cell) == 1
    # Aa x Aa gives AA, Aa, aa in 1:2:1.
    _, _, t2 = one_locus_model([Fraction(1, 2), Fraction(1, 2)], Fraction(1))
    assert t2[1][1] == [Fraction(1, 4), Fraction(1, 2), Fraction(1, 4)]


def test_no_data_gives_one():
    _, prior, trans = one_locus_model([Fraction(3, 10), Fraction(7, 10)], Fraction(1))
    ped = random_pedigree(random.Random(1), 7)
    assert elston_stewart(ped, prior, trans, {}, Fraction(1)) == 1


def test_recessive_example_of_the_page():
    # Allele 0 is D (frequency 0.9), allele 1 is d (0.1); affected iff dd.
    _, prior, trans = one_locus_model([Fraction(9, 10), Fraction(1, 10)], Fraction(1))
    unaff = [Fraction(1), Fraction(1), Fraction(0)]
    aff = [Fraction(0), Fraction(0), Fraction(1)]
    ped = {"father": (None, None), "mother": (None, None),
           "child1": ("father", "mother"), "child2": ("father", "mother")}
    pen = {"father": unaff, "mother": unaff, "child1": aff, "child2": unaff}
    L = elston_stewart(ped, prior, trans, pen, Fraction(1))
    assert L == Fraction(18, 100) ** 2 * Fraction(3, 16)
    assert L == Fraction(243, 40000)
    post = genotype_posterior(ped, prior, trans, pen, "child2", Fraction(1))
    assert post == [Fraction(1, 3), Fraction(2, 3), Fraction(0)]


def test_nuclear_family_exact_against_brute_force():
    rng = random.Random(7)
    for freqs in ([Fraction(1, 4), Fraction(3, 4)], [Fraction(1, 2), Fraction(1, 3), Fraction(1, 6)]):
        _, prior, trans = one_locus_model(freqs, Fraction(1))
        G = len(prior)
        ped = {"f": (None, None), "m": (None, None),
               "c1": ("f", "m"), "c2": ("f", "m"), "c3": ("f", "m")}
        for _ in range(3):
            pen = random_pen(rng, ped, G, frac=True, missing=0.2)
            assert elston_stewart(ped, prior, trans, pen, Fraction(1)) == \
                brute_force_likelihood(ped, prior, trans, pen, Fraction(1))


def test_three_generations_against_brute_force():
    # Grandparents, two children who each marry in, and three grandchildren.
    ped = {"GF": (None, None), "GM": (None, None),
           "C1": ("GF", "GM"), "C2": ("GF", "GM"),
           "S1": (None, None), "S2": (None, None),
           "K1": ("C1", "S1"), "K2": ("C1", "S1"), "K3": ("S2", "C2")}
    _, prior, trans = one_locus_model([0.35, 0.65], 1.0)
    rng = random.Random(11)
    for _ in range(2):
        pen = random_pen(rng, ped, 3)
        a = elston_stewart(ped, prior, trans, pen, 1.0)
        b = brute_force_likelihood(ped, prior, trans, pen, 1.0)
        assert abs(a - b) <= 1e-12 * b


def test_half_sibs_and_random_pedigrees():
    # A father with children by two mothers: two families share one person.
    ped = {"f": (None, None), "m1": (None, None), "m2": (None, None),
           "a": ("f", "m1"), "b": ("f", "m1"), "c": ("f", "m2")}
    _, prior, trans = one_locus_model([Fraction(1, 5), Fraction(4, 5)], Fraction(1))
    pen = random_pen(random.Random(3), ped, 3, frac=True, missing=0.0)
    assert elston_stewart(ped, prior, trans, pen, Fraction(1)) == \
        brute_force_likelihood(ped, prior, trans, pen, Fraction(1))
    _, prior, trans = one_locus_model([0.2, 0.5, 0.3], 1.0)
    for seed in range(8):
        rng = random.Random(100 + seed)
        ped = random_pedigree(rng, rng.randint(3, 6))
        pen = random_pen(rng, ped, 6)
        a = elston_stewart(ped, prior, trans, pen, 1.0)
        b = brute_force_likelihood(ped, prior, trans, pen, 1.0)
        assert abs(a - b) <= 1e-12 * max(b, 1e-300)


def test_disconnected_pedigree_is_a_product():
    _, prior, trans = one_locus_model([Fraction(1, 3), Fraction(2, 3)], Fraction(1))
    a = {"f": (None, None), "m": (None, None), "c": ("f", "m")}
    b = {"x": (None, None), "y": (None, None), "z": ("x", "y"), "u": ("x", "y")}
    rng = random.Random(5)
    pa = random_pen(rng, a, 3, frac=True, missing=0.0)
    pb = random_pen(rng, b, 3, frac=True, missing=0.0)
    both = {**a, **b}
    assert elston_stewart(both, prior, trans, {**pa, **pb}, Fraction(1)) == \
        elston_stewart(a, prior, trans, pa, Fraction(1)) * elston_stewart(b, prior, trans, pb, Fraction(1))


def test_loop_is_rejected():
    # First cousins who have a child: an inbreeding loop.
    ped = {"GF": (None, None), "GM": (None, None),
           "A": ("GF", "GM"), "B": ("GF", "GM"),
           "SA": (None, None), "SB": (None, None),
           "X": ("A", "SA"), "Y": ("SB", "B"), "Z": ("X", "Y")}
    _, prior, trans = one_locus_model([0.5, 0.5], 1.0)
    with pytest.raises(ValueError):
        elston_stewart(ped, prior, trans, {}, 1.0)
    with pytest.raises(ValueError):
        elston_stewart({"a": ("b", None), "b": (None, None)}, prior, trans, {}, 1.0)

History

Robert Elston and John Stewart (1971) wrote the genetic model of a pedigree as a prior, a transmission probability and a penetrance, and they showed how to compute the likelihood of a simple pedigree by summing out one generation at a time. Lange and Elston (1975) and Cannings, Thompson and Skolnick (1978) extended peeling to pedigrees of arbitrary size and complexity. The algorithm became the core of linkage programs in the 1980s and 1990s. Later work saw it as one case of variable elimination in graphical models.

References

  1. Robert C. Elston and John Stewart, A general model for the genetic analysis of pedigree data, Human Heredity 21(6), 1971, pp. 523-542 (the model of genotype, transmission and penetrance, and the recursive sum over the genotypes of a simple pedigree)
  2. Chris Cannings, Elizabeth A. Thompson and Mark H. Skolnick, Probability functions on complex pedigrees, Advances in Applied Probability 10(1), 1978, pp. 26-61 (probability functions and peeling on pedigrees of arbitrary complexity)
  3. Kenneth Lange, Mathematical and Statistical Methods for Genetic Analysis, 2nd edition, Springer, 2002, Chapter 7, Computation of Mendelian Likelihoods (the Elston-Stewart algorithm and genotype elimination)

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