MATH 4310 · Computational Bioinformatics

Eulerian Paths, Repeats, and Assembly Errors

Lesson 7 · 2027-02-03 · Week 4

Core question

Do a genome’s short words determine its full sequence?

Eulerian paths

Assembly starts with overlapping reads whose positions in the genome are unknown. Lesson 6 represented their short words in a de Bruijn graph: each word supplies an edge, and matching suffixes and prefixes allow edges to follow one another. For the ideal 3-mer multiset of TACGACG, those edges must be ordered to use TAC once, ACG twice, CGA once, and GAC once. Following that order spells a candidate DNA sequence.

Our first task is to find such an ordering without guessing at branches. Throughout, the multiset is the ideal genomic one, in which each genome position contributes exactly one \(k\)-mer occurrence, so a complete reconstruction uses each edge exactly once. This is an Eulerian path problem, named for Euler’s 1735 answer to a puzzle from Königsberg: could a walk cross each of the city’s seven bridges exactly once? He settled it by counting the bridges that meet at each landmass.1 The same counting, applied to directed edges, decides whether a reconstruction exists, and an algorithm modeled on its proof builds one in linear time.

A complete path gives a candidate genome, but we still need to know whether other paths spell different sequences. Choosing an unsupported order can give a false account of how genes are arranged. Repeats can leave the data compatible with several genomes, and with real reads, errors and coverage gaps add or remove edges. An assembler then reports contigs, stretches that every compatible genome shares.

For example, ACGTCGACG and ACGACGTCG contain exactly the same 3-mers with the same counts, so they have the same de Bruijn graph. Figure 7.1 draws that graph twice, each time with a different loop from CG taken first, and spells the resulting genome beneath it. The two loops append TCG and ACG, and taking them in the other order swaps those letters in the genome. A route through this graph is a valid reconstruction, but the words alone cannot say which of the two genomes supplied them.

Two copies of the same directed multigraph, each above a nine-letter string. The upper graph highlights CG to GT to TC to CG above ACGTCGACG, with letters 4 to 6 (TCG) on red; the lower highlights CG to GA to AC to CG above ACGACGTCG, with letters 4 to 6 (ACG) on red.

Figure 7.1. One graph, two genomes. Each panel highlights the loop from CG that a complete traversal takes first and, beneath it, the string the traversal spells, with the three letters appended by the highlighted loop in red. Swapping the order of the two loops swaps TCG and ACG in the spelled genome while using the same edges.

Recall that \(\operatorname{Comp}_k(x)\) lists the length-\(k\) substrings of \(x\), including repeated occurrences. In \(D(K)\), each word in the multiset \(K\) supplies an edge from its length-\((k-1)\) prefix to its length-\((k-1)\) suffix, identical words supply parallel edges, and following an edge appends the word’s last base to the sequence spelled so far.

Definition 7.1 Eulerian path and cycle

An Eulerian path uses every edge exactly once. An Eulerian cycle is an Eulerian path whose first and last nodes agree.

Nodes may repeat; the restriction falls on edges, because they represent the \(k\)-mer occurrences that a reconstruction must consume.

In these terms, the previous lesson’s conclusion reads: a string \(x\) with \(\operatorname{Comp}_k(x)=K\) determines an Eulerian path in \(D(K)\), and every Eulerian path in \(D(K)\) spells a string with composition \(K\).

Proof sketch

List the genome’s \(k\)-mers in order as \(w^{(1)},\ldots,w^{(q)}\). Consecutive words overlap in \(k-1\) letters, \[ \operatorname{suffix}\bigl(w^{(j)}\bigr)=\operatorname{prefix}\bigl(w^{(j+1)}\bigr), \] so their edges meet head to tail and form a walk that uses each edge of \(D(K)\) once. Conversely, the \(j\)th \(k\)-mer of a spelled string is the label of the \(j\)th edge traversed, so a walk that uses every edge once spells a string with \[ \operatorname{Comp}_k(\text{spelled string})=\{\!\{\text{labels of all edges}\}\!\}=K. \]

This reduces exact string reconstruction to a graph traversal. We still need to know when such a traversal exists, how to find it, and whether a different traversal would spell a different string.

Degree conditions

Write \(d^+(v)\) and \(d^-(v)\) for out-degree and in-degree, counting parallel edges.

Theorem 7.1 Eulerian path criterion

Suppose all nonzero-degree nodes of a finite directed multigraph are connected when directions are ignored. It has an Eulerian path exactly when either every node is balanced, \(d^+(v)=d^-(v)\), in which case every Eulerian path is a cycle; or there are two nodes \(s\neq t\) with \[ d^+(v)-d^-(v)=\begin{cases} \phantom{-}1, & v=s \text{ (the start)},\\ -1, & v=t \text{ (the end)},\\ \phantom{-}0, & \text{every other node } v. \end{cases} \]

Proof sketch

Necessity. Follow an Eulerian path \(v_0\to v_1\to\cdots\to v_q\). Each pass through a node enters on one edge and leaves on another, and each edge is used once, so only the two ends keep an unpaired edge: \[ d^+(v)-d^-(v)=\mathbf 1[v=v_0]-\mathbf 1[v=v_q]. \] If \(v_0=v_q\) every node is balanced; otherwise \(s=v_0\) and \(t=v_q\).

Sufficiency. In the open-path case, add an edge \(t\to s\) so that every node is balanced; cutting the finished cycle at that edge leaves a path from \(s\) to \(t\). Now let a walker start at a node \(v\) and leave each node by any unused edge.1 Standing at a node \(u\neq v\), the walker has entered \(u\) once more than it has left, so \[ \text{exits used at }u=\text{entries used at }u-1\le d^-(u)-1=d^+(u)-1, \] and an unused exit remains. The walker can get stuck only back at \(v\), so it traces a closed walk \(C_0\).

A closed walk uses as many entries as exits at each node, so the unused edges are balanced too. If any remain, some node \(w\) of \(C_0\) touches one: an undirected route from \(C_0\) to an unused edge must leave the nodes of \(C_0\) along an edge that \(C_0\) did not use. Balance gives \(w\) an unused exit. Restart the walker at \(w\), send it once around \(C_0\), and let it continue on unused edges until it is stuck at \(w\) again. Each round yields a longer closed walk, \[ |C_0|<|C_1|<|C_2|<\cdots\le|E|, \] so after finitely many rounds the closed walk uses every edge.

The proof explains why local degree counts suffice once connectivity is checked: every unfinished excursion has somewhere to rejoin the growing walk.

Example 7.1 Degree check for TACGACG

Node \(d^-\) \(d^+\) difference
TA 0 1 1
AC 2 2 0
CG 2 1 -1
GA 1 1 0

The path must start at TA and end at CG.

Interpreting degree differences

For a genome walk, the necessity argument says that only the first \((k-1)\)-mer keeps an unpaired exit and only the last an unpaired entry; for a circular genome, every node balances. This accounting gives a fast rejection test. If two nodes each have one extra outgoing edge, no ordering of the given edges can produce one linear string. The failure could come from a missing \(k\)-mer, an extra erroneous one, or data from more than one genome, and the degrees alone do not say which.

Degrees also do not test connectivity. Two separate cycles, one on nodes \(A,B\) and one on \(C,D\), balance every node, yet a walk stays trapped in the cycle where it begins. The weak-connectivity condition in Theorem 7.1 rules out this case.

Constructing a path

Hierholzer’s algorithm follows the proof. It postpones adding a node to the answer until no unused outgoing edge remains. A stack is a list whose last entry is called its top. Pushing adds an entry at that end, and popping removes the top entry.

Algorithm Construct an Eulerian path

Input: a directed multigraph with a nonempty list \(E\) of edge occurrences.

Output: an Eulerian path of \(|E|+1\) nodes, or a report that no such path exists.

  1. For each node \(v\), start an empty outgoing list \(L(v)\) and initialize \(d^+(v)\leftarrow 0\) and \(d^-(v)\leftarrow 0\).
  2. For each edge occurrence \(u\to v\) in \(E\):
    1. Append \(v\) to \(L(u)\). // store the edge endpoint
    2. \(d^+(u)\leftarrow d^+(u)+1\). // count an exit
    3. \(d^-(v)\leftarrow d^-(v)+1\). // count an entry
  3. If the degree differences violate Theorem 7.1, report failure and stop. // check degree balance
  4. If one node has \(d^+-d^-=1\), let that node be \(v_0\). Otherwise, let \(v_0\) be the source of the first edge in \(E\). // choose start by degree
  5. Start a stack containing just \(v_0\) and an empty output list \(P\). // track the current walk
  6. While the stack is nonempty: // extend or backtrack
    1. \(u\leftarrow\) the top node on the stack. // read the current node
    2. If \(L(u)\) is nonempty, remove its last entry \(v\) and push \(v\) onto the stack. // take one unused edge
    3. Otherwise, pop \(u\) from the stack and append it to \(P\). // backtrack from dead end
  7. If \(|P|<|E|+1\), report failure and stop. // check for unused edges
  8. Reverse \(P\) and return it. // restore traversal order
Python Construct and spell an Eulerian path
def eulerian_path(edges: list[tuple[str, str]]) -> list[str]:
    """Return an Eulerian node path, or raise ValueError."""
    if not edges:
        return []
    adjacency = {}
    indegree = {}
    outdegree = {}
    for source, target in edges:
        adjacency.setdefault(source, []).append(target)
        adjacency.setdefault(target, [])
        outdegree[source] = outdegree.get(source, 0) + 1
        outdegree.setdefault(target, 0)
        indegree[target] = indegree.get(target, 0) + 1
        indegree.setdefault(source, 0)

    starts = [v for v in adjacency if outdegree[v] - indegree[v] == 1]
    ends = [v for v in adjacency if indegree[v] - outdegree[v] == 1]
    bad = [v for v in adjacency if abs(outdegree[v] - indegree[v]) > 1]
    if bad or (len(starts), len(ends)) not in [(0, 0), (1, 1)]:
        raise ValueError("Degree conditions fail.")

    start = starts[0] if starts else edges[0][0]
    stack, reverse_path = [start], []
    while stack:
        node = stack[-1]
        if adjacency[node]:
            stack.append(adjacency[node].pop())
        else:
            reverse_path.append(stack.pop())
    path = reverse_path[::-1]
    if len(path) != len(edges) + 1:
        raise ValueError("Edges are disconnected.")
    return path

def spell_node_path(path: list[str]) -> str:
    """Spell a string from overlapping node labels."""
    return "" if not path else path[0] + "".join(v[-1] for v in path[1:])

edges = [("TA", "AC"), ("AC", "CG"), ("CG", "GA"),
         ("GA", "AC"), ("AC", "CG")]
path = eulerian_path(edges)
print("Eulerian path:", " → ".join(path))
print("Reconstructed sequence:", spell_node_path(path))
Eulerian path: TA → AC → CG → GA → AC → CG
Reconstructed sequence: TACGACG

For the de Bruijn graph, spelling starts with the first node’s label and appends the last letter of every later node’s label. Each traversal pushes one endpoint, and each stack entry is popped once. The adjacency lists therefore give \(\mathcal O(|V|+|E|)\) time and space. The output is reversed because a node is finalized only after all its outgoing excursions have been completed.

Stack order and path order

Take edges \(A\to B\), \(B\to A\), and \(A\to C\). The degree conditions require starting at \(A\) and ending at \(C\). Suppose the algorithm first takes \(A\to C\), reaching a dead end while two edges remain. A greedy walk that commits this order as its final answer would fail.

The stack algorithm instead postpones the final ordering:

Action Stack Output so far, before reversal
start A empty
take \(A\to C\) A, C empty
pop C A C
take \(A\to B\to A\) A, B, A C
pop until empty empty C, A, B, A

Reversing the output gives \(A,B,A,C\), which uses every edge once. The earlier dead end becomes the end of the final path. Popping a vertex records where its completed portion belongs after the remaining excursions have been inserted.

Repeats and ambiguity

For ACGTCGACG at \(k=3\), \[K=\{\!\{\texttt{ACG},\texttt{ACG},\texttt{CGT},\texttt{GTC},\texttt{TCG},\texttt{CGA},\texttt{GAC}\}\!\}.\] The node CG occurs three times in the genome. Between those visits lie two closed excursions: CG → GT → TC → CG, which appends TCG, and CG → GA → AC → CG, which appends ACG. The graph records both excursions but not their order. After the first edge AC → CG, taking the TCG excursion first spells ACGTCGACG, and taking the ACG excursion first spells ACGACGTCG, using the same edges (Figure 7.1).

Example 7.2 Two strings with one composition

Both ACGTCGACG and ACGACGTCG have composition \(K\). Data consisting only of \(K\) cannot favor either reconstruction.

The swap works for any node that a complete walk visits three times. Write such a walk as \[ P\;E_1\;E_2\;Q, \] where \(P\) is the part up to the first visit of the node \(v\), \(E_1\) and \(E_2\) are the closed excursions from \(v\) back to \(v\), and \(Q\) is the rest. Because each excursion begins and ends at \(v\), \(P\,E_2\,E_1\,Q\) is also a walk using exactly the same edges. Like every Eulerian path, it spells a string with composition \(K\), which differs from the first whenever \(E_1\) and \(E_2\) spell different letters. A \((k-1)\)-mer occurring three times in the genome supplies such a node: in ACGTCGACG, CG occurs at positions 2, 5, and 8.

A \((k-1)\)-mer that occurs only twice gives one excursion and nothing to reorder, but two such repeats can still cause ambiguity when they interleave. If the walk visits \(u\), then \(w\), then \(u\), then \(w\), write it as \(P\,A\,B\,C\,Q\), where \(A\) and \(C\) run from \(u\) to \(w\) and \(B\) runs from \(w\) back to \(u\). Then \(P\,C\,B\,A\,Q\) uses the same edges, and it spells a different string whenever \(A\) and \(C\) spell different letters. TACGACG shows why that last condition matters. Its repeated 2-mers interleave, with AC at positions 2 and 5 and CG at 3 and 6, but both segments from AC to CG are the single word ACG, so the swap returns the same string. A triple repeat or two interleaved repeats therefore makes the genome impossible to recover from its \(k\)-mers whenever swapping the segments changes the spelled string.

Existence and uniqueness

The degree theorem says whether at least one traversal exists; assembly also asks whether all traversals spell the same string. A branching node alone does not settle this, because one choice may get stuck before using every edge, or two choices may spell the same letters, as in TACGACG.

Once two strings produce the same \(K\), every algorithm receiving only \(K\) sees identical data, so no tie-breaking rule or cleverer traversal can recover which string generated it. Additional information must cross the repeat: longer k-mers, paired reads taken from the two ends of one DNA fragment with an approximately known length, which act like one long read with an unread middle, or a long read spanning both flanks.1

At \(k=4\), the two strings in Example 7.2 no longer have the same composition: only the first contains TCGA and only the second ACGA, so one extra base of context separates the candidates. In general, once no \((k-1)\)-mer occurs twice in an error-free genome, no nodes are glued, the de Bruijn graph is a single path, and the reconstruction is unique; a longer repeat needs a correspondingly larger \(k\).1

Errors, tips, and bubbles

A wrong measured base changes several overlapping k-mers at once. The resulting edges may look like a second route through a region, so an assembler must decide whether that route is a measurement artifact or a sequence actually present in the sample.

Definition 7.2 Tips and bubbles

A tip is a short dead-end path. A bubble consists of two distinct paths that diverge from one node and later rejoin, with no shared internal nodes.

Example 7.3 One substitution creates a bubble

Suppose some reads report ACGTC and one reports ACTTC. The third base differs. At \(k=3\), their k-mer lists and node paths are

Read 3-mers Node path
ACGTC ACG, CGT, GTC AC → CG → GT → TC
ACTTC ACT, CTT, TTC AC → CT → TT → TC

All three words in the second read contain the changed base, so the two paths share only their ends, AC and TC: the unchanged two-base flanks are enough for them to rejoin.

Two directed paths from AC at the left to TC at the right. The upper path passes through CG and GT; the lower highlighted path passes through CT and TT.

Figure 7.2. The reads ACGTC and ACTTC give two paths from AC to TC at k = 3; the ACTTC route is highlighted. A bubble locates conflicting sequence evidence but does not identify its cause.

Suppose twenty independently sampled reads spanning these flanks support ACGTC, and one supports ACTTC. Under a model with rare, independent sequencing errors, this imbalance supports keeping the first route. But the same graph could come from two biological versions of the region, or from similar repeat copies sampled at different depths. Read counts alone cannot distinguish those explanations, and an assembler must make this choice at each of the very many bubbles that sequencing errors create; pruning one side of a bubble formed by two inexact repeat copies erases a real difference between them. Base quality and reads spanning additional flanking sequence can supply evidence beyond this local graph.1

Bubble detection answers only the structural question of where paths disagree. Choosing a route requires assumptions about the sample and the measurement process, and when the evidence stays ambiguous, ending the contiguous sequences at the bubble avoids an unsupported join.

From a graph to contigs

After filtering and graph simplification, real data still contain branches supported by substantial evidence. To identify routes rather than count observations, aggregate repeated observations of the same \(k\)-mer into one edge and keep the count as an attribute of that edge; a word present twice in the genome should be observed about twice as often.1 In this graph, a maximal path whose internal nodes each have exactly one incoming and one outgoing edge involves no choice, so every genome compatible with the graph contains the sequence it spells. That sequence is a contig.

Return to the repeat graph of Figure 7.1. With one edge per distinct 3-mer, AC has one incoming and one outgoing edge, and only CG branches, with two edges in and two out. The non-branching paths therefore run from CG back to CG: \[ \texttt{CG}\to\texttt{GT}\to\texttt{TC}\to\texttt{CG}\ \text{spells}\ \texttt{CGTCG}, \qquad \texttt{CG}\to\texttt{GA}\to\texttt{AC}\to\texttt{CG}\ \text{spells}\ \texttt{CGACG}. \] Both candidate genomes contain both contigs, which overlap only in the repeated CG:

ACGTCGACG        ACGACGTCG
 CGTCG            CGACG
    CGACG            CGTCG

An assembler reports these two contigs and leaves their order open, which is exactly what the 3-mers determine. In Figure 7.2, the two outgoing neighbors of AC are genuinely different, so aggregating counts leaves the bubble intact, and contigs stop at its branch points. A contig ends where a route encounters branching, a coverage gap, or a chromosome end. An isolated component that forms a directed cycle needs separate treatment: choose a starting node and report the circular sequence rather than wait for a branch.1

A contig is not necessarily a chromosome, and an assembly with fewer contigs is not automatically more accurate. Joining across an unresolved repeat can produce a longer but false sequence.

A simplified short-read workflow therefore has several distinct steps:

  1. Count read-derived k-mers and remove counts poorly supported under an error model.
  2. Build a de Bruijn graph with one edge per retained distinct k-mer and keep observation counts as edge attributes.
  3. Simplify tips and bubbles when the evidence supports one path.
  4. Emit unbranched contigs and use longer-range data to order or connect them.

The degree theorem and traversal algorithm solve the ideal composition problem exactly. The contig workflow answers a different biological question: which stretches can the measured reads support without choosing among unresolved joins?

Exercises

Exercise 7.1. For \(A\to B\), \(B\to C\), \(C\to A\), and \(A\to C\), compute degrees and identify required endpoints.

Exercise 7.2. Give a balanced directed graph with no Eulerian cycle using all edges. Which theorem hypothesis fails?

Exercise 7.3. Verify the two strings in Example 7.2 have the same 3-mer multiset. Compare their 4-mer multisets.

Exercise 7.4. Change the last base of ACGTC to make ACGTA. Draw its 3-mer path together with that of ACGTC. Which edges survive, and why does this example produce two terminal alternatives rather than the rejoining bubble in Example 7.3?

Exercise 7.5. Run eulerian_path on two disconnected cycles. Explain the final length check.

References 2 sources

Cited in the text

1.Compeau, P., and P. Pevzner. 2015. Bioinformatics Algorithms: An Active Learning Approach. 2nd ed. Active Learning Publishers.↑ 1 2 3 4 5 6 7

Also drawn on

Pevzner, P. A., H. Tang, and M. S. Waterman. 2001. An Eulerian path approach to DNA fragment assembly. Proceedings of the National Academy of Sciences 98: 9748–9753. doihttps://doi.org/10.1073/pnas.171285098