Algorithm Search⌘K

Data structureadvanced

Variation graph

Also called genome graph, pangenome graph.

A sequence graph whose paths spell a reference and known variant haplotypes, so that reads align to the variation instead of one linear genome.

A variation graph stores a reference genome together with known variants as one graph. Each node holds a piece of DNA sequence, and each edge says that one piece can follow another. The reference is one path through the graph, and each variant adds a second route around the reference bases it changes. Every path from the start to the end spells one possible genome, a haplotype. Reads can then be aligned to the graph instead of to one linear sequence, so a read that carries a known variant matches it exactly, without the bias toward the reference allele that a linear reference gives. The vg toolkit of Garrison et al. (2018) made this practical at the scale of a human genome.

In plain words

A reference genome is one long line of letters. But people differ from it at millions of places, and a read from a person with a different letter looks like an error when you compare it to that line.

A variation graph splits the line at each known difference and adds a short side road with the other version. A side road can also be empty, for a missing piece, or extra letters, for an added piece. Each way through the graph, taking the main road or the side road at each place, spells one version of the genome. A read can now match the version it comes from.

The abstract type

A sequence graph is a directed graph whose nodes are labeled with non-empty strings. A walk w1→w2→⋯→wtw_1 \to w_2 \to \cdots \to w_t spells the concatenation of its node strings. A variation graph is a sequence graph with a set of named paths, the walks that spell known sequences, such as the reference or the haplotypes of a sample.

This page builds the graph from a reference and a list of variants. A variant (p,a,b)(p, a, b) replaces the reference bases ref[p:p+∣a∣]\mathit{ref}[p{:}p + |a|], which must equal aa, by the string bb. One of aa and bb may be empty, for an insertion or a deletion, and a≠ba \ne b. The variants must not touch each other or the ends of the reference. The structure supports:

  • BUILD(ref,variants)(\mathit{ref}, \text{variants}): make the graph and the path of the reference;
  • SPELL(path)(\text{path}): the string of a walk;
  • HAPLOTYPE(C)(C): the walk that takes the alternative allele of the variants in the set CC and the reference allele of the others;
  • FIND(s)(s): every place (node, offset) where the string ss starts an exact match along some walk.

Representation

The nodes are numbered 0,1,2,…0, 1, 2, \ldots in the order of their start on the reference, and each node keeps its string and a sorted list of its successors. The graph keeps the named paths as lists of node ids, and for each variant its bubble: the node before it, the node after it, and the two routes between them. Real toolkits use a bidirected graph, in which each node can be read on either strand and an edge joins two node sides, so that inversions and reads from both strands fit in one graph.

Operations

BUILD cuts the reference at both ends of every variant, which makes the reference nodes, and adds one node for each non-empty alternative allele. An inserted node is numbered before the reference node that starts at the same place, so that every edge goes from a smaller id to a larger one.

  1. BUILD(ref, V)
  2. 1cuts ← {0, |ref|} ∪ {p, p + |a| : (p, a, b) in V}, sorted
  3. 2make a reference node for ref[x..y) for each two adjacent cuts x < y
  4. 3make an alt node for b for each (p, a, b) in V with b non-empty, numbered by start position
  5. 4join the reference nodes in order with edges; this is the path "ref"
  6. 5for each variant (p, a, b) in V, with u the node that ends at p and w the node that starts at p + |a| do
  7. 6if b is non-empty then add the edges u → (the node of b) → w
  8. 7else add the edge u → w

FIND keeps a set of states, each a start place and a current place. It begins at every base equal to s[0]s[0] and, for each next character of ss, moves every state one base on: inside the node if it is not at the end, and to base 0 of each successor if it is.

  1. FIND(G, s)
  2. 1S ← {(i, k, i, k) : base k of node i equals s[0]}
  3. 2for each next character c of s do
  4. 3a state at (i, k) with k + 1 < |seq(i)| moves to (i, k + 1)
  5. 4a state at the end of node i moves to (j, 0) for each successor j of i; keep only the states whose new base is c
  6. 5return the sorted set of the start places (i, k) of the states left

SPELL joins the strings of the nodes of a walk, after checking each edge. HAPLOTYPE follows the reference path and, at each bubble in CC, takes the alternative route. Mapping reads with errors is sequence-to-graph alignment, the dynamic program of alignment run along the graph in topological order.

Example

The reference is CTAGGATCCAGT\texttt{CTAGGATCCAGT}, of 12 bases, and there are three variants: a substitution (2,A,G)(2, \texttt{A}, \texttt{G}), a deletion (5,AT,empty)(5, \texttt{AT}, \text{empty}) and an insertion (9,empty,TT)(9, \text{empty}, \texttt{TT}). The cuts are 0, 2, 3, 5, 7, 9 and 12. BUILD makes eight nodes:

id string kind
0 CT reference
1 A reference allele of the substitution
2 G alternative allele of the substitution
3 GG reference
4 AT reference allele of the deletion
5 CC reference
6 TT inserted
7 AGT reference

The edges are 0→10 \to 1, 0→20 \to 2, 1→31 \to 3, 2→32 \to 3, 3→43 \to 4, 3→53 \to 5, 4→54 \to 5, 5→65 \to 6, 5→75 \to 7 and 6→76 \to 7. The edge 3→53 \to 5 skips the deleted bases, and node 6 is a route from 5 to 7 next to the direct edge. The reference path is 0,1,3,4,5,70, 1, 3, 4, 5, 7, which spells the reference. The walk 0,2,3,5,6,70, 2, 3, 5, 6, 7 takes all three variants and spells CTGGGCCTTAGT\texttt{CTGGGCCTTAGT}. There are 23=82^3 = 8 walks from node 0 to node 7, one for each set of variants.

FIND(AGGCCTTA\texttt{AGGCCTTA}) returns (1,0)(1, 0): the match runs through nodes 1, 3, 5, 6 and 7, on the haplotype with the deletion and the insertion, and the string does not occur in the reference. FIND(GGATCC\texttt{GGATCC}) returns (3,0)(3, 0), a match on the reference path. FIND(GG\texttt{GG}) returns (2,0)(2, 0) and (3,0)(3, 0): the first match crosses the edge 2→32 \to 3. FIND(GGGG\texttt{GGGG}) returns nothing, because no walk has four G bases in a row.

Correctness

The cuts never fall inside the reference allele of a variant, so each variant gives one bubble between a node uu and a node ww with exactly two routes, which spell aa and bb. Between two bubbles there is at least one reference base, so a walk from the source to the sink visits the reference nodes outside the bubbles in order and makes one choice at each bubble. This gives the theorem that the walks from the source to the sink are exactly the 2v2^v haplotypes of the vv variants, each spelling the reference with its chosen variants applied. The ids are a topological order, so the graph is acyclic. FIND keeps the invariant that after tt steps its states are exactly the walks that spell s[0..t]s[0..t], which follows from the rule for the next base along a walk. The full proofs are in proofs/correctness.md, and the tests check the walks against the haplotypes, and FIND against a search in the strings of all walks.

Proof: The paths of the built graph are exactly the haplotypes of the variant subsets, and FIND returns every exact match along a walkfull

Setting. The reference is a string ref\mathit{ref} of length nn. A variant (p,a,b)(p, a, b) replaces ref[p:p+∣a∣]\mathit{ref}[p{:}p + |a|], which must equal aa, by bb, with a≠ba \ne b. The variants (p1,a1,b1),…,(pv,av,bv)(p_1, a_1, b_1), \ldots, (p_v, a_v, b_v) are sorted by position and do not touch: p1≥1p_1 \ge 1, pt+1≥pt+∣at∣+1p_{t+1} \ge p_t + |a_t| + 1, and pv+∣av∣≤n−1p_v + |a_v| \le n - 1. For a set CC of variant indices, refC\mathit{ref}^C is the string with the variants of CC applied and the others not. A walk is a path that follows the edges of the graph.

Lemma 1 (the nodes). Every node of BUILD holds a non-empty string. No cut lies strictly inside the reference allele ref[pt:pt+∣at∣]\mathit{ref}[p_t{:}p_t + |a_t|] of a variant, so a variant with ata_t non-empty has one reference node, whose string is ata_t. Each variant has a reference node that ends at ptp_t and one that starts at pt+∣at∣p_t + |a_t|.

Proof. Line L2 makes a node for each two adjacent distinct cuts, so its string has at least one base. Line L3 makes an alt node only for a non-empty bb. The cuts are 00, nn and the two ends of each variant. The ends of another variant lie at least one base outside [pt,pt+∣at∣][p_t, p_t + |a_t|], because the variants do not touch, so no cut lies strictly inside. The cuts pt≥1p_t \ge 1 and pt+∣at∣≤n−1p_t + |a_t| \le n - 1 are not the ends of the reference, so there is a node on each side. □\square

Call the reference nodes that are not a reference allele the backbone. The source (the node at 0) and the sink (the node that ends at nn) are in the backbone. Between two backbone nodes that are next to each other on the reference there is at most one variant, because two variants are separated by at least one backbone base.

Lemma 2 (the bubbles). For variant tt, let utu_t be the backbone node that ends at ptp_t and wtw_t the backbone node that starts at pt+∣at∣p_t + |a_t|. The walks from utu_t to wtw_t are exactly two: the reference route, through the node of ata_t (or the direct edge ut→wtu_t \to w_t if ata_t is empty), and the alternative route, through the node of btb_t (or the direct edge if btb_t is empty). The two routes are different and spell ata_t and btb_t between the two backbone nodes.

Proof. Line L4 joins the reference nodes in order, which gives the reference route, and lines L5 to L7 add the alternative route. No other line adds an edge out of utu_t, out of the allele nodes, or into wtw_t from inside the bubble, since the other variants have their own uu and ww nodes outside [pt,pt+∣at∣][p_t, p_t + |a_t|]. At least one of ata_t, btb_t is non-empty, and if both are, they are two different nodes, so the routes differ. □\square

Lemma 3 (topological ids). Every edge goes from a smaller id to a larger id.

Proof. The ids follow the start position on the reference, with an inserted node before the reference node at the same start and an alt node after the reference allele at the same start. A reference edge goes to a node that starts later. An edge ut→u_t \to alt goes to a node that starts at ptp_t, after the start of utu_t. An edge alt →wt\to w_t goes to a node that starts at pt+∣at∣p_t + |a_t|, which is later for a non-empty ata_t; for an insertion the two start at the same place, and the inserted node has the smaller id by its order. A direct edge ut→wtu_t \to w_t goes to a later start. □\square

So the graph is a directed acyclic graph, and the walks are finite.

Theorem 1 (the paths are the haplotypes). The map from a set C⊆{1,…,v}C \subseteq \{1, \ldots, v\} to the walk that takes the alternative route at the variants of CC and the reference route at the others is a one-to-one map onto the walks from the source to the sink. The walk of CC spells refC\mathit{ref}^C. In particular the reference path spells ref\mathit{ref}, and there are 2v2^v walks from the source to the sink.

Proof. A walk from the source must leave each backbone node by one of its edges. A backbone node that is not some utu_t has one out-edge, to the next backbone node. At utu_t, by Lemma 2, the walk takes one of the two routes and comes to wtw_t. So every walk from the source to the sink visits all backbone nodes in order and picks one route at each bubble, and the set of bubbles where it takes the alternative route is its CC. Different sets give different walks, because the routes differ. The spelled string is the backbone strings in order with ata_t or btb_t put between utu_t and wtw_t, which is refC\mathit{ref}^C. □\square

Lemma 4 (one step of FIND). If a walk is at base kk of node ii, its next base is base k+1k + 1 of node ii when k+1<∣seq(i)∣k + 1 < |\mathit{seq}(i)|, and otherwise base 0 of a successor of ii, one for each out-edge.

Proof. A walk spells the strings of its nodes one after the other, and every node is non-empty by Lemma 1, so base 0 of each successor exists. □\square

Theorem 2 (FIND). After line L8 and tt runs of lines L9 to L11, the state set holds (i0,k0,i,k)(i_0, k_0, i, k) exactly when some walk has s[0:t+1]s[0{:}t+1] as the bases from base k0k_0 of node i0i_0 to base kk of node ii. Line L12 returns every place (i0,k0)(i_0, k_0) where ss starts along some walk, and every node lies on a walk from the source to the sink, so these are also the places where ss starts in the string of some haplotype path, mapped to the graph.

Proof. For t=0t = 0, line L8 keeps the places whose base is s[0]s[0], each as its own start. For the step, a walk that matches s[0:t+2]s[0{:}t+2] is a walk that matches s[0:t+1]s[0{:}t+1], ending at (i,k)(i, k), followed by the next base of Lemma 4, which must be s[t+1]s[t+1]. Lines L10 and L11 make every such next base and keep the ones equal to s[t+1]s[t+1]. Every node is a backbone node or on a route of a bubble, so by the proof of Theorem 1 it lies on a walk from the source to the sink, and every walk from a node can be extended to such a walk on both sides. □\square

The test compares FIND with a search of ss in the strings of all 2v2^v haplotype paths.

Cost. BUILD sorts the variants and the cuts in O(vlog⁡v)O(v \log v) time and copies the reference in O(n)O(n) time. It makes at most 2v+12v + 1 reference nodes and vv alt nodes, and at most 4v4v edges: 2v2v along the reference path and two for each variant. FIND keeps states of a start and a current place. With NN bases in the graph and out-degree at most dd, each of the ∣s∣−1|s| - 1 steps costs O(d)O(d) per state. A test for whether ss occurs at all needs only the current places, at most NN of them, so it costs O(∣s∣Nd)O(|s| N d) time; keeping the starts can raise the number of states up to N2N^2 in the worst case.

Complexity

  • BUILD. Sorting the variants and the cuts takes O(vlog⁡v)O(v \log v) time, and copying the reference takes O(n)O(n) for a reference of length nn. The graph has at most 3v+13v + 1 nodes and 4v4v edges.
  • SPELL and HAPLOTYPE. Linear in the length of the result.
  • FIND. With NN bases in the graph and out-degree at most dd, the current places are at most NN, so a test for whether ss occurs costs O(∣s∣Nd)O(|s| N d). Keeping the start of each state can raise the number of states to N2N^2 in the worst case.
  • Space. O(n+∑∣b∣)O(n + \sum |b|) for the strings and O(v)O(v) for the edges and bubbles.

A search of each read against the whole graph state by state is too slow for a genome. Toolkits index the graph instead: vg uses GCSA2, a generalization of the FM-index to the paths of a graph, to find seeds, and then aligns around them.

Variants

  • Bidirected graphs. Each node has two sides, for the two strands. This allows inversions and the reads of both strands.
  • Graphs from assemblies. Instead of a reference and a VCF file, the graph can come from the alignment of many whole genome assemblies, which also holds large and nested variants.
  • Graphs with cycles. Duplications and repeats make cycles, which the build of this page never makes.
  • Haplotype indexes. The GBWT stores the haplotypes of many samples as paths in compact form, in the style of the positional Burrows-Wheeler transform, so that a mapper can prefer the walks that real haplotypes take.
  • De Bruijn graphs. A de Bruijn graph of the k-mers of many genomes is another kind of sequence graph, with nodes of a fixed length.

When to use it

Use a variation graph when reads come from a population with many known variants, and a linear reference would bias the alignment toward its own alleles, as near insertions and deletions or in regions of high diversity such as the HLA genes. It also lets a caller genotype known structural variants from short reads, since the reads that cross them align to their routes. When the variants are rare, or the reads are long and few, a linear reference is simpler and the gain is small.

Pitfalls

  • Too many variants. Every bubble doubles the number of walks, and close variants make many combinations that no real haplotype has. Reads can then align to a walk that does not exist in the population. Filter rare variants, or use a haplotype index.
  • Overlapping variants. Two variants that share bases need a joint bubble; the simple build of this page rejects them.
  • Coordinates. A position on the graph is a node and an offset. To report results in reference coordinates, project them onto the reference path, and decide what to do with places on alternative routes.
  • Normalization of the input. The same insertion or deletion written at two places in a repeat gives two bubbles; normalize the variants first.

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.

variation_graph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variation-graph/. The authors are listed in prov/XJVQNQ.jsonl.
"""A variation graph built from a linear reference and a list of variants.

A variant (pos, a, b) replaces the reference bases ref[pos:pos + len(a)] by
the string b. Either a or b may be empty (an insertion or a deletion), but
not both, and a != b. Positions are 0-based. The variants must not touch:
each one starts at least one base after the end of the one before it, and
each one has at least one reference base on each side. These rules make
every node non-empty and every variant one bubble of the graph.

Each node holds a string. The graph has the reference path, which spells the
reference, and one path for each subset of the variants. Node ids are
0, 1, 2, ... in the order of the start of the node on the reference, with the
reference allele before the alternative allele, so the order of the ids is a
topological order.

The module has three operations: build the graph, spell a path, and find the
exact matches of a string along the walks of the graph. What it leaves out
compared with vg: the bidirected form (both strands of a node), variants
that overlap or touch, a graph built from whole-genome alignments,
alignment with errors, and an index such as the GCSA2 or GBWT.
"""

from __future__ import annotations

from typing import Dict, List, Sequence, Tuple

Variant = Tuple[int, str, str]


class VariationGraph:
    """Nodes with strings, edges between them and named paths."""

    def __init__(self) -> None:
        self.seq: List[str] = []
        self.succ: List[List[int]] = []
        self.paths: Dict[str, List[int]] = {}
        # bubble[v] = (u, w, ref_route, alt_route): the bubble of variant v.
        self.bubble: List[Tuple[int, int, List[int], List[int]]] = []

    def add_node(self, s: str) -> int:
        self.seq.append(s)
        self.succ.append([])
        return len(self.seq) - 1

    def add_edge(self, u: int, w: int) -> None:
        if w not in self.succ[u]:
            self.succ[u].append(w)
            self.succ[u].sort()


def build(ref: str, variants: Sequence[Variant]) -> VariationGraph:
    """The graph of ref and the variants, with the path "ref"."""
    vs = sorted(variants)
    end = 0
    for pos, a, b in vs:
        if a == b:
            raise ValueError("a variant must change the sequence")
        if pos < end + 1 or pos < 1 or pos + len(a) > len(ref) - 1:
            raise ValueError("variants must not touch each other or the ends of the reference")
        if ref[pos:pos + len(a)] != a:
            raise ValueError("the reference allele does not match the reference")
        end = pos + len(a)
    g = VariationGraph()
    cuts = sorted({0, len(ref)} | {p for p, _, _ in vs} | {p + len(a) for p, a, _ in vs})  # @line L1
    node_at: Dict[int, int] = {}  # start on the reference -> reference node
    # (start, order, string): order 0 for a reference node, 1 for an alt node, and -1 for an
    # inserted node, which comes before the reference node that starts at the same place.
    pieces: List[Tuple[int, int, str]] = []
    for x, y in zip(cuts, cuts[1:]):  # @line L2
        pieces.append((x, 0, ref[x:y]))
    for pos, a, b in vs:
        if b:
            pieces.append((pos, 1 if a else -1, b))  # @line L3
    pieces.sort()
    alt_node: Dict[int, int] = {}
    for start, order, s in pieces:
        i = g.add_node(s)
        if order == 0:
            node_at[start] = i
        else:
            alt_node[start] = i
    ref_path = [node_at[x] for x in cuts[:-1]]
    for u, w in zip(ref_path, ref_path[1:]):  # @line L4
        g.add_edge(u, w)
    ends_at = {cuts[t + 1]: node_at[cuts[t]] for t in range(len(cuts) - 1)}
    for pos, a, b in vs:  # @line L5
        u, w = ends_at[pos], node_at[pos + len(a)]
        ref_route = [node_at[pos]] if a else []
        if b:
            alt_route = [alt_node[pos]]
            g.add_edge(u, alt_route[0])  # @line L6
            g.add_edge(alt_route[0], w)
        else:
            alt_route = []
            g.add_edge(u, w)  # @line L7
        g.bubble.append((u, w, ref_route, alt_route))
    g.paths["ref"] = ref_path
    return g


def spell(g: VariationGraph, path: Sequence[int]) -> str:
    """The string of a path: the strings of its nodes, joined. The path must follow edges."""
    for u, w in zip(path, path[1:]):
        if w not in g.succ[u]:
            raise ValueError(f"no edge from {u} to {w}")
    return "".join(g.seq[i] for i in path)


def haplotype_path(g: VariationGraph, chosen: Sequence[int]) -> List[int]:
    """The path that takes the alternative route of the variants in chosen (indices
    into the sorted variant list) and the reference route of the others."""
    pick = set(chosen)
    ref_path = g.paths["ref"]
    out: List[int] = []
    t = 0
    for v, (u, w, ref_route, alt_route) in enumerate(g.bubble):
        while ref_path[t] != u:
            out.append(ref_path[t])
            t += 1
        out.append(u)
        out.extend(alt_route if v in pick else ref_route)
        t = ref_path.index(w)
    out.extend(ref_path[t:])
    return out


def walks(g: VariationGraph) -> List[List[int]]:
    """Every path from the first to the last reference node, in sorted order."""
    source, sink = g.paths["ref"][0], g.paths["ref"][-1]
    out: List[List[int]] = []

    def go(path: List[int]) -> None:
        u = path[-1]
        if u == sink:
            out.append(list(path))
            return
        for w in g.succ[u]:
            path.append(w)
            go(path)
            path.pop()

    go([source])
    return sorted(out)


def find(g: VariationGraph, s: str) -> List[Tuple[int, int]]:
    """The places (node, offset) where s starts an exact match along some walk of the graph.

    A match may start in any node and cross edges. The search keeps the set of
    (start, node, offset) states that have matched a prefix of s.
    """
    if not s:
        return []
    states = {(i, k, i, k) for i, x in enumerate(g.seq) for k in range(len(x)) if x[k] == s[0]}  # @line L8
    for c in s[1:]:  # @line L9
        nxt = set()
        for si, sk, i, k in states:
            if k + 1 < len(g.seq[i]):  # @line L10
                steps = [(i, k + 1)]
            else:  # @line L11
                steps = [(w, 0) for w in g.succ[i]]
            for j, t in steps:
                if g.seq[j][t] == c:
                    nxt.add((si, sk, j, t))
        states = nxt
    return sorted({(si, sk) for si, sk, _, _ in states})  # @line L12
test_variation_graph.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variation-graph/. The authors are listed in prov/XJVQNQ.jsonl.

import itertools
import random

from variation_graph import build, find, haplotype_path, spell, walks

EXAMPLE_REF = "CTAGGATCCAGT"
EXAMPLE_VARIANTS = [(2, "A", "G"), (5, "AT", ""), (9, "", "TT")]


def apply(ref, variants, chosen):
    """ref with the chosen variants (indices into the sorted list) applied, built directly."""
    out, t = [], 0
    for v, (pos, a, b) in enumerate(sorted(variants)):
        out.append(ref[t:pos])
        out.append(b if v in chosen else a)
        t = pos + len(a)
    out.append(ref[t:])
    return "".join(out)


def random_case(rng):
    n = rng.randint(4, 16)
    ref = "".join(rng.choice("ACGT") for _ in range(n))
    variants, x = [], 1 + rng.randint(0, 2)
    while x < n - 1 and len(variants) < 4:
        la = rng.randint(0, min(3, n - 1 - x))
        lb = rng.randint(0, 3)
        a = ref[x:x + la]
        b = "".join(rng.choice("ACGT") for _ in range(lb))
        if a != b:
            variants.append((x, a, b))
            x += la + 1 + rng.randint(0, 2)
        else:
            x += 1
    return ref, variants


def test_example_graph():
    g = build(EXAMPLE_REF, EXAMPLE_VARIANTS)
    assert g.seq == ["CT", "A", "G", "GG", "AT", "CC", "TT", "AGT"]
    assert g.succ == [[1, 2], [3], [3], [4, 5], [5], [6, 7], [7], []]
    assert g.paths["ref"] == [0, 1, 3, 4, 5, 7]
    assert spell(g, g.paths["ref"]) == EXAMPLE_REF
    assert spell(g, haplotype_path(g, [0, 1, 2])) == "CTGGGCCTTAGT"
    assert len(walks(g)) == 8


def test_example_find():
    g = build(EXAMPLE_REF, EXAMPLE_VARIANTS)
    # This read needs the deletion and the insertion; it is not in the reference.
    assert find(g, "AGGCCTTA") == [(1, 0)]
    assert "AGGCCTTA" not in EXAMPLE_REF
    # A read of the reference is found at its reference place.
    assert find(g, "GGATCC") == [(3, 0)]
    # GG starts in two places: at the start of node 3, and in node 2 across the edge to node 3.
    assert find(g, "GG") == [(2, 0), (3, 0)]
    assert find(g, "GGGG") == []


def test_ids_are_a_topological_order():
    rng = random.Random(11)
    for _ in range(300):
        ref, vs = random_case(rng)
        g = build(ref, vs)
        for u, out in enumerate(g.succ):
            assert all(w > u for w in out)
        assert all(g.seq)


def test_paths_are_the_haplotypes():
    rng = random.Random(12)
    for _ in range(300):
        ref, vs = random_case(rng)
        g = build(ref, vs)
        assert spell(g, g.paths["ref"]) == ref
        subsets = [c for r in range(len(vs) + 1) for c in itertools.combinations(range(len(vs)), r)]
        paths = []
        for c in subsets:
            p = haplotype_path(g, c)
            assert spell(g, p) == apply(ref, vs, set(c))
            paths.append(p)
        # Each walk is the path of exactly one subset of the variants.
        assert sorted(paths) == walks(g)
        assert len(walks(g)) == 2 ** len(vs)


def brute_find(g, s):
    starts = set()
    for w in walks(g):
        owner = [(i, k) for i in w for k in range(len(g.seq[i]))]
        text = spell(g, w)
        for p in range(len(text) - len(s) + 1):
            if text[p:p + len(s)] == s:
                starts.add(owner[p])
    return sorted(starts)


def test_find_against_all_walks():
    rng = random.Random(13)
    checked = 0
    for _ in range(200):
        ref, vs = random_case(rng)
        g = build(ref, vs)
        hap = apply(ref, vs, {v for v in range(len(vs)) if rng.random() < 0.5})
        for _ in range(4):
            if rng.random() < 0.7:
                i = rng.randrange(len(hap))
                s = hap[i:i + rng.randint(1, 8)]
            else:
                s = "".join(rng.choice("ACGT") for _ in range(rng.randint(1, 5)))
            got = find(g, s)
            assert got == brute_find(g, s)
            checked += bool(got)
    assert checked > 300


def test_rejects_bad_variants():
    for vs in ([(0, "C", "G")], [(11, "T", "A")], [(2, "A", "G"), (3, "G", "C")],
               [(2, "A", "A")], [(2, "G", "C")], [(2, "A", "G"), (2, "", "T")]):
        try:
            build(EXAMPLE_REF, vs)
        except ValueError:
            continue
        raise AssertionError(f"expected ValueError for {vs}")

History

Graph models of genomes come from assembly, with the de Bruijn graph and the string graph. Paten, Novak, Eizenga and Garrison (2017) reviewed the use of such graphs as a reference for a population, in place of one linear genome. Garrison et al. (2018) described the vg toolkit, which builds a variation graph from a reference and a VCF file, indexes it with GCSA2 and maps reads to it, and showed that it reduces the bias toward the reference allele. Later work built graphs from many complete assemblies.

References

  1. Erik Garrison, Jouni Sirén, Adam M. Novak and others, Variation graph toolkit improves read mapping by representing genetic variation in the reference, Nature Biotechnology 36(9), 2018, pp. 875 to 879 (the variation graph with nodes, edges and embedded paths, its construction from a reference and a VCF file, and the mapping of reads to it)
  2. Benedict Paten, Adam M. Novak, Jordan M. Eizenga and Erik Garrison, Genome graphs and the evolution of genome inference, Genome Research 27(5), 2017, pp. 665 to 676 (a review of graph models of genomes, the bidirected sequence graph, and the ways to build and index such graphs)

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 proofH2 full proof
  • correctness: no review record reviews/XJVQNQ/proof-correctness.yaml
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