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.
- Evidence
- Full proofCode in 1 languages
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 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 replaces the reference bases , which must equal , by the string . One of and may be empty, for an insertion or a deletion, and . The variants must not touch each other or the ends of the reference. The structure supports:
- BUILD: make the graph and the path of the reference;
- SPELL: the string of a walk;
- HAPLOTYPE: the walk that takes the alternative allele of the variants in the set and the reference allele of the others;
- FIND: every place (node, offset) where the string starts an exact match along some walk.
Representation
The nodes are numbered 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.
BUILD(ref, V)- 1
cuts ← {0, |ref|} ∪ {p, p + |a| : (p, a, b) in V}, sorted - 2
make a reference node for ref[x..y) for each two adjacent cuts x < y - 3
make an alt node for b for each (p, a, b) in V with b non-empty, numbered by start position - 4
join the reference nodes in order with edges; this is the path "ref" - 5
for 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 - 6
if b is non-empty then add the edges u → (the node of b) → w - 7
else 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 and, for each next character of , 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.
FIND(G, s)- 1
S ← {(i, k, i, k) : base k of node i equals s[0]} - 2
for each next character c of s do - 3
a state at (i, k) with k + 1 < |seq(i)| moves to (i, k + 1) - 4
a 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 - 5
return 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 , 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 , of 12 bases, and there are three variants: a substitution , a deletion and an insertion . 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 , , , , , , , , and . The edge skips the deleted bases, and node 6 is a route from 5 to 7 next to the direct edge. The reference path is , which spells the reference. The walk takes all three variants and spells . There are walks from node 0 to node 7, one for each set of variants.
FIND() returns : 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() returns , a match on the reference path. FIND() returns and : the first match crosses the edge . FIND() 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 and a node with exactly two routes, which spell and . 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 haplotypes of the 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 steps its states are exactly the walks that spell , 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 of length . A variant replaces , which must equal , by , with . The variants are sorted by position and do not touch: , , and . For a set of variant indices, is the string with the variants of 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 of a variant, so a variant with non-empty has one reference node, whose string is . Each variant has a reference node that ends at and one that starts at .
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 . The cuts are , and the two ends of each variant. The ends of another variant lie at least one base outside , because the variants do not touch, so no cut lies strictly inside. The cuts and are not the ends of the reference, so there is a node on each side.
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 ) 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 , let be the backbone node that ends at and the backbone node that starts at . The walks from to are exactly two: the reference route, through the node of (or the direct edge if is empty), and the alternative route, through the node of (or the direct edge if is empty). The two routes are different and spell and 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 , out of the allele nodes, or into from inside the bubble, since the other variants have their own and nodes outside . At least one of , is non-empty, and if both are, they are two different nodes, so the routes differ.
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 alt goes to a node that starts at , after the start of . An edge alt goes to a node that starts at , which is later for a non-empty ; for an insertion the two start at the same place, and the inserted node has the smaller id by its order. A direct edge goes to a later start.
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 to the walk that takes the alternative route at the variants of 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 spells . In particular the reference path spells , and there are 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 has one out-edge, to the next backbone node. At , by Lemma 2, the walk takes one of the two routes and comes to . 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 . Different sets give different walks, because the routes differ. The spelled string is the backbone strings in order with or put between and , which is .
Lemma 4 (one step of FIND). If a walk is at base of node , its next base is base of node when , and otherwise base 0 of a successor of , 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.
Theorem 2 (FIND). After line L8 and runs of lines L9 to L11, the state set holds exactly when some walk has as the bases from base of node to base of node . Line L12 returns every place where starts along some walk, and every node lies on a walk from the source to the sink, so these are also the places where starts in the string of some haplotype path, mapped to the graph.
Proof. For , line L8 keeps the places whose base is , each as its own start. For the step, a walk that matches is a walk that matches , ending at , followed by the next base of Lemma 4, which must be . Lines L10 and L11 make every such next base and keep the ones equal to . 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.
The test compares FIND with a search of in the strings of all haplotype paths.
Cost. BUILD sorts the variants and the cuts in time and copies the reference in time. It makes at most reference nodes and alt nodes, and at most edges: along the reference path and two for each variant. FIND keeps states of a start and a current place. With bases in the graph and out-degree at most , each of the steps costs per state. A test for whether occurs at all needs only the current places, at most of them, so it costs time; keeping the starts can raise the number of states up to in the worst case.
Complexity
- BUILD. Sorting the variants and the cuts takes time, and copying the reference takes for a reference of length . The graph has at most nodes and edges.
- SPELL and HAPLOTYPE. Linear in the length of the result.
- FIND. With bases in the graph and out-degree at most , the current places are at most , so a test for whether occurs costs . Keeping the start of each state can raise the number of states to in the worst case.
- Space. for the strings and 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XJVQNQ Edit this page History Report an error Markdown