2 Introduction to graph theory
Many biological systems are naturally described as networks: proteins that bind one another, genes that regulate one another, metabolites linked by reactions. Before building detailed dynamic models of such systems, a great deal can be learnt from the structure of the network alone. This chapter sets up the representation of networks in both languages; Chapter 3 then measures their structure.
2.1 Basics
2.1.1 History of graph theory
There is no code for this section; see the book.
2.1.2 Examples of graphs
There is no code for this section; see the book.
2.2 Why graphs?
There is no code for this section; see the book.
2.3 Types of graphs
2.3.1 Simple vs. non-simple graphs
There is no code for this section; see the book.
2.3.2 Directed vs. undirected graphs
There is no code for this section; see the book.
2.3.3 Weighted vs. unweighted graphs
There is no code for this section; see the book.
2.3.4 Other graph types
There is no code for this section; see the book.
2.3.5 Hypergraphs
There is no code for this section; see the book.
2.4 Computational representations of graphs
2.4.1 Data structures
There is no code for this section; see the book.
2.4.2 Adjacency matrix
A network, or graph, is a set of nodes joined by edges. For an undirected network of \(n\) nodes, the adjacency matrix \(\mathbf{A}\) has \(a_{ij} = 1\) if nodes \(i\) and \(j\) are joined, and 0 otherwise.
In MATLAB, networks are graph objects (or digraph for directed networks), part of core MATLAB. In Python, the standard package is NetworkX. Both provide shortest paths and centrality measures. In Chapter 3, we compute the clustering coefficient and closeness from their definitions, so that both languages use exactly the same formulas as the book. Table 2.1 collects the functions we use most.
| MATLAB | Python (NetworkX) | |
|---|---|---|
| Build a network | G = graph(s, t) |
G = nx.Graph(); G.add_edges_from(edges) |
| Adjacency matrix | adjacency(G) (sparse) |
nx.to_numpy_array(G) |
| Degrees | degree(G) |
dict(G.degree()) |
| Shortest-path lengths | distances(G) |
nx.floyd_warshall_numpy(G) |
| Betweenness | centrality(G, 'betweenness') |
nx.betweenness_centrality(G, normalized=False) |
2.4.3 The Laplacian matrix
The Laplacian, \(\mathbf{L} = \mathbf{D} - \mathbf{A}\), where \(\mathbf{D}\) is the diagonal matrix of degrees, has some remarkable properties. All its eigenvalues are non-negative, and the number of zero eigenvalues equals the number of connected components of the graph. The second-smallest eigenvalue, the algebraic connectivity, measures how well connected the graph is, and the signs of the corresponding eigenvector, the Fiedler vector, split the graph into two well-separated parts. Let us see this on a classic social network, Zachary’s karate club (Zachary 1977): 34 members, and 78 friendships observed outside the club, recorded just before a dispute between the instructor (member 1) and the administrator (member 34) split the club in two.
Core MATLAB only.
%% The Laplacian matrix, and what its eigenvectors say about a network
% Zachary's karate club: 34 members, and 78 friendships observed outside
% the club. A dispute between the instructor (member 1, Mr. Hi) and the
% administrator (member 34, the Officer) split the club in two. The
% Laplacian is L = D - A (book §2.4.3), where D holds the degrees on its
% diagonal. Its eigenvalues are all >= 0; the number of zero eigenvalues
% is the number of connected components; and the eigenvector of the
% second-smallest eigenvalue (the Fiedler vector) splits the network into
% two well-separated parts, by the signs of its entries.
edges = readmatrix(fullfile(sbp.data_dir(), 'karate_edges.csv'));
factions = readtable(fullfile(sbp.data_dir(), 'karate_factions.csv'), ...
'TextType', 'string');
faction = factions.faction';
n = numel(faction);
A = zeros(n);
for e = 1:size(edges, 1)
A(edges(e, 1), edges(e, 2)) = 1;
A(edges(e, 2), edges(e, 1)) = 1;
end
L = diag(sum(A, 2)) - A;
[V, D] = eig(L);
[eigenvalues, order] = sort(diag(D)); % ascending order
fiedler = V(:, order(2))';
fiedler = fiedler * sign(fiedler(1)); % member 1 positive
side = repmat("Officer", 1, n);
side(fiedler > 0) = "Mr. Hi";
agree = sum(side == faction);
misplaced = find(side ~= faction);
fprintf('Smallest eigenvalues: %s\n', mat2str(round(eigenvalues(1:4)', 4)));
fprintf('Zero eigenvalues: %d (connected components)\n', ...
sum(eigenvalues < 1e-9));
fprintf('Algebraic connectivity: %.4f\n', eigenvalues(2));
fprintf(['The Fiedler vector puts %d of %d members on the side they ' ...
'actually joined; it misplaces member(s) %s\n'], agree, n, ...
strjoin(string(misplaced), ', '));
% Remove the friendships between the two halves found by the Fiedler
% vector: the network falls apart, and a second zero eigenvalue appears
cut = side(edges(:, 1)) ~= side(edges(:, 2));
A_cut = A;
for e = find(cut)
A_cut(edges(e, 1), edges(e, 2)) = 0;
A_cut(edges(e, 2), edges(e, 1)) = 0;
end
ev_cut = eig(diag(sum(A_cut, 2)) - A_cut);
fprintf(['Cutting the %d edges between the halves leaves %d zero ' ...
'eigenvalues\n'], sum(cut), sum(ev_cut < 1e-9));
%% Plot: the network, coloured by the sign of the Fiedler vector;
% a black ring marks the members who joined the other faction
fig = figure('Position', [100 100 1100 450]);
subplot(1, 2, 1)
okabe_ito = sbp.palette();
blue = okabe_ito(1, :); red = okabe_ito(4, :);
colours = repmat(red, n, 1);
colours(side == "Mr. Hi", :) = repmat(blue, sum(side == "Mr. Hi"), 1);
h = plot(graph(A), 'Layout', 'force', 'NodeColor', colours, ...
'MarkerSize', 7, 'EdgeColor', 'k', 'EdgeAlpha', 0.3);
hold on
plot(h.XData(misplaced), h.YData(misplaced), 'ko', 'MarkerSize', 11, ...
'LineWidth', 1.5);
p1 = plot(NaN, NaN, 'o', 'MarkerFaceColor', blue, 'MarkerEdgeColor', 'none');
p2 = plot(NaN, NaN, 'o', 'MarkerFaceColor', red, 'MarkerEdgeColor', 'none');
p3 = plot(NaN, NaN, 'ko', 'LineWidth', 1.5);
legend([p1 p2 p3], {'Fiedler entry > 0', 'Fiedler entry < 0', ...
'Joined the other faction'}, 'Location', 'southwest', 'Box', 'off');
title('Split by the Fiedler vector'); axis off
subplot(1, 2, 2)
[~, order] = sort(fiedler);
b = bar(fiedler(order), 'FaceColor', 'flat', 'EdgeColor', 'none');
b.CData = colours(order, :);
xticks(1:n); xticklabels(string(order)); xtickangle(90);
ax = gca; ax.XAxis.FontSize = 7; ylim padded
xlabel('Member', 'FontSize', 11); ylabel('Fiedler vector entry')
sbp.save_figure(fig, mfilename('fullpath'), 'fig-laplacian');
results.eigenvalues = eigenvalues';
results.fiedler = fiedler;
results.agree = agree;
results.misplaced = misplaced;
results.cut_edges = sum(cut);
results.zero_eigenvalues_after_cut = sum(ev_cut < 1e-9);
sbp.save_results(mfilename('fullpath'), results);
Needs NetworkX (for drawing).
"""The Laplacian matrix, and what its eigenvectors say about a network.
Zachary's karate club: 34 members, and 78 friendships observed outside
the club. A dispute between the instructor (member 1, Mr. Hi) and the
administrator (member 34, the Officer) split the club in two. The
Laplacian is L = D - A (book §2.4.3), where D holds the degrees on its
diagonal. Its eigenvalues are all >= 0; the number of zero eigenvalues
is the number of connected components; and the eigenvector of the
second-smallest eigenvalue (the Fiedler vector) splits the network into
two well-separated parts, by the signs of its entries.
"""
import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import sbp
edges = pd.read_csv(sbp.DATA / "karate_edges.csv")
faction = pd.read_csv(sbp.DATA / "karate_factions.csv")["faction"].to_numpy()
n = len(faction)
A = np.zeros((n, n))
for i, j in edges.to_numpy() - 1: # members are 1 to 34
A[i, j] = A[j, i] = 1
L = np.diag(A.sum(axis=1)) - A
eigenvalues, eigenvectors = np.linalg.eigh(L) # ascending order
fiedler = eigenvectors[:, 1]
fiedler *= np.sign(fiedler[0]) # member 1 positive
side = np.where(fiedler > 0, "Mr. Hi", "Officer")
agree = np.sum(side == faction)
misplaced = np.flatnonzero(side != faction)
print(f"Smallest eigenvalues: {np.round(eigenvalues[:4], 4)}")
print(f"Zero eigenvalues: {np.sum(eigenvalues < 1e-9)} "
f"(connected components)")
print(f"Algebraic connectivity: {eigenvalues[1]:.4f}")
print(f"The Fiedler vector puts {agree} of {n} members on the side they "
f"actually joined; it misplaces member(s) "
f"{', '.join(str(k) for k in misplaced + 1)}")
# Remove the friendships between the two halves found by the Fiedler
# vector: the network falls apart, and a second zero eigenvalue appears
cut = [(i, j) for i, j in edges.to_numpy() - 1 if side[i] != side[j]]
A_cut = A.copy()
for i, j in cut:
A_cut[i, j] = A_cut[j, i] = 0
ev_cut = np.linalg.eigvalsh(np.diag(A_cut.sum(axis=1)) - A_cut)
print(f"Cutting the {len(cut)} edges between the halves leaves "
f"{np.sum(ev_cut < 1e-9)} zero eigenvalues")
# --- Plot: the network, coloured by the sign of the Fiedler vector;
# a black ring marks the members who joined the other faction
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.5))
G = nx.from_numpy_array(A)
pos = nx.spring_layout(G, seed=1)
blue, red = sbp.PALETTE[0], sbp.PALETTE[3]
colours = [blue if s == "Mr. Hi" else red for s in side]
nx.draw_networkx_edges(G, pos, ax=ax1, alpha=0.3)
nx.draw_networkx_nodes(G, pos, ax=ax1, node_color=colours, node_size=180)
xy = np.array([pos[k] for k in misplaced])
ax1.scatter(xy[:, 0], xy[:, 1], s=320, facecolors="none",
edgecolors="black", linewidths=1.5, zorder=3)
nx.draw_networkx_labels(G, pos, {k: k + 1 for k in range(n)}, ax=ax1,
font_size=7, font_color="white")
ax1.scatter([], [], s=60, color=blue, label="Fiedler entry > 0")
ax1.scatter([], [], s=60, color=red, label="Fiedler entry < 0")
ax1.scatter([], [], s=60, facecolors="none", edgecolors="black",
linewidths=1.5, label="Joined the other faction")
ax1.legend(loc="lower left", fontsize=9, frameon=False)
ax1.set_title("Split by the Fiedler vector")
ax1.axis("off")
order = np.argsort(fiedler)
ax2.bar(range(n), fiedler[order], color=[colours[k] for k in order])
ax2.set_xticks(range(n), order + 1, fontsize=7, rotation=90)
ax2.set_xlabel("Member")
ax2.set_ylabel("Fiedler vector entry")
sbp.save_figure(fig, __file__, "fig-laplacian")
sbp.save_results(__file__, {
"eigenvalues": eigenvalues, "fiedler": fiedler, "agree": agree,
"misplaced": misplaced + 1,
"cut_edges": len(cut),
"zero_eigenvalues_after_cut": np.sum(ev_cut < 1e-9),
})
sbp.show()
The Fiedler vector, computed from the friendships alone, places 32 of the 34 members on the side they actually joined. The two it misplaces, members 3 and 9 (highlighted in the network drawing), have friends on both sides, and their entries in the Fiedler vector are close to zero (see the bar chart). Cutting the ten friendships between the two halves disconnects the network, and a second zero eigenvalue duly appears. We shall return to this network, and to finding such groups, in §3.3.
2.5 Graph representations of biological networks
2.5.1 Networks of protein interactions and functional associations
There is no code for this section; see the book.
2.5.2 Signalling networks
There is no code for this section; see the book.
2.5.3 Protein structure networks
There is no code for this section; see the book.
2.5.4 Gene regulatory networks
There is no code for this section; see the book.
2.5.5 Metabolic networks
Metabolic networks can be represented as graphs in several ways, and the choice matters a great deal. Here, we build the substrate graph of the E. coli core model directly from its stoichiometric matrix: two metabolites are joined if one is a substrate and the other a product of the same reaction. Exchange reactions and the biomass reaction are left out.
Core MATLAB only; reads the model from data/e_coli_core.mat.
%% A metabolic network as a graph: the substrate graph of E. coli core
% In a substrate graph (book §2.5.5), metabolites are nodes, and two are
% joined if one is converted into the other by some reaction: a substrate
% and a product of the same reaction. We build it from the stoichiometric
% matrix of the E. coli core model, leaving out the exchange reactions and
% the biomass reaction. Currency metabolites, such as H+, water, ATP and
% NAD(H), take part in so many reactions that they connect almost
% everything to everything else, and shortest paths through them make no
% biochemical sense. We compare the graph with and without them.
s = load(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
model = s.e_coli_core;
S = full(model.S);
mets = model.mets;
internal = find(~startsWith(model.rxns, {'EX_', 'Biomass'}));
M = zeros(numel(mets));
for j = internal'
substrates = find(S(:, j) < 0);
products = find(S(:, j) > 0);
M(substrates, products) = 1;
M(products, substrates) = 1;
end
G = graph(M, mets);
currency = {'h_c', 'h_e', 'h2o_c', 'h2o_e', 'atp_c', 'adp_c', 'amp_c', ...
'pi_c', 'pi_e', 'nad_c', 'nadh_c', 'nadp_c', 'nadph_c', ...
'co2_c', 'co2_e', 'coa_c', 'nh4_c', 'nh4_e', 'o2_c', 'q8_c', 'q8h2_c'};
H = rmnode(G, currency);
results.with_currency = summary(G);
results.without_currency = summary(H);
deg = degree(G);
[~, order] = sortrows(table(-deg, string(mets))); % by degree, then name
results.top_degree = mets(order(1:10))';
results.top_degree_values = deg(order(1:10))';
results.glc_to_succ.with_currency = distances(G, 'g6p_c', 'succ_c');
results.glc_to_succ.without_currency = distances(H, 'g6p_c', 'succ_c');
fprintf('Most connected metabolites: %s\n', strjoin(compose('%s (%d)', ...
string(mets(order(1:10))), deg(order(1:10))), ', '));
keys = {'with_currency', 'without_currency'};
for c = 1:2
r = results.(keys{c});
fprintf(['%s: %d metabolites, %d edges, %d component(s); in the ' ...
'largest (%d), mean path %.2f, diameter %d\n'], ...
strrep(keys{c}, '_', ' '), r.nodes, r.edges, r.components, ...
r.largest, r.mean_path, r.diameter);
end
fprintf('A shortest path from glucose 6-phosphate to succinate:\n');
fprintf(' with currency metabolites: %s\n', ...
strjoin(shortestpath(G, 'g6p_c', 'succ_c'), ' - '));
fprintf(' without currency metabolites: %s\n', ...
strjoin(shortestpath(H, 'g6p_c', 'succ_c'), ' - '));
%% Plot
fig = figure('Position', [100 100 1100 400]);
subplot(1, 2, 1)
top = order(1:15);
b = bar(deg(top), 'FaceColor', 'flat', 'EdgeColor', 'none');
is_currency = ismember(mets(top), currency);
b.CData = repmat([0.000 0.447 0.698], 15, 1);
b.CData(is_currency, :) = repmat([0.835 0.369 0.000], sum(is_currency), 1);
set(gca, 'XTick', 1:15, 'XTickLabel', mets(top), ...
'TickLabelInterpreter', 'none');
xtickangle(60); ylabel('Degree');
title('Most connected metabolites (vermillion: currency)'); box off
subplot(1, 2, 2); hold on
colours = {[0.835 0.369 0.000], [0.000 0.447 0.698]};
for c = 1:2
counts = results.(keys{c}).path_counts;
plot(1:numel(counts), counts / sum(counts), 'o-', 'Color', colours{c}, ...
'MarkerFaceColor', colours{c});
end
legend({'with currency', 'without'}, 'Box', 'off');
xlabel('Shortest path length'); ylabel('Fraction of pairs');
title('Path lengths in the largest component'); box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-metabolic-graphs');
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function r = summary(G)
% Size, and path lengths within the largest connected component.
bins = conncomp(G);
largest = mode(bins);
sub = subgraph(G, find(bins == largest));
d = distances(sub);
lengths = d(triu(true(size(d)), 1));
r.nodes = numnodes(G);
r.edges = numedges(G);
r.components = max(bins);
r.largest = numnodes(sub);
r.mean_path = mean(lengths);
r.diameter = max(lengths);
r.path_counts = accumarray(lengths, 1)';
end
Needs COBRApy (to read the model) and NetworkX.
"""A metabolic network as a graph: the substrate graph of E. coli core.
In a substrate graph (book §2.5.5), metabolites are nodes, and two are
joined if one is converted into the other by some reaction: a substrate
and a product of the same reaction. We build it from the stoichiometric
matrix of the E. coli core model, leaving out the exchange reactions and
the biomass reaction. Currency metabolites, such as H+, water, ATP and
NAD(H), take part in so many reactions that they connect almost
everything to everything else, and shortest paths through them make no
biochemical sense. We compare the graph with and without them.
"""
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import cobra
from cobra.util import create_stoichiometric_matrix
import sbp
model = cobra.io.read_sbml_model(str(sbp.DATA / "e_coli_core.xml"))
S = create_stoichiometric_matrix(model)
mets = [m.id for m in model.metabolites]
internal = [j for j, r in enumerate(model.reactions)
if not r.id.startswith(("EX_", "Biomass"))]
G = nx.Graph()
G.add_nodes_from(mets)
for j in internal:
for a in np.flatnonzero(S[:, j] < 0): # substrates
for b in np.flatnonzero(S[:, j] > 0): # products
G.add_edge(mets[a], mets[b])
currency = ["h_c", "h_e", "h2o_c", "h2o_e", "atp_c", "adp_c", "amp_c",
"pi_c", "pi_e", "nad_c", "nadh_c", "nadp_c", "nadph_c",
"co2_c", "co2_e", "coa_c", "nh4_c", "nh4_e", "o2_c",
"q8_c", "q8h2_c"]
H = G.copy()
H.remove_nodes_from(currency)
def summary(graph):
"""Size, and path lengths within the largest connected component."""
largest = graph.subgraph(max(nx.connected_components(graph), key=len))
d = dict(nx.all_pairs_shortest_path_length(largest))
lengths = [d[u][v] for u in largest for v in largest if u < v]
return {"nodes": graph.number_of_nodes(), "edges": graph.number_of_edges(),
"components": nx.number_connected_components(graph),
"largest": largest.number_of_nodes(),
"mean_path": np.mean(lengths), "diameter": max(lengths),
"path_counts": np.bincount(lengths)[1:]}
results = {"with_currency": summary(G), "without_currency": summary(H)}
degree = sorted(G.degree, key=lambda x: (-x[1], x[0]))
results["top_degree"] = [m for m, _ in degree[:10]]
results["top_degree_values"] = [k for _, k in degree[:10]]
results["glc_to_succ"] = {
"with_currency": nx.shortest_path_length(G, "g6p_c", "succ_c"),
"without_currency": nx.shortest_path_length(H, "g6p_c", "succ_c")}
print("Most connected metabolites: " + ", ".join(
f"{m} ({k})" for m, k in degree[:10]))
for key, r in results.items():
if key.endswith("currency"):
print(f"{key.replace('_', ' ')}: {r['nodes']} metabolites, "
f"{r['edges']} edges, {r['components']} component(s); in the "
f"largest ({r['largest']}), mean path {r['mean_path']:.2f}, "
f"diameter {r['diameter']}")
print("A shortest path from glucose 6-phosphate to succinate:")
print(" with currency metabolites: " + " - ".join(
nx.shortest_path(G, "g6p_c", "succ_c")))
print(" without currency metabolites: " + " - ".join(
nx.shortest_path(H, "g6p_c", "succ_c")))
# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
top = degree[:15]
ax1.bar(range(15), [k for _, k in top],
color=["#D55E00" if m in currency else "#0072B2" for m, _ in top])
ax1.set_xticks(range(15), [m for m, _ in top], rotation=60, fontsize=8)
ax1.set_ylabel("Degree")
ax1.set_title("Most connected metabolites (vermillion: currency)")
for key, colour, label in (("with_currency", "#D55E00", "with currency"),
("without_currency", "#0072B2", "without")):
counts = results[key]["path_counts"]
ax2.plot(range(1, len(counts) + 1), counts / counts.sum(), "o-",
color=colour, label=label)
ax2.set_xlabel("Shortest path length")
ax2.set_ylabel("Fraction of pairs")
ax2.legend(frameon=False)
ax2.set_title("Path lengths in the largest component")
sbp.save_figure(fig, __file__, "fig-metabolic-graphs")
sbp.save_results(__file__, results)
sbp.show()
The most connected “metabolite” is the cytosolic proton, linked to 40 others, followed by water, protons outside the cell, and phosphate, which ties with pyruvate, a genuine hub of central metabolism; ADP, NADH, CO2 and ATP are not far behind (see the bar chart). Such currency metabolites take part in so many reactions that they connect almost everything to everything else. With them, the mean shortest path between two metabolites is just 2.4, and glucose 6-phosphate is two steps away from succinate, through a proton! Such a path makes no biochemical sense. Removing 21 currency metabolites makes the paths meaningful: glucose 6-phosphate now reaches succinate in five steps, for example through PEP, oxaloacetate, malate and fumarate, and the mean path length almost doubles, to 4.6. (Several paths are equally short, so the two languages may print different ones.) Note that the list of currency metabolites is a choice, and other reasonable choices give somewhat different numbers; this is one of the pitfalls discussed in §2.6.1.
2.6 Common challenges & troubleshooting
2.6.1 Choosing a representation
There is no code for this section; see the book.
2.6.2 Loading and creating graphs
There is no code for this section; see the book.
2.7 Software tools
There is no code for this section; see the book.