Skip to main content

4  Applications of network biology

Chapter 3 built networks and measured their structure. This chapter puts those measures to work on two questions. Are the most connected proteins in a cell the ones it cannot live without? And how does the shape of a contact network decide whether an infection spreads, and whom to vaccinate to stop it?

4.1 The centrality–lethality hypothesis

When Jeong and colleagues mapped the protein interaction network of yeast, they found that a protein’s chance of being essential rose with its degree: proteins with more than 15 partners were about three times as likely to be essential as those with five or fewer (Jeong et al. 2001). This centrality–lethality hypothesis has been tested and debated many times since, with different networks and different measures of centrality; across 20 organisms, essential genes have higher degree and betweenness than the network average (Raman et al. 2014) (book, §4.1).

Here we look at the E. coli K-12 protein network from the STRING database (Szklarczyk et al. 2023), keeping only the 32,244 high-confidence links (combined score of at least 700). For essentiality, we use NetGenes, which predicts essential genes in over 2700 bacteria with a machine-learning model trained on features of their STRING networks (Azhagesan et al. 2018) (book, §4.1.1); it lists 790 E. coli genes as essential. For each protein in the largest connected component, we compute three centralities from Chapter 3: degree, closeness and eigenvector centrality.

To measure how well a single centrality separates essential genes from the rest, we use the receiver operating characteristic (ROC) curve. Ranking the proteins by centrality and moving a threshold down the list, it plots the fraction of essential genes above the threshold against the fraction of other genes above it. The area under the curve (AUC) is the probability that a randomly chosen essential gene is more central than a randomly chosen non-essential one: 0.5 for a centrality that tells us nothing, 1 for one that separates the two groups perfectly.

Core MATLAB only.

%% Are central proteins more often essential?
% The E. coli K-12 protein interaction network from STRING (v12.0, links
% with a combined score of at least 700), and the genes that NetGenes
% predicts to be essential. We compute three centralities for each
% protein, see how the fraction of essential genes changes with degree, and
% measure how well each centrality alone separates essential from other
% genes.
% Requires: core MATLAB only.

data = sbp.data_dir();
links = readtable(fullfile(data, 'ecoli_string_ppi.csv'), ...
    'TextType', 'string');
proteins = readtable(fullfile(data, 'ecoli_string_proteins.csv'), ...
    'TextType', 'string');
netgenes = readtable(fullfile(data, 'ecoli_netgenes_essential.csv'), ...
    'TextType', 'string', 'Delimiter', ',');

G = graph(links.protein1, links.protein2);
[comp, sizes] = conncomp(G);
[~, largest] = max(sizes);
G = subgraph(G, comp == largest);
[nodes, order] = sort(G.Nodes.Name);       % a fixed order, as in Python
G = reordernodes(G, order);
is_ess = ismember(nodes, netgenes.string_id);
fprintf(['Largest connected component: %d proteins, %d interactions, ' ...
    '%d essential\n'], numnodes(G), numedges(G), nnz(is_ess));

names = {'degree', 'closeness', 'eigenvector'};
for c = 1:3
    cent.(names{c}) = centrality(G, names{c});
end
for c = 1:3
    aucs.(names{c}) = auc(cent.(names{c}), is_ess);
    fprintf('AUC of %s: %.4f\n', names{c}, aucs.(names{c}));
end

% Fraction essential in ten equal groups, from least to most connected
deg = cent.degree;
[~, order] = sort(deg);
n = numel(deg);
group_size = floor(n / 10) + ((1:10) <= mod(n, 10));
edges = [0 cumsum(group_size)];
frac_ess = zeros(1, 10); mean_deg = zeros(1, 10);
for g = 1:10
    idx = order(edges(g) + 1:edges(g + 1));
    frac_ess(g) = mean(is_ess(idx));
    mean_deg(g) = mean(deg(idx));
end
fprintf('Fraction essential by degree group:%s\n', ...
    sprintf(' %.3f', frac_ess));

[~, top] = sort(deg, 'descend');
top = top(1:10);
[~, where] = ismember(nodes(top), proteins.string_id);
top_names = proteins.name(where);
disp('Ten most connected proteins:');
for k = 1:10
    tag = '';
    if is_ess(top(k)), tag = '  essential'; end
    fprintf('  %-6s degree %d%s\n', top_names(k), deg(top(k)), tag);
end

%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
semilogx(mean_deg, frac_ess, 'o-', 'Color', [0.000 0.447 0.698], ...
    'MarkerFaceColor', [0.000 0.447 0.698]);
yline(mean(is_ess), ':', 'all proteins', 'Color', [0.6 0.6 0.6], ...
    'LineWidth', 1, 'LabelHorizontalAlignment', 'left');
xlim([1 100]); xticks([1 2 5 10 20 50 100]);
xlabel('Mean degree of the group'); ylabel('Fraction essential');
title('Ten groups of proteins, by degree');
box off
subplot(1, 2, 2)
colours = [0.000 0.447 0.698; 0.902 0.624 0.000; 0.000 0.620 0.451];
hold on
for c = 1:3
    x = cent.(names{c});
    thresholds = sort(unique(x), 'descend');
    tpr = arrayfun(@(t) mean(x(is_ess) >= t), thresholds);
    fpr = arrayfun(@(t) mean(x(~is_ess) >= t), thresholds);
    plot([0; fpr], [0; tpr], 'Color', colours(c, :), 'DisplayName', ...
        sprintf('%s (AUC %.2f)', names{c}, aucs.(names{c})));
end
plot([0 1], [0 1], ':', 'Color', [0.6 0.6 0.6], 'HandleVisibility', 'off');
xlabel('Fraction of other genes above threshold');
ylabel('Fraction of essential genes above threshold');
title('ROC curves');
legend('Location', 'southeast', 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-centrality-lethality');

results.n_nodes = numnodes(G);
results.n_edges = numedges(G);
results.n_essential = nnz(is_ess);
results.auc = aucs;
results.fraction_essential_by_degree = frac_ess;
results.top_degree = cellstr(top_names)';
sbp.save_results(mfilename('fullpath'), results);

%% Local function
function a = auc(score, positive)
% Area under the ROC curve: the probability that a randomly chosen
% positive scores higher than a randomly chosen negative (ties count one
% half), from the ranks of the scores.
[s, order] = sort(score);
ranks = zeros(size(score));
i = 1;
while i <= numel(s)                       % average ranks over ties
    j = i;
    while j < numel(s) && s(j + 1) == s(i)
        j = j + 1;
    end
    ranks(order(i:j)) = (i + j) / 2;
    i = j + 1;
end
n_pos = nnz(positive); n_neg = nnz(~positive);
a = (sum(ranks(positive)) - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg);
end

Needs NetworkX.

"""Are central proteins more often essential?

The E. coli K-12 protein interaction network from STRING (v12.0, links
with a combined score of at least 700), and the genes that NetGenes
predicts to be essential. We compute three centralities for each protein,
see how the fraction of essential genes changes with degree, and measure
how well each centrality alone separates essential from other genes.
"""
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import sbp

edges = np.loadtxt(sbp.DATA / "ecoli_string_ppi.csv", delimiter=",",
                   skiprows=1, usecols=(0, 1), dtype=str)
names = dict(np.loadtxt(sbp.DATA / "ecoli_string_proteins.csv",
                        delimiter=",", skiprows=1, usecols=(0, 1), dtype=str))
essential = set(np.loadtxt(sbp.DATA / "ecoli_netgenes_essential.csv",
                           delimiter=",", skiprows=1, usecols=0, dtype=str))

G = nx.Graph()
G.add_edges_from(edges)
G = G.subgraph(max(nx.connected_components(G), key=len)).copy()
nodes = sorted(G.nodes)                 # a fixed order, as in MATLAB
is_ess = np.array([v in essential for v in nodes])
print(f"Largest connected component: {len(nodes)} proteins, "
      f"{G.number_of_edges()} interactions, {is_ess.sum()} essential")

cc = nx.closeness_centrality(G)
ec = nx.eigenvector_centrality_numpy(G)
centrality = {
    "degree": np.array([G.degree(v) for v in nodes], dtype=float),
    "closeness": np.array([cc[v] for v in nodes]),
    "eigenvector": np.array([ec[v] for v in nodes]),
}


def auc(score, positive):
    """Area under the ROC curve: the probability that a randomly chosen
    positive scores higher than a randomly chosen negative (ties count
    one half), from the ranks of the scores."""
    order = np.argsort(score, kind="stable")
    ranks = np.empty(len(score))
    s = score[order]
    i = 0
    while i < len(s):                     # average ranks over ties
        j = i
        while j + 1 < len(s) and s[j + 1] == s[i]:
            j += 1
        ranks[order[i:j + 1]] = (i + j) / 2 + 1
        i = j + 1
    n_pos, n_neg = positive.sum(), (~positive).sum()
    return (ranks[positive].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)


aucs = {name: auc(c, is_ess) for name, c in centrality.items()}
for name, a in aucs.items():
    print(f"AUC of {name}: {a:.4f}")

# Fraction essential in ten equal groups, from least to most connected
order = np.argsort(centrality["degree"], kind="stable")
groups = np.array_split(order, 10)
frac_ess = np.array([is_ess[g].mean() for g in groups])
mean_deg = np.array([centrality["degree"][g].mean() for g in groups])
print("Fraction essential by degree group:", np.round(frac_ess, 3))

top = np.argsort(-centrality["degree"], kind="stable")[:10]
print("Ten most connected proteins:")
for i in top:
    print(f"  {names[nodes[i]]:6s} degree {centrality['degree'][i]:.0f}"
          f"{'  essential' if is_ess[i] else ''}")

# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot(mean_deg, frac_ess, "o-", color="#0072B2")
ax1.axhline(is_ess.mean(), color="#999999", ls=":", lw=1)
ax1.text(1.1, is_ess.mean() + 0.01, "all proteins", color="#666666",
         fontsize=9)
ax1.set_xscale("log")
ax1.set_xticks([1, 2, 5, 10, 20, 50, 100], labels=["1", "2", "5", "10",
                                                  "20", "50", "100"])
ax1.minorticks_off()
ax1.set_xlabel("Mean degree of the group")
ax1.set_ylabel("Fraction essential")
ax1.set_title("Ten groups of proteins, by degree")
for name, colour in [("degree", "#0072B2"), ("closeness", "#E69F00"),
                     ("eigenvector", "#009E73")]:
    c = centrality[name]
    thresholds = np.sort(np.unique(c))[::-1]
    tpr = [(c[is_ess] >= t).mean() for t in thresholds]
    fpr = [(c[~is_ess] >= t).mean() for t in thresholds]
    ax2.plot([0] + fpr, [0] + tpr, color=colour,
             label=f"{name} (AUC {aucs[name]:.2f})")
ax2.plot([0, 1], [0, 1], ":", color="#999999")
ax2.set_xlabel("Fraction of other genes above threshold")
ax2.set_ylabel("Fraction of essential genes above threshold")
ax2.set_title("ROC curves")
ax2.legend(frameon=False, loc="lower right")
sbp.save_figure(fig, __file__, "fig-centrality-lethality")

sbp.save_results(__file__, {
    "n_nodes": len(nodes), "n_edges": G.number_of_edges(),
    "n_essential": int(is_ess.sum()), "auc": aucs,
    "fraction_essential_by_degree": frac_ess,
    "top_degree": [names[nodes[i]] for i in top],
})
sbp.show()

The relationship is striking. In the tenth of proteins with the fewest links, fewer than 1% are predicted essential; in the most connected tenth, 43% are, against 20% overall. Degree alone separates essential from other genes with an AUC of 0.77, a little better than closeness (0.74) and eigenvector centrality (0.69).

Two cautions are in order. First, the essential genes here are predictions, made from network features of this very network, degree among them, so some of the association is built in. The fair test uses essentiality measured in experiments, such as the Keio collection of single-gene knock-outs (Baba et al. 2006) (Exercise 1). Second, the most connected proteins are almost all ribosomal proteins and subunits of RNA polymerase, which interact densely with one another. They are among the best-known essential genes of E. coli, yet NetGenes predicts only three of the top ten to be essential: whatever the model learnt, it is more than “hubs are essential”, and, like every prediction, it can be wrong.

4.1.1 Predicting essential genes using network measures

In a sense, the example above already does this: NetGenes predicts essential genes from features of the STRING network. Remember the two cautions above when reading its results; Exercise 1 tests the centralities against essentiality measured in experiments instead.

4.2 Networks and modules in disease

4.2.1 Disease networks

There is no code for this section; see the book.

4.2.2 Identification of disease modules

There is no code for this section; see the book.

4.2.3 Edgetic perturbation models

There is no code for this section; see the book.

4.3 Differential network analysis

Co-expression networks need many samples per condition, and PRECISE-1K (Lamoureux et al. 2023) provides them: 200 RNA-seq profiles of wild-type E. coli grown on glucose, and 108 grown on glycerol, all in minimal medium at 37 °C. We take 44 genes of central carbon and glycerol metabolism, compute the correlation of every pair of genes in each condition, and test each pair for a difference, using Fisher’s \(z\)-transformation. With 946 pairs, we use a Bonferroni-corrected threshold. The genes with the most differentially co-expressed partners are the most “rewired” between the two conditions.

Core MATLAB only.

%% Differential co-expression: how gene-gene correlations change between
% two conditions.
% The data are RNA-seq profiles from PRECISE-1K (Lamoureux et al., 2023) of
% wild-type E. coli grown on glucose (200 samples) or glycerol (108
% samples), for 44 genes of central carbon and glycerol metabolism. For
% each condition we compute the Pearson correlation of every pair of genes
% (a co-expression network), and test whether the correlation differs
% between the conditions, using Fisher's z-transformation (book §4.3):
%     z = (atanh r1 - atanh r2) / sqrt(1/(n1 - 3) + 1/(n2 - 3)).
% A pair is differentially co-expressed if |z| exceeds the Bonferroni
% threshold for all 946 pairs (overall significance 0.05). The genes with
% the most differential partners are the most "rewired".

expr = readtable(fullfile(sbp.data_dir(), 'precise1k_carbon_log_tpm.csv'), ...
    'ReadRowNames', true, 'VariableNamingRule', 'preserve');
samples = readtable(fullfile(sbp.data_dir(), ...
    'precise1k_carbon_samples.csv'), 'TextType', 'string');
genes = expr.Properties.RowNames';
g = numel(genes);

carbons = {'glucose', 'glycerol'};
for c = 1:2
    columns = cellstr(samples.sample(samples.carbon_source == carbons{c}));
    X = expr{:, columns};                         % genes x samples
    r.(carbons{c}) = corrcoef(X');                % correlations of genes
    n.(carbons{c}) = numel(columns);
end

% Fisher's z (the diagonal, r = 1, is not used, so we set it to 0)
f1 = atanh(r.glucose - diag(diag(r.glucose)));
f2 = atanh(r.glycerol - diag(diag(r.glycerol)));
z = (f1 - f2) / sqrt(1 / (n.glucose - 3) + 1 / (n.glycerol - 3));
pairs = g * (g - 1) / 2;
threshold = sqrt(2) * erfcinv(0.05 / pairs);      % two-sided, Bonferroni
upper = triu(true(g), 1);
differential = abs(z) > threshold & upper;
rewired = sum(differential | differential', 2)';

[i, j] = find(upper);
[~, order] = sort(-abs(z(upper)));                % stable
[~, most] = sortrows(table(-rewired', string(genes')));  % ties: alphabetical
most = most(1:8)';

fprintf('%d gene pairs; |z| > %.2f for %d of them\n', pairs, threshold, ...
    sum(differential, 'all'));
fprintf('Largest changes in correlation (glucose -> glycerol):\n');
for k = order(1:8)'
    fprintf('  %-5s %-5s  %+.2f -> %+.2f\n', genes{i(k)}, genes{j(k)}, ...
        r.glucose(i(k), j(k)), r.glycerol(i(k), j(k)));
end
fprintf('Most rewired genes: %s\n', strjoin(compose('%s (%d)', ...
    string(genes(most)'), rewired(most)'), ', '));

%% Plot: the two correlation matrices
fig = figure('Position', [100 100 1300 650]);
tiledlayout(1, 2, 'TileSpacing', 'compact');
for c = 1:2
    nexttile
    imagesc(r.(carbons{c}), [-1, 1]); axis image
    colormap(sbp.colormap('RdBu_r'));
    set(gca, 'XTick', 1:g, 'XTickLabel', genes, 'YTick', 1:g, ...
        'YTickLabel', genes, 'FontSize', 7);
    xtickangle(90);
    title(sprintf('%s (%d samples)', carbons{c}, n.(carbons{c})), ...
        'FontSize', 11);
end
cb = colorbar('FontSize', 10); cb.Layout.Tile = 'east';
cb.Label.String = 'Pearson r';
sbp.save_figure(fig, mfilename('fullpath'), 'fig-differential-network');

results.genes = genes;
results.n = n;
results.threshold = threshold;
results.r_glucose = r.glucose;
results.r_glycerol = r.glycerol;
results.differential = sum(differential, 'all');
results.rewired = rewired;
results.most_rewired = genes(most);
sbp.save_results(mfilename('fullpath'), results);

Needs SciPy.

"""Differential co-expression: how gene-gene correlations change between
two conditions.

The data are RNA-seq profiles from PRECISE-1K (Lamoureux et al., 2023) of
wild-type E. coli grown on glucose (200 samples) or glycerol (108
samples), for 44 genes of central carbon and glycerol metabolism. For
each condition we compute the Pearson correlation of every pair of genes
(a co-expression network), and test whether the correlation differs
between the conditions, using Fisher's z-transformation (book §4.3):
    z = (atanh r1 - atanh r2) / sqrt(1/(n1 - 3) + 1/(n2 - 3)).
A pair is differentially co-expressed if |z| exceeds the Bonferroni
threshold for all 946 pairs (overall significance 0.05). The genes with
the most differential partners are the most "rewired".
"""
import numpy as np
import pandas as pd
from scipy.special import erfcinv
import matplotlib.pyplot as plt
import sbp

expr = pd.read_csv(sbp.DATA / "precise1k_carbon_log_tpm.csv", index_col=0)
samples = pd.read_csv(sbp.DATA / "precise1k_carbon_samples.csv")
genes = list(expr.index)
g = len(genes)

r, n = {}, {}
for carbon in ("glucose", "glycerol"):
    columns = samples.loc[samples["carbon_source"] == carbon, "sample"]
    r[carbon] = np.corrcoef(expr[columns].to_numpy())
    n[carbon] = len(columns)

# Fisher's z (the diagonal, r = 1, is not used, so we set it to 0)
fisher = {c: np.arctanh(m - np.diag(np.diag(m))) for c, m in r.items()}
z = ((fisher["glucose"] - fisher["glycerol"])
     / np.sqrt(1 / (n["glucose"] - 3) + 1 / (n["glycerol"] - 3)))
pairs = g * (g - 1) // 2
threshold = np.sqrt(2) * erfcinv(0.05 / pairs)   # two-sided, Bonferroni
upper = np.triu(np.ones((g, g), dtype=bool), 1)
differential = (np.abs(z) > threshold) & upper
rewired = (differential | differential.T).sum(axis=1)

order = np.argsort(-np.abs(z[upper]), kind="stable")
i, j = np.nonzero(upper)
top = [(genes[i[k]], genes[j[k]], r["glucose"][i[k], j[k]],
        r["glycerol"][i[k], j[k]]) for k in order[:8]]
most = np.lexsort((genes, -rewired))[:8]           # ties: alphabetical

print(f"{pairs} gene pairs; |z| > {threshold:.2f} for {differential.sum()} "
      "of them")
print("Largest changes in correlation (glucose -> glycerol):")
for a, b, r1, r2 in top:
    print(f"  {a:5s} {b:5s}  {r1:+.2f} -> {r2:+.2f}")
print("Most rewired genes: " + ", ".join(
    f"{genes[k]} ({rewired[k]})" for k in most))

# --- Plot: the two correlation matrices
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(13, 6.5), layout="constrained")
for ax, carbon in zip(axes, ("glucose", "glycerol")):
    im = ax.imshow(r[carbon], cmap="RdBu_r", vmin=-1, vmax=1)
    ax.set_xticks(range(g), genes, rotation=90, fontsize=7)
    ax.set_yticks(range(g), genes, fontsize=7)
    ax.set_title(f"{carbon} ({n[carbon]} samples)")
fig.colorbar(im, ax=axes, shrink=0.6, label="Pearson r")
sbp.save_figure(fig, __file__, "fig-differential-network")

sbp.save_results(__file__, {
    "genes": genes, "n": n, "threshold": threshold,
    "r_glucose": r["glucose"], "r_glycerol": r["glycerol"],
    "differential": int(differential.sum()), "rewired": rewired,
    "most_rewired": [genes[k] for k in most],
})
sbp.show()

The largest changes make good biological sense. On glycerol, the genes of the GlpR regulon are induced, and they rise and fall together: the correlation between glpT and glpQ, which share an operon, goes from 0.33 on glucose (where the regulon is repressed and its expression mostly noise) to 0.97. The glyoxylate shunt genes, aceA, aceB and aceK, are among the most rewired. Note, however, that 312 of the 946 pairs differ significantly, a third of all pairs. Part of this reflects biology, but part reflects the samples themselves: the glycerol samples come from only 3 studies, and the glucose samples from 26, with different strains, perturbations and protocols. Differences in correlation can arise from such differences in the experimental design, as much as from the condition being compared, and this is one of the main pitfalls of differential network analysis.

4.4 Disease spreading on networks

The SIR model of Chapter 1 assumes that everyone meets everyone else equally often. On a network, an infected person can infect only their contacts.

4.4.1 Percolation-based models

A simple version of the SIR model on a network gives each infected person one chance to infect each of their contacts, with probability \(T\), the transmissibility, before recovering. For a network in which the degrees of neighbours are uncorrelated, a large outbreak is possible only if

\[ T > T_c = \frac{\langle k \rangle}{\langle k^2 \rangle - \langle k \rangle}, \]

where \(\langle k \rangle\) and \(\langle k^2 \rangle\) are the mean degree and the mean squared degree (Newman 2002). This result comes from viewing the epidemic as a percolation process: keep each link of the network with probability \(T\), and an outbreak reaches everyone in the connected cluster of its first case (book, §4.4.1). For an Erdős–Rényi network, \(\langle k^2 \rangle - \langle k \rangle = \langle k \rangle^2\), so \(T_c = 1/\langle k \rangle\). In a scale-free network, the hubs make \(\langle k^2 \rangle\) large, and so the threshold small; in an infinitely large scale-free network, it disappears altogether (Pastor-Satorras and Vespignani 2001).

Let us simulate epidemics on Erdős–Rényi and scale-free networks of 2000 people, each with four contacts on average, starting each from one randomly chosen person. We then vaccinate 10% of the scale-free network, either at random or by choosing the people with the most contacts, and repeat the epidemic.

Core MATLAB only.

%% Epidemics on networks, and vaccinating the hubs
% An SIR epidemic on a contact network: each infected person infects each
% susceptible contact with probability T (the transmissibility) and then
% recovers. We compare Erdős–Rényi and preferential-attachment (scale-free)
% networks with the same mean degree, 4, and then compare two ways of
% vaccinating 10% of the scale-free network: at random, or the people with
% the most contacts.
% Requires: core MATLAB only.

n = 2000; m = 2;
n_networks = 10; n_seeds = 50;
T_values = round(0:0.05:0.6, 10);
rng(1);

size_er = zeros(size(T_values)); size_ba = zeros(size(T_values));
Tc_er = zeros(1, n_networks); Tc_ba = zeros(1, n_networks);
for r = 1:n_networks
    ba = neighbour_lists(barabasi_albert(n, m), n);
    er = neighbour_lists(erdos_renyi(n, 2 * m), n);
    Tc_ba(r) = threshold(ba);
    Tc_er(r) = threshold(er);
    for t = 1:numel(T_values)
        for seed = randi(n, 1, n_seeds)
            size_ba(t) = size_ba(t) + outbreak(ba, T_values(t), seed, []) / n;
        end
        for seed = randi(n, 1, n_seeds)
            size_er(t) = size_er(t) + outbreak(er, T_values(t), seed, []) / n;
        end
    end
end
size_er = size_er / (n_networks * n_seeds);
size_ba = size_ba / (n_networks * n_seeds);
Tc = struct('er', mean(Tc_er), 'ba', mean(Tc_ba));
fprintf(['Epidemic threshold <k>/(<k^2> - <k>): Erdős–Rényi %.4f, ' ...
    'scale-free %.4f\n'], Tc.er, Tc.ba);
for t = [4 7 11]
    fprintf(['T = %.2f: mean fraction infected, Erdős–Rényi %.4f, ' ...
        'scale-free %.4f\n'], T_values(t), size_er(t), size_ba(t));
end

%% Vaccination of 10% of a scale-free network, with T = 0.5
T_vacc = 0.5; n_vacc = n / 10;
strategies = {'none', 'random', 'hubs'};
vacc = struct('none', [], 'random', [], 'hubs', []);
for r = 1:n_networks
    nbrs = neighbour_lists(barabasi_albert(n, m), n);
    degree = cellfun(@numel, nbrs);
    [~, by_degree] = sort(degree, 'descend');
    choices = {[], randperm(n, n_vacc), by_degree(1:n_vacc)};
    for s = 1:3
        others = setdiff(1:n, choices{s});
        for seed = others(randi(numel(others), 1, n_seeds))
            vacc.(strategies{s})(end + 1) = ...
                outbreak(nbrs, T_vacc, seed, choices{s}) / n;
        end
    end
end
for s = 1:3
    vacc.(strategies{s}) = mean(vacc.(strategies{s}));
end
fprintf(['Vaccinating 10%% at T = %g: mean fraction infected %.4f ' ...
    '(no vaccination), %.4f (random), %.4f (hubs)\n'], T_vacc, ...
    vacc.none, vacc.random, vacc.hubs);

%% Plot
blue = [0.000 0.447 0.698]; orange = [0.902 0.624 0.000];
sky_blue = [0.337 0.706 0.914];
fig = figure('Position', [100 100 1000 400]);
subplot(1, 5, 1:3)
plot(T_values, size_er, 's-', 'Color', orange, 'MarkerFaceColor', orange);
hold on
plot(T_values, size_ba, 'o-', 'Color', blue, 'MarkerFaceColor', blue);
xline(Tc.er, 'LineStyle', ':', 'Color', orange, 'LineWidth', 1);
xline(Tc.ba, 'LineStyle', ':', 'Color', blue, 'LineWidth', 1);
xlabel('Transmissibility T'); ylabel('Mean fraction infected');
title('Epidemic size (dotted: thresholds)');
legend({'Erdős–Rényi', 'scale-free'}, 'Location', 'southeast', ...
    'Box', 'off');
subplot(1, 5, 4:5)
labels = ["none", "random\newline10%", ...
    "top 10%\newlineby degree"];   % \newline: two-line label
b = bar([vacc.none vacc.random vacc.hubs], 'FaceColor', 'flat', ...
    'EdgeColor', 'none');
b.CData = [0.6 0.6 0.6; sky_blue; blue];
xticks(1:3); xticklabels(labels); xtickangle(0);
ylabel('Mean fraction infected'); xlabel('Who is vaccinated');
title(sprintf('Vaccination, scale-free, T = %g', T_vacc));
sbp.save_figure(fig, mfilename('fullpath'), 'fig-epidemic-networks');

high = T_values >= 0.4;     % well above both thresholds
results.threshold = Tc;
results.T = T_values;
results.size_er = size_er;
results.size_ba = size_ba;
results.size_er_high_T = size_er(high);
results.size_ba_high_T = size_ba(high);
results.vaccination = vacc;
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function edges = barabasi_albert(n, m)
% Preferential attachment, as in the networks chapter (nodes from 1).
n_edges = m * (m + 1) / 2 + m * (n - m - 1);
edges = zeros(n_edges, 2);
e = 0;
for i = 1:m + 1                            % start from a clique
    for j = 1:i - 1
        e = e + 1;
        edges(e, :) = [i j];
    end
end
ends = [reshape(edges(1:e, :)', 1, []), zeros(1, 2 * (n_edges - e))];
n_ends = 2 * e;
for new = m + 2:n
    targets = [];
    while numel(targets) < m
        t = ends(randi(n_ends));
        if ~ismember(t, targets)
            targets(end + 1) = t; %#ok<AGROW>
        end
    end
    for t = targets
        e = e + 1;
        edges(e, :) = [new t];
        ends(n_ends + 1:n_ends + 2) = [new t];
        n_ends = n_ends + 2;
    end
end
end

function edges = erdos_renyi(n, mean_k)
[i, j] = find(triu(rand(n) < mean_k / (n - 1), 1));
edges = [i j];
end

function nbrs = neighbour_lists(edges, n)
A = sparse(edges(:, 1), edges(:, 2), 1, n, n);
A = A + A';
nbrs = cell(1, n);
for i = 1:n
    nbrs{i} = find(A(:, i))';
end
end

function total = outbreak(nbrs, T, seed, immune)
% Final number of people infected, starting from one person. Each newly
% infected person gets one chance to infect each contact.
state = false(1, numel(nbrs));            % ever infected (or immune)
state(immune) = true;
state(seed) = true;
current = seed; total = 1;
while ~isempty(current)
    new = [];
    for i = current
        contacts = nbrs{i}(rand(1, numel(nbrs{i})) < T);
        for j = contacts
            if ~state(j)
                state(j) = true;
                new(end + 1) = j; %#ok<AGROW>
            end
        end
    end
    total = total + numel(new);
    current = new;
end
end

function Tc = threshold(nbrs)
% Epidemic threshold T_c = <k> / (<k^2> - <k>).
k = cellfun(@numel, nbrs);
Tc = mean(k) / (mean(k.^2) - mean(k));
end

Needs NumPy.

"""Epidemics on networks, and vaccinating the hubs.

An SIR epidemic on a contact network: each infected person infects each
susceptible contact with probability T (the transmissibility) and then
recovers. We compare Erdős–Rényi and preferential-attachment (scale-free)
networks with the same mean degree, 4, and then compare two ways of
vaccinating 10% of the scale-free network: at random, or the people with
the most contacts.
"""
import numpy as np
import matplotlib.pyplot as plt
import sbp

n, m = 2000, 2
n_networks, n_seeds = 10, 50
T_values = np.round(np.arange(0, 0.6001, 0.05), 10)
rng = np.random.default_rng(1)


def barabasi_albert(n, m):
    """Preferential attachment, as in the networks chapter."""
    edges = [(i, j) for i in range(m + 1) for j in range(i)]
    ends = [v for e in edges for v in e]
    for new in range(m + 1, n):
        targets = set()
        while len(targets) < m:
            targets.add(ends[rng.integers(len(ends))])
        for t in targets:
            edges.append((new, t))
            ends += [new, t]
    return np.array(edges)


def erdos_renyi(n, mean_k):
    upper = np.triu(rng.random((n, n)) < mean_k / (n - 1), 1)
    return np.argwhere(upper)


def neighbour_lists(edges, n):
    nbrs = [[] for _ in range(n)]
    for a, b in edges:
        nbrs[a].append(b)
        nbrs[b].append(a)
    return [np.array(x, dtype=int) for x in nbrs]


def outbreak(nbrs, T, seed, immune=None):
    """Final number of people infected, starting from one person. Each
    newly infected person gets one chance to infect each contact."""
    state = np.zeros(len(nbrs), dtype=bool)        # ever infected (or immune)
    if immune is not None:
        state[immune] = True
    state[seed] = True
    current, total = [seed], 1
    while current:
        new = []
        for i in current:
            for j in nbrs[i][rng.random(len(nbrs[i])) < T]:
                if not state[j]:
                    state[j] = True
                    new.append(j)
        total += len(new)
        current = new
    return total


def threshold(nbrs):
    """Epidemic threshold T_c = <k> / (<k^2> - <k>)."""
    k = np.array([len(x) for x in nbrs], dtype=float)
    return k.mean() / ((k ** 2).mean() - k.mean())


size = {"er": np.zeros(len(T_values)), "ba": np.zeros(len(T_values))}
Tc = {"er": [], "ba": []}
for _ in range(n_networks):
    networks = {"ba": neighbour_lists(barabasi_albert(n, m), n),
                "er": neighbour_lists(erdos_renyi(n, 2 * m), n)}
    for name, nbrs in networks.items():
        Tc[name].append(threshold(nbrs))
        for t, T in enumerate(T_values):
            for seed in rng.integers(n, size=n_seeds):
                size[name][t] += outbreak(nbrs, T, seed) / n
for name in size:
    size[name] /= n_networks * n_seeds
    Tc[name] = float(np.mean(Tc[name]))
print(f"Epidemic threshold <k>/(<k^2> - <k>): Erdős–Rényi {Tc['er']:.4f}, "
      f"scale-free {Tc['ba']:.4f}")
for t in [3, 6, 10]:
    print(f"T = {T_values[t]:.2f}: mean fraction infected, Erdős–Rényi "
          f"{size['er'][t]:.4f}, scale-free {size['ba'][t]:.4f}")

# --- Vaccination of 10% of a scale-free network, with T = 0.5
T_vacc, n_vacc = 0.5, n // 10
vacc = {"none": [], "random": [], "hubs": []}
for _ in range(n_networks):
    nbrs = neighbour_lists(barabasi_albert(n, m), n)
    degree = np.array([len(x) for x in nbrs])
    choices = {"none": np.array([], dtype=int),
               "random": rng.choice(n, n_vacc, replace=False),
               "hubs": np.argsort(-degree, kind="stable")[:n_vacc]}
    for name, immune in choices.items():
        others = np.setdiff1d(np.arange(n), immune)
        for seed in rng.choice(others, n_seeds):
            vacc[name].append(outbreak(nbrs, T_vacc, seed, immune) / n)
vacc = {name: float(np.mean(v)) for name, v in vacc.items()}
print(f"Vaccinating 10% at T = {T_vacc}: mean fraction infected "
      f"{vacc['none']:.4f} (no vaccination), {vacc['random']:.4f} "
      f"(random), {vacc['hubs']:.4f} (hubs)")

# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
                               gridspec_kw={"width_ratios": [3, 2]})
ax1.plot(T_values, size["er"], "s-", color="#E69F00", label="Erdős–Rényi")
ax1.plot(T_values, size["ba"], "o-", color="#0072B2", label="scale-free")
for name, colour in [("er", "#E69F00"), ("ba", "#0072B2")]:
    ax1.axvline(Tc[name], color=colour, ls=":", lw=1)
ax1.set_xlabel("Transmissibility T")
ax1.set_ylabel("Mean fraction infected")
ax1.set_title("Epidemic size (dotted: thresholds)")
ax1.legend(loc="lower right", frameon=False)
labels = ["none", "random\n10%", "top 10%\nby degree"]
ax2.bar(labels, [vacc["none"], vacc["random"], vacc["hubs"]],
        color=["#999999", "#56B4E9", "#0072B2"])
ax2.set_ylabel("Mean fraction infected")
ax2.set_title(f"Vaccination, scale-free, T = {T_vacc}")
ax2.set_xlabel("Who is vaccinated")
sbp.save_figure(fig, __file__, "fig-epidemic-networks")

high = T_values >= 0.4      # well above both thresholds
sbp.save_results(__file__, {
    "threshold": Tc, "T": T_values, "size_er": size["er"],
    "size_ba": size["ba"], "size_er_high_T": size["er"][high],
    "size_ba_high_T": size["ba"][high], "vaccination": vacc,
})
sbp.show()

The threshold for the Erdős–Rényi network is 0.25, as expected, but for the scale-free network it is only about 0.09. Between the two, an infection that would die out among people with similar numbers of contacts spreads on the scale-free network, reaching hubs, which pass it on widely: at \(T = 0.3\), it infects on average 18 to 19% of the scale-free network (the two languages differ slightly), against 9% of the Erdős–Rényi one. Well above both thresholds, the two networks fare much alike.

Vaccination shows the other side of the hubs. Vaccinating a random 10% of people reduces the average epidemic only from about 60% to 43–45% of the population, but vaccinating the 10% with the most contacts stops it almost completely. Removing the hubs breaks the network into pieces too small to sustain an epidemic, just as targeted attacks on hubs fragment scale-free networks far faster than random failures do (book §3.5.2; Exercise 3 of Chapter 3). Finding the hubs of a real contact network is hard, but there is a clever shortcut: vaccinate a random contact of a randomly chosen person, who is more likely to be a hub than the person is (Exercise 5).

The centrality–lethality and epidemic examples are related. In each, a few highly connected nodes matter far more than their numbers suggest, whether for the survival of the cell or for the spread of an infection.

4.4.2 Agent-based simulations

There is no code for this section; see the book.

4.5 Molecular graphs and their applications

4.5.1 Retrosynthesis

There is no code for this section; see the book.

4.6 Protein structure and conformational networks

4.6.1 Protein folding pathways

There is no code for this section; see the book.

Exercises

  1. Download the list of genes found to be essential in the Keio collection (Baba et al. 2006), map them to STRING identifiers, and repeat the centrality–lethality analysis. Is the AUC of degree higher or lower than for the NetGenes predictions? Which hubs are essential?
  2. Add betweenness centrality to the comparison (centrality(G, 'betweenness') in MATLAB, nx.betweenness_centrality in NetworkX; the latter takes a minute or two for this network). Do proteins with high betweenness but low degree, the bottlenecks of the network, tend to be essential?
  3. Repeat the centrality–lethality analysis for another organism from NetGenes, using its STRING network. Does the relationship hold?
  4. Book Exercise 4.3: plot the degree distributions of essential and other proteins, and see how they change when the STRING score cut-off is raised from 700 to 900 (tools/fetch_string.py makes the network; change its cut-off).
  5. In the epidemic example, vaccinate 10% of people by choosing a person at random and vaccinating one of their contacts, chosen at random. Compare this acquaintance immunisation with random and hub vaccination. Why does it work?
  6. Compute \(T_c\) for scale-free networks of 500, 2000 and 8000 nodes with \(m = 2\). How does it change with the size of the network?

Going further

Network ideas reach well beyond the examples of this chapter, to disease modules in human interaction networks (§4.2), molecular graphs and retrosynthesis (§4.5) and protein folding networks (§4.6) in book Chapter 4. For epidemics, agent-based simulations on realistic contact networks, such as EpiSims, add time and the movement of people (book, §4.4.2).