Skip to content

Graphs, Trees, and Recurrence Relations

A graph represents relationships as nodes and edges. Nodes can represent genes, cells, sequence fragments, or analysis tasks. The meaning of an edge determines which calculations have a biological interpretation.

Read sets and combinations and matrices first.

An undirected edge connects two nodes without choosing a direction. A directed edge goes from one node to another. An edge weight can represent distance, similarity, or confidence, but those meanings are not interchangeable.

This invented undirected network contains four genes. A one in its adjacency matrix means that the corresponding pair has an edge. A zero means that it does not.

import numpy as np
genes = ["A", "B", "C", "D"]
adjacency = np.array([
[0, 1, 1, 0],
[1, 0, 1, 0],
[1, 1, 0, 1],
[0, 0, 1, 0],
])
degrees = adjacency.sum(axis=1)
for gene, degree in zip(genes, degrees):
print(f"Gene {gene}: degree {degree}")
print("Edge count:", adjacency.sum() // 2)
assert np.array_equal(adjacency, adjacency.T)
Gene A: degree 2
Gene B: degree 2
Gene C: degree 3
Gene D: degree 1
Edge count: 4

The degree counts a node’s neighbors in this simple graph. The edge count divides by two because each undirected edge appears twice in the matrix. A high degree does not prove that a gene is causally important.

The diagram shows the same edges as the adjacency matrix. Its node positions help display the connections; they do not represent measurements or distances between genes.

from pathlib import Path
import matplotlib.pyplot as plt
positions = np.array([[0.0, 1.0], [0.0, -1.0], [1.0, 0.0], [2.0, 0.0]])
fig, ax = plt.subplots(figsize=(6, 4))
for first, second in zip(*np.where(np.triu(adjacency, k=1))):
ax.plot(positions[[first, second], 0], positions[[first, second], 1],
color="0.5", zorder=1)
ax.scatter(positions[:, 0], positions[:, 1], s=900, color="tab:blue", zorder=2)
for gene, position in zip(genes, positions):
ax.text(*position, gene, ha="center", va="center", color="white",
fontsize=14)
ax.set(xlim=(-0.5, 2.5), ylim=(-1.5, 1.5), aspect="equal")
ax.axis("off")
fig.tight_layout()
Path("outputs").mkdir(exist_ok=True)
fig.savefig("outputs/gene_network.png", dpi=160)
plt.close(fig)

The invented network connects A, B, and C in a triangle, with D connected only to C.

A walk follows edges and can revisit a node. A simple path does not revisit nodes. A cycle returns to its start. A tree is a connected undirected graph without cycles, so exactly one simple path connects each pair of nodes.

Powers of an unweighted adjacency matrix count walks of a given length. They do not generally count simple paths.

two_step_walks = adjacency @ adjacency
print("Two-step walks from A to D:", two_step_walks[0, 3])
print("Two-step walks from A back to A:", two_step_walks[0, 0])
Two-step walks from A to D: 1
Two-step walks from A back to A: 2

A phylogenetic tree adds a particular evolutionary interpretation to the nodes and branches. A directed acyclic graph allows multiple incoming edges and need not be a tree. Workflow managers use such graphs to represent task dependencies.

Sequence edit distance provides a small recurrence with a biological connection. It counts the minimum insertions, deletions, and substitutions needed to turn one string into another. Each operation has cost one in this example.

Let D[i,j] denote the distance between prefixes of lengths i and j. The boundary values are D[i,0]=i and D[0,j]=j. Each interior cell chooses the cheapest final operation.

D[i,j] = min(
D[i-1,j] + 1,
D[i,j-1] + 1,
D[i-1,j-1] + substitution_cost
)

The substitution cost is zero for matching characters and one otherwise. Each cell depends only on earlier cells, so a table avoids repeated calculations.

sequence_a = "GATTACA"
sequence_b = "GACTATA"
distance = np.zeros((len(sequence_a) + 1, len(sequence_b) + 1), dtype=int)
distance[:, 0] = np.arange(len(sequence_a) + 1)
distance[0, :] = np.arange(len(sequence_b) + 1)
for row, base_a in enumerate(sequence_a, start=1):
for column, base_b in enumerate(sequence_b, start=1):
substitution_cost = int(base_a != base_b)
distance[row, column] = min(
distance[row - 1, column] + 1,
distance[row, column - 1] + 1,
distance[row - 1, column - 1] + substitution_cost,
)
print("Edit distance:", distance[-1, -1])
print("Distance from the empty string:", distance[0, -1])
Edit distance: 2
Distance from the empty string: 7

For lengths m and n, the table requires O(m*n) operations and memory proportional to m*n. Keeping only the previous and current rows reduces memory when only the distance is needed. Recovering an alignment requires more information.

The first row and column describe conversion to or from the empty string. Every other cell contains the best cost for its pair of prefixes. Print the completed table to see how the final distance depends on smaller comparisons.

print(" " + " ".join(["-"] + list(sequence_b)))
for label, row_values in zip(["-"] + list(sequence_a), distance):
print(f"{label} " + " ".join(str(value) for value in row_values))
row = column = 3
print("Delete cost:", distance[row - 1, column] + 1)
print("Insert cost:", distance[row, column - 1] + 1)
print("Substitute cost:", distance[row - 1, column - 1] + 1)
- G A C T A T A
- 0 1 2 3 4 5 6 7
G 1 0 1 2 3 4 5 6
A 2 1 0 1 2 3 4 5
T 3 2 1 1 1 2 3 4
T 4 3 2 2 1 2 2 3
A 5 4 3 3 2 1 2 2
C 6 5 4 3 3 2 2 3
A 7 6 5 4 4 3 3 2
Delete cost: 2
Insert cost: 2
Substitute cost: 1

The selected cell compares the prefixes GAT and GAC. Their final characters differ, so the diagonal predecessor receives a substitution cost. The cell above represents a deletion, and the cell to the left represents an insertion. The smallest candidate determines the cell’s value.

The table records costs rather than an explicit sequence of operations. To recover an alignment, trace a sequence of predecessor choices backward from the last cell. Equal candidate costs can produce more than one optimal alignment.

This unit-cost distance does not model substitution probabilities or affine gap penalties. Biological alignment methods choose scores and boundary conditions for their scientific task. A recurrence describes the computation, while the scoring model defines its meaning.

Does every connected network qualify as a tree?

It does not. A tree must also have no cycles. The triangle in this example supplies a cycle, so the network remains a graph with multiple routes between some nodes.

  • MIT Mathematics for Computer Science

    The course covers graphs, discrete structures, and mathematical reasoning. Its open textbook extends the adjacency and dependency definitions.

  • Chulalongkorn edit-distance lesson

    The lesson derives a dynamic programming recurrence from insertion, deletion, and substitution costs. Its table initialization and pseudocode explain the boundary conditions used here.

Continue with numerical accuracy. The Nextflow guide applies dependency graphs to analysis tasks.