Skip to main content

3  Structure of networks

How do we describe the structure of a network, and what does that structure tell us? In this chapter, we compute the standard network parameters for a small example, and then generate the three classic network models, random, small-world and scale-free, to see how they differ. We then look at real networks: the E. coli STRING network, to measure assortativity and to see how it falls apart when its nodes are removed, a classic social network, to find communities, and the transcriptional regulatory network of E. coli, to find motifs. Throughout, we shall compare real networks with randomised versions of themselves, which is often the only way to tell whether a property is remarkable.

3.1 Network parameters

Most network parameters follow directly from the adjacency matrix (§2.4.2):

  • the degree \(k_i = \sum_j a_{ij}\), the number of neighbours of node \(i\) (book, Eq. 3.1);
  • the clustering coefficient \(C_i\), the fraction of pairs of neighbours of \(i\) that are themselves joined. Because \((\mathbf{A}^3)_{ii}\) counts the closed walks of length three from \(i\), which is twice the number of triangles through \(i\), \(C_i = (\mathbf{A}^3)_{ii} / k_i(k_i - 1)\) (book, Eqs. 3.6 and 3.7);
  • the shortest-path length \(d_{ij}\) between every pair of nodes, from which follow the diameter (the largest \(d_{ij}\)) and the characteristic path length (the mean \(d_{ij}\) over all pairs) (book, Eqs. 3.11 and 3.12);
  • two measures of how central a node is: closeness, \((n-1)/\sum_j d_{ij}\), the reciprocal of the mean distance to all other nodes (Eq. 3.14), and betweenness (Eq. 3.18), the number of shortest paths between other pairs of nodes that pass through the node (a path shared by several equally short alternatives counts fractionally).

Our example is a small network of ten proteins, two tightly knit groups joined through protein E.

Core MATLAB only.

%% Basic network parameters for a small undirected network
% Ten proteins, A to J, in two tightly knit groups joined through E.
% We compute degrees, clustering coefficients, shortest-path lengths and
% two centrality measures, using the definitions in the book (Ch. 3).
% Requires: core MATLAB only (graph objects, R2015b or newer).

nodes = cellstr(('A':'J')');
edges = {'A' 'B'; 'A' 'C'; 'A' 'D'; 'B' 'C'; 'B' 'D'; 'C' 'D'; 'D' 'E';
         'E' 'F'; 'F' 'G'; 'F' 'H'; 'G' 'H'; 'G' 'I'; 'H' 'I'; 'I' 'J'};
G = graph(edges(:, 1), edges(:, 2));
G = reordernodes(G, nodes);   % keep nodes in the order A, B, ..., J
n = numnodes(G);

% Adjacency matrix and degrees (book Eq. 3.1)
A = full(adjacency(G));
deg = sum(A, 2);

% Clustering coefficient (Eq. 3.6): the fraction of pairs of neighbours
% that are themselves connected; (A^3)_ii counts each triangle twice
triangles = diag(A^3) / 2;
pairs = deg .* (deg - 1) / 2;
clustering = zeros(n, 1);
clustering(pairs > 0) = triangles(pairs > 0) ./ pairs(pairs > 0);

% Shortest-path lengths between all pairs of nodes
D = distances(G);
diameter = max(D(:));                                  % Eq. 3.11
char_path_length = mean(D(triu(true(n), 1)));          % Eq. 3.12
closeness = (n - 1) ./ sum(D, 2);                      % Eq. 3.14

% Betweenness centrality (Eq. 3.18), counting each pair of nodes once
betweenness = centrality(G, 'betweenness');

fprintf('%d nodes, %d edges, mean degree %.2f\n', n, numedges(G), ...
    mean(deg));
fprintf(['mean clustering coefficient %.4f, diameter %g, ' ...
    'characteristic path length %.4f\n'], mean(clustering), diameter, ...
    char_path_length);
fprintf('node  degree  clustering  closeness  betweenness\n');
for i = 1:n
    fprintf('  %s   %4g    %8.3f   %8.3f   %9.2f\n', nodes{i}, deg(i), ...
        clustering(i), closeness(i), betweenness(i));
end

%% Plot: node size by degree, colour by betweenness, fixed positions
x = [0 1 0 1 2 3 4 3 4 5];
y = [1 1 0 0 0.5 0.5 1 0 0 0];
fig = figure('Position', [100 100 700 320]);
hold on
for e = 1:size(edges, 1)
    i = find(strcmp(nodes, edges{e, 1}));
    j = find(strcmp(nodes, edges{e, 2}));
    plot([x(i) x(j)], [y(i) y(j)], '-', 'Color', [0.6 0.6 0.6]);
end
scatter(x, y, 150 * deg, betweenness, 'filled', 'MarkerEdgeColor', 'k');
text(x, y + 0.12 + 0.03 * deg', nodes, 'HorizontalAlignment', 'center', ...
    'BackgroundColor', 'white', 'Margin', 1);
colormap(sbp.colormap('viridis_r'));
cb = colorbar('Ticks', 0:5:20);
cb.Label.String = 'Betweenness centrality';
title('Node size: degree; colour: betweenness');
axis off
ylim([-0.4 1.6]);
sbp.save_figure(fig, mfilename('fullpath'), 'fig-graph-basics');

results.degree = deg';
results.clustering = clustering';
results.mean_clustering = mean(clustering);
results.diameter = diameter;
results.char_path_length = char_path_length;
results.closeness = closeness';
results.betweenness = betweenness';
sbp.save_results(mfilename('fullpath'), results);

Needs NetworkX.

"""Basic network parameters for a small undirected network.

Ten proteins, A to J, in two tightly knit groups joined through E.
We compute degrees, clustering coefficients, shortest-path lengths and
two centrality measures, using the definitions in the book (Ch. 3).
"""
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import sbp

nodes = list("ABCDEFGHIJ")
edges = [("A", "B"), ("A", "C"), ("A", "D"), ("B", "C"), ("B", "D"),
         ("C", "D"), ("D", "E"), ("E", "F"), ("F", "G"), ("F", "H"),
         ("G", "H"), ("G", "I"), ("H", "I"), ("I", "J")]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
n = G.number_of_nodes()

# Adjacency matrix and degrees (book Eq. 3.1)
A = nx.to_numpy_array(G, nodelist=nodes)
degree = A.sum(axis=1)

# Clustering coefficient (Eq. 3.6): the fraction of pairs of neighbours
# that are themselves connected; (A^3)_ii counts each triangle twice
triangles = np.diag(A @ A @ A) / 2
pairs = degree * (degree - 1) / 2
clustering = np.divide(triangles, pairs, out=np.zeros(n), where=pairs > 0)

# Shortest-path lengths between all pairs of nodes
D = nx.floyd_warshall_numpy(G, nodelist=nodes)
diameter = D.max()                                         # Eq. 3.11
char_path_length = D[np.triu_indices(n, k=1)].mean()      # Eq. 3.12
closeness = (n - 1) / D.sum(axis=1)                        # Eq. 3.14

# Betweenness centrality (Eq. 3.18), counting each pair of nodes once
bc = nx.betweenness_centrality(G, normalized=False)
betweenness = np.array([bc[v] for v in nodes])

print(f"{n} nodes, {G.number_of_edges()} edges, mean degree "
      f"{degree.mean():.2f}")
print(f"mean clustering coefficient {clustering.mean():.4f}, diameter "
      f"{diameter:g}, characteristic path length {char_path_length:.4f}")
print("node  degree  clustering  closeness  betweenness")
for i, v in enumerate(nodes):
    print(f"  {v}   {degree[i]:4g}    {clustering[i]:8.3f}   "
          f"{closeness[i]:8.3f}   {betweenness[i]:9.2f}")

# --- Plot: node size by degree, colour by betweenness, fixed positions
x = [0.0, 1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 3.0, 4.0, 5.0]
y = [1.0, 1.0, 0.0, 0.0, 0.5, 0.5, 1.0, 0.0, 0.0, 0.0]
sbp.style()
fig, ax = plt.subplots(figsize=(7, 3.2))
idx = {v: i for i, v in enumerate(nodes)}
for u, w in edges:
    ax.plot([x[idx[u]], x[idx[w]]], [y[idx[u]], y[idx[w]]], "-",
            color="#999999", zorder=1)
sc = ax.scatter(x, y, s=150 * degree, c=betweenness, cmap="viridis_r",
                edgecolors="k", zorder=2)
for i, v in enumerate(nodes):
    ax.annotate(v, (x[i], y[i]), xytext=(0, 14 + 2 * degree[i]),
                textcoords="offset points", ha="center",
                bbox=dict(facecolor="white", edgecolor="none", pad=1))
fig.colorbar(sc, ax=ax, label="Betweenness centrality",
             ticks=range(0, 21, 5))
ax.set_title("Node size: degree; colour: betweenness")
ax.set_axis_off()
ax.set_ylim(-0.4, 1.6)
sbp.save_figure(fig, __file__, "fig-graph-basics")

sbp.save_results(__file__, {
    "degree": degree, "clustering": clustering,
    "mean_clustering": clustering.mean(), "diameter": diameter,
    "char_path_length": char_path_length, "closeness": closeness,
    "betweenness": betweenness,
})
sbp.show()

The different measures pick out different nodes. D has the largest degree, but E and F, with only two and three neighbours, carry the most shortest paths: every path between the two groups passes through both of them, so removing either would split the network in two. A, B and C, inside a complete group of four, have the highest clustering coefficient and no betweenness at all. Which measure matters depends on the question being asked; for example, betweenness, more than degree, often marks nodes whose removal disrupts communication across a network (book, §3.1.2 and §3.5).

3.1.1 Fundamental parameters

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

3.1.2 Measures of centrality

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

3.1.3 Mixing patterns: assortativity

Assortativity is the correlation coefficient between the degrees of the nodes at the two ends of each edge. A single number, however, is hard to interpret on its own: does it reflect how the network is wired, or merely the degrees of its nodes? A useful habit is to compare every such measure with randomised networks that preserve the degree of every node (§3.4.1). Each step of the randomisation takes two edges, \(a\)–\(b\) and \(c\)–\(d\), and rewires them as \(a\)–\(d\) and \(c\)–\(b\), unless this creates a self-loop or an edge that already exists. Random choices would normally differ between MATLAB and Python, so here they come from a small random number generator, sbp.uniform, written out in both languages, which returns exactly the same numbers in each.

Core MATLAB only.

%% Degree assortativity, and comparing a network with randomised versions
% Assortativity (book §3.1.3) is the correlation between the degrees of the
% two nodes at either end of an edge: positive when hubs link to hubs,
% negative when hubs link to sparsely connected nodes. To see whether a
% value says something about a network, rather than about its degrees
% alone, we compare it with randomised networks that keep every node's
% degree (book §3.4.1). Each randomisation step picks two edges, a-b and
% c-d, and rewires them to a-d and c-b, unless that would create a
% self-loop or an edge that already exists. The random choices come from
% sbp.uniform, so that MATLAB and Python make exactly the same swaps.
%
% Two networks: Zachary's karate club, and the E. coli STRING network
% (combined score at least 700).

files = {'karate_edges.csv', 'ecoli_string_ppi.csv'};
columns = {{'member1', 'member2'}, {'protein1', 'protein2'}};
keys = {'karate', 'string'};
copies = [20, 3];
results = struct();
for net = 1:2
    [edges, n] = load_edges(files{net}, columns{net});
    k0 = accumarray(edges(:), 1, [n, 1]);
    r_rand = zeros(1, copies(net)); c_rand = r_rand;
    for seed = 1:copies(net)
        shuffled = randomise(edges, n, 1000 + seed, 10);
        assert(isequal(accumarray(shuffled(:), 1, [n, 1]), k0));
        r_rand(seed) = degree_correlation(shuffled, n);
        c_rand(seed) = clustering(shuffled, n);
    end
    r = struct('nodes', n, 'edges', size(edges, 1), ...
        'assortativity', degree_correlation(edges, n), ...
        'clustering', clustering(edges, n), ...
        'assortativity_random', r_rand, 'clustering_random', c_rand);
    results.(keys{net}) = r;
    fprintf('%s: %d nodes, %d edges\n', keys{net}, n, size(edges, 1));
    fprintf(['  assortativity %+.3f; randomised %+.3f (range %+.3f to ' ...
        '%+.3f, %d networks)\n'], r.assortativity, mean(r_rand), ...
        min(r_rand), max(r_rand), copies(net));
    fprintf('  mean clustering %.3f; randomised %.3f\n', r.clustering, ...
        mean(c_rand));
end

%% Plot
fig = figure('Position', [100 100 900 400]);
measures = {'assortativity', 'clustering'};
labels = {'Assortativity r', 'Mean clustering'};
okabe_ito = sbp.palette();
blue = okabe_ito(1, :); red = okabe_ito(4, :);
for p = 1:2
    subplot(1, 2, p); hold on
    for net = 1:2
        r = results.(keys{net});
        h1 = plot(net - 1, r.(measures{p}), 'o', 'Color', red, ...
            'MarkerFaceColor', red, 'MarkerSize', 9);
        random = r.([measures{p} '_random']);
        h2 = plot(repmat(net - 0.85, size(random)), random, '_', ...
            'Color', blue, 'MarkerSize', 12);
    end
    yline(0, 'k');
    set(gca, 'XTick', [0, 1], 'XTickLabel', {'karate club', 'E. coli STRING'});
    xlim([-0.5, 1.5]); title(labels{p}); box off
    if p == 1
        legend([h1, h2], {'network', 'randomised'}, ...
            'Location', 'northwest', 'Box', 'off');
    end
end
sbp.save_figure(fig, mfilename('fullpath'), 'fig-assortativity');

sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function [edges, n] = load_edges(file, columns)
% Edges as pairs of node indices; nodes numbered in sorted order.
T = readtable(fullfile(sbp.data_dir(), file), 'TextType', 'string');
a = string(T.(columns{1})); b = string(T.(columns{2}));
names = unique([a; b]);                          % sorted
[~, ia] = ismember(a, names);
[~, ib] = ismember(b, names);
edges = [ia, ib];
n = numel(names);
end

function r = degree_correlation(edges, n)
% Newman's degree correlation coefficient.
k = accumarray(edges(:), 1, [n, 1]);
j = k(edges(:, 1)); l = k(edges(:, 2));
m = mean((j + l) / 2);
r = (mean(j .* l) - m ^ 2) / (mean((j .^ 2 + l .^ 2) / 2) - m ^ 2);
end

function c = clustering(edges, n)
% Mean clustering coefficient (nodes of degree < 2 count as 0).
A = sparse(edges(:, 1), edges(:, 2), 1, n, n);
A = A + A';
k = full(sum(A, 2));
triangles = full(sum((A * A) .* A, 2)) / 2;
cc = zeros(n, 1);
ok = k > 1;
cc(ok) = 2 * triangles(ok) ./ (k(ok) .* (k(ok) - 1));
c = mean(cc);
end

function edges = randomise(edges, n, seed, swaps_per_edge)
% Degree-preserving randomisation by double edge swaps.
m = size(edges, 1);
A = false(n);
A(sub2ind([n, n], edges(:, 1), edges(:, 2))) = true;
A(sub2ind([n, n], edges(:, 2), edges(:, 1))) = true;
u = sbp.uniform(seed, 3 * swaps_per_edge * m);
for t = 0:swaps_per_edge * m - 1
    e1 = floor(u(3 * t + 1) * m) + 1;
    e2 = floor(u(3 * t + 2) * m) + 1;
    a = edges(e1, 1); b = edges(e1, 2);
    c = edges(e2, 1); d = edges(e2, 2);
    if u(3 * t + 3) < 0.5                        % either orientation of c-d
        [c, d] = deal(d, c);
    end
    if numel(unique([a, b, c, d])) < 4 || A(a, d) || A(c, b)
        continue                                 % self-loop or existing edge
    end
    A(a, b) = false; A(b, a) = false; A(c, d) = false; A(d, c) = false;
    A(a, d) = true; A(d, a) = true; A(c, b) = true; A(b, c) = true;
    edges(e1, :) = [a, d];
    edges(e2, :) = [c, b];
end
end

Needs SciPy.

"""Degree assortativity, and comparing a network with randomised versions.

Assortativity (book §3.1.3) is the correlation between the degrees of the
two nodes at either end of an edge: positive when hubs link to hubs,
negative when hubs link to sparsely connected nodes. To see whether a
value says something about a network, rather than about its degrees
alone, we compare it with randomised networks that keep every node's
degree (book §3.4.1). Each randomisation step picks two edges, a-b and
c-d, and rewires them to a-d and c-b, unless that would create a
self-loop or an edge that already exists. The random choices come from
sbp.uniform, so that MATLAB and Python make exactly the same swaps.

Two networks: Zachary's karate club, and the E. coli STRING network
(combined score at least 700).
"""
import numpy as np
import pandas as pd
from scipy import sparse
import matplotlib.pyplot as plt
import sbp


def load(edge_file, columns):
    """Edges as pairs of node indices; nodes numbered in sorted order."""
    table = pd.read_csv(sbp.DATA / edge_file)[columns].astype(str)
    names = np.unique(table.to_numpy())
    index = {name: i for i, name in enumerate(names)}
    edges = np.array([[index[a], index[b]] for a, b in table.to_numpy()])
    return edges, len(names)


def degree_correlation(edges, n):
    """Newman's degree correlation coefficient."""
    k = np.bincount(edges.ravel(), minlength=n).astype(float)
    j, l = k[edges[:, 0]], k[edges[:, 1]]
    mean = np.mean((j + l) / 2)
    return ((np.mean(j * l) - mean ** 2)
            / (np.mean((j ** 2 + l ** 2) / 2) - mean ** 2))


def clustering(edges, n):
    """Mean clustering coefficient (nodes of degree < 2 count as 0)."""
    A = sparse.coo_matrix((np.ones(len(edges)), (edges[:, 0], edges[:, 1])),
                          shape=(n, n)).tocsr()
    A = A + A.T
    k = np.asarray(A.sum(axis=1)).ravel()
    triangles = np.asarray((A @ A).multiply(A).sum(axis=1)).ravel() / 2
    c = np.zeros(n)
    ok = k > 1
    c[ok] = 2 * triangles[ok] / (k[ok] * (k[ok] - 1))
    return c.mean()


def randomise(edges, n, seed, swaps_per_edge=10):
    """Degree-preserving randomisation by double edge swaps."""
    edges = edges.copy()
    m = len(edges)
    A = np.zeros((n, n), dtype=bool)
    A[edges[:, 0], edges[:, 1]] = A[edges[:, 1], edges[:, 0]] = True
    u = sbp.uniform(seed, 3 * swaps_per_edge * m)
    for t in range(swaps_per_edge * m):
        e1, e2 = int(u[3 * t] * m), int(u[3 * t + 1] * m)
        a, b = edges[e1]
        c, d = edges[e2]
        if u[3 * t + 2] < 0.5:                  # either orientation of c-d
            c, d = d, c
        if len({a, b, c, d}) < 4 or A[a, d] or A[c, b]:
            continue                            # self-loop or existing edge
        A[a, b] = A[b, a] = A[c, d] = A[d, c] = False
        A[a, d] = A[d, a] = A[c, b] = A[b, c] = True
        edges[e1], edges[e2] = (a, d), (c, b)
    return edges


networks = {
    "karate": (load("karate_edges.csv", ["member1", "member2"]), 20),
    "string": (load("ecoli_string_ppi.csv", ["protein1", "protein2"]), 3),
}
results = {}
for name, ((edges, n), copies) in networks.items():
    r_rand, c_rand = [], []
    for seed in range(1, copies + 1):
        shuffled = randomise(edges, n, seed=1000 + seed)
        assert np.array_equal(np.bincount(shuffled.ravel(), minlength=n),
                              np.bincount(edges.ravel(), minlength=n))
        r_rand.append(degree_correlation(shuffled, n))
        c_rand.append(clustering(shuffled, n))
    results[name] = {"nodes": n, "edges": len(edges),
                     "assortativity": degree_correlation(edges, n),
                     "clustering": clustering(edges, n),
                     "assortativity_random": r_rand,
                     "clustering_random": c_rand}
    r = results[name]
    print(f"{name}: {n} nodes, {len(edges)} edges")
    print(f"  assortativity {r['assortativity']:+.3f}; randomised "
          f"{np.mean(r_rand):+.3f} (range {min(r_rand):+.3f} to "
          f"{max(r_rand):+.3f}, {copies} networks)")
    print(f"  mean clustering {r['clustering']:.3f}; randomised "
          f"{np.mean(c_rand):.3f}")

# --- Plot
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
for ax, (key, label) in zip(axes, [("assortativity", "Assortativity r"),
                                   ("clustering", "Mean clustering")]):
    for x, name in enumerate(results):
        r = results[name]
        ax.plot([x], [r[key]], "o", color="#D55E00", ms=9,
                label="network" if x == 0 else None)
        ax.plot(np.full(len(r[f"{key}_random"]), x + 0.15),
                r[f"{key}_random"], "_", color="#0072B2", ms=12,
                label="randomised" if x == 0 else None)
    ax.axhline(0, color="black", lw=0.5)
    ax.set_xticks([0, 1], ["karate club", "E. coli STRING"])
    ax.set_xlim(-0.5, 1.5)
    ax.set_title(label)
axes[0].legend(loc="upper left", frameon=False)
sbp.save_figure(fig, __file__, "fig-assortativity")

sbp.save_results(__file__, results)
sbp.show()

The karate club is disassortative (\(r = -0.48\)): its two leaders, the hubs, are friends with many members who have few other friends. Note, though, that the randomised networks are also disassortative (\(r \approx -0.30\)): in a small network with a few large hubs, there are simply not enough hubs to link to each other. Only part of the effect, therefore, reflects how the club is wired. The E. coli STRING network is strongly assortative (\(r = +0.64\)), whereas its randomised versions are not (\(r \approx -0.02\)). This is perhaps surprising, since protein interaction networks are often described as disassortative. But STRING records functional associations, and the members of a protein complex are all associated with each other: complexes appear as dense clusters of proteins with similar degrees, which also explains the high clustering coefficient (0.41, against 0.02 after randomisation).

3.2 Canonical network models

3.2.1 Erdős–Rényi (ER) network model

To judge whether a property of a real network is remarkable, we need something to compare it with. The simplest null model is the Erdős–Rényi random network, in which each of the \(\binom{n}{2}\) possible edges is present independently with probability \(p\). Its degrees follow a binomial distribution, close to a Poisson distribution for large \(n\); its clustering coefficient is about \(p\), which is very small for a sparse network; and its paths are short, growing only as \(\ln n\).

3.2.2 Small-world networks

Real networks often combine short paths with high clustering. Watts and Strogatz showed how this can arise (Watts and Strogatz 1998). Start from a ring lattice, in which each node is joined to its \(k\) nearest neighbours on either side: clustering is high, but paths are long, since getting to the far side of the ring takes many steps. Then rewire each edge, with probability \(p\), to a randomly chosen node. The code below computes the mean clustering coefficient \(C(p)\) and characteristic path length \(L(p)\) as \(p\) rises from \(10^{-4}\) to 1, for networks of 500 nodes with ten neighbours each, averaging over ten networks at each \(p\). This is also the first problem of the BT5240 network assignment.

Core MATLAB only.

%% Small-world networks (Watts and Strogatz, 1998)
% Start from a ring lattice of n nodes, each linked to its k nearest
% neighbours on either side, and rewire each edge with probability p. A
% little rewiring makes paths short, as in a random network, while keeping
% the high clustering of the lattice. We also compare with Erdős–Rényi
% random networks with the same numbers of nodes and edges.
% Requires: core MATLAB only.

n = 500; k = 5;                   % 500 nodes, 2k = 10 neighbours each
probs = logspace(-4, 0, 13);      % rewiring probabilities
reps = 10;                        % networks averaged for each p
rng(1);

[C0, L0] = clustering_and_path_length(ring_lattice(n, k));
C = zeros(reps, numel(probs));
L = zeros(reps, numel(probs));
for r = 1:reps
    for i = 1:numel(probs)
        [C(r, i), L(r, i)] = clustering_and_path_length( ...
            watts_strogatz(n, k, probs(i)));
    end
end
C_ratio = mean(C, 1) / C0;
L_ratio = mean(L, 1) / L0;

p_er = n * k / (n * (n - 1) / 2);  % same expected number of edges, n*k
er = zeros(reps, 2);
for r = 1:reps
    [er(r, 1), er(r, 2)] = clustering_and_path_length(erdos_renyi(n, p_er));
end
er = mean(er, 1);

fprintf('Ring lattice: C = %.4f, L = %.4f\n', C0, L0);
for i = 1:numel(probs)
    fprintf('  p = %8.4f: C(p)/C(0) = %.3f, L(p)/L(0) = %.3f\n', ...
        probs(i), C_ratio(i), L_ratio(i));
end
fprintf('Erdős–Rényi, same n and m: C = %.4f, L = %.4f\n', er(1), er(2));

%% Plot
fig = figure;
blue = [0.000 0.447 0.698]; orange = [0.902 0.624 0.000];
semilogx(probs, C_ratio, 'o-', 'Color', blue, 'MarkerFaceColor', blue);
hold on
semilogx(probs, L_ratio, 's-', 'Color', orange, 'MarkerFaceColor', orange);
xlabel('Rewiring probability p'); ylabel('Relative to the ring lattice');
title(sprintf('Watts–Strogatz networks, n = %d, %d neighbours', n, 2 * k));
legend({'C(p) / C(0)', 'L(p) / L(0)'}, 'Location', 'southwest', ...
    'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-small-world');

results.lattice = struct('C', C0, 'L', L0);
for p = [0.1 1]
    i = find(abs(probs - p) < 1e-12);
    name = strrep(sprintf('p_%g', p), '.', '_');
    results.ws.(name) = struct('C_ratio', C_ratio(i), ...
        'L_ratio', L_ratio(i));
end
results.er = struct('C', er(1), 'L', er(2));
results.probs = probs;
results.C_ratio = C_ratio;
results.L_ratio = L_ratio;
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function A = ring_lattice(n, k)
A = false(n);
idx = (1:n)';
for j = 1:k
    nb = mod(idx - 1 + j, n) + 1;
    A(sub2ind([n n], idx, nb)) = true;
    A(sub2ind([n n], nb, idx)) = true;
end
end

function A = watts_strogatz(n, k, p)
% Rewire each lattice edge (i, i+j) with probability p, moving its far
% end to a random node, avoiding self-loops and duplicate edges.
A = ring_lattice(n, k);
for j = 1:k
    for i = 1:n
        old = mod(i - 1 + j, n) + 1;
        if A(i, old) && rand < p
            new = randi(n);                 % draw until the new end is
            while new == i || A(i, new)     % neither i nor a neighbour
                new = randi(n);
            end
            A(i, old) = false; A(old, i) = false;
            A(i, new) = true;  A(new, i) = true;
        end
    end
end
end

function A = erdos_renyi(n, p)
upper = triu(rand(n) < p, 1);
A = upper | upper';
end

function [C, L] = clustering_and_path_length(A)
% Mean clustering coefficient, and mean shortest-path length over all
% pairs of nodes that are connected by some path.
A = double(A);
deg = sum(A, 2);
tri = sum((A * A) .* A, 2) / 2;
pairs = deg .* (deg - 1) / 2;
c = zeros(size(deg));
c(pairs > 0) = tri(pairs > 0) ./ pairs(pairs > 0);
C = mean(c);
D = distances(graph(A));
d = D(triu(true(size(A)), 1));
L = mean(d(isfinite(d)));
end

Needs NumPy and SciPy.

"""Small-world networks (Watts and Strogatz, 1998).

Start from a ring lattice of n nodes, each linked to its k nearest
neighbours on either side, and rewire each edge with probability p. A
little rewiring makes paths short, as in a random network, while keeping
the high clustering of the lattice. We also compare with Erdős–Rényi
random networks with the same numbers of nodes and edges.
"""
import numpy as np
from scipy.sparse.csgraph import shortest_path
import matplotlib.pyplot as plt
import sbp

n, k = 500, 5                     # 500 nodes, 2k = 10 neighbours each
probs = np.logspace(-4, 0, 13)    # rewiring probabilities
reps = 10                         # networks averaged for each p
rng = np.random.default_rng(1)


def ring_lattice(n, k):
    A = np.zeros((n, n), dtype=bool)
    for j in range(1, k + 1):
        idx = np.arange(n)
        A[idx, (idx + j) % n] = A[(idx + j) % n, idx] = True
    return A


def watts_strogatz(n, k, p):
    """Rewire each lattice edge (i, i+j) with probability p, moving its far
    end to a random node, avoiding self-loops and duplicate edges."""
    A = ring_lattice(n, k)
    for j in range(1, k + 1):
        for i in range(n):
            old = (i + j) % n
            if A[i, old] and rng.random() < p:
                new = rng.integers(n)          # draw until the new end is
                while new == i or A[i, new]:   # neither i nor a neighbour
                    new = rng.integers(n)
                A[i, old] = A[old, i] = False
                A[i, new] = A[new, i] = True
    return A


def erdos_renyi(n, p):
    upper = np.triu(rng.random((n, n)) < p, 1)
    return upper | upper.T


def clustering_and_path_length(A):
    """Mean clustering coefficient, and mean shortest-path length over all
    pairs of nodes that are connected by some path."""
    A = A.astype(float)
    deg = A.sum(axis=1)
    tri = ((A @ A) * A).sum(axis=1) / 2
    pairs = deg * (deg - 1) / 2
    C = np.divide(tri, pairs, out=np.zeros(len(A)), where=pairs > 0).mean()
    D = shortest_path(A, unweighted=True, directed=False)
    d = D[np.triu_indices(len(A), k=1)]
    return C, d[np.isfinite(d)].mean()


C0, L0 = clustering_and_path_length(ring_lattice(n, k))
C, L = np.zeros((reps, probs.size)), np.zeros((reps, probs.size))
for r in range(reps):
    for i, p in enumerate(probs):
        C[r, i], L[r, i] = clustering_and_path_length(watts_strogatz(n, k, p))
C_ratio, L_ratio = C.mean(axis=0) / C0, L.mean(axis=0) / L0

p_er = n * k / (n * (n - 1) / 2)  # same expected number of edges, n*k
er = np.array([clustering_and_path_length(erdos_renyi(n, p_er))
               for _ in range(reps)]).mean(axis=0)

print(f"Ring lattice: C = {C0:.4f}, L = {L0:.4f}")
for p, c, l in zip(probs, C_ratio, L_ratio):
    print(f"  p = {p:8.4f}: C(p)/C(0) = {c:.3f}, L(p)/L(0) = {l:.3f}")
print(f"Erdős–Rényi, same n and m: C = {er[0]:.4f}, L = {er[1]:.4f}")

# --- Plot
sbp.style()
fig, ax = plt.subplots()
ax.semilogx(probs, C_ratio, "o-", color="#0072B2", label="C(p) / C(0)")
ax.semilogx(probs, L_ratio, "s-", color="#E69F00", label="L(p) / L(0)")
ax.set_xlabel("Rewiring probability p")
ax.set_ylabel("Relative to the ring lattice")
ax.set_title(f"Watts–Strogatz networks, n = {n}, {2 * k} neighbours")
ax.legend(frameon=False, loc="lower left")
sbp.save_figure(fig, __file__, "fig-small-world")

at = {f"p_{p:g}".replace(".", "_"): i
      for i, p in enumerate(probs) if p in (0.1, 1.0)}
sbp.save_results(__file__, {
    "lattice": {"C": C0, "L": L0},
    "ws": {name: {"C_ratio": C_ratio[i], "L_ratio": L_ratio[i]}
           for name, i in at.items()},
    "er": {"C": er[0], "L": er[1]},
    "probs": probs, "C_ratio": C_ratio, "L_ratio": L_ratio,
})
sbp.show()

The two curves fall at very different rewiring probabilities. Rewiring 1% of the edges already shortens the typical path by about 70%, because each rewired edge is a shortcut across the ring, while clustering hardly changes, because each rewired edge removes only a few of the many triangles around it. Between about \(p = 0.01\) and \(p = 0.1\), the networks are small worlds: clustered almost like a lattice, with paths far shorter than in the lattice and approaching those of a random network. At \(p = 1\), they are essentially random, and their clustering coefficient and path length are close to those of Erdős–Rényi networks with the same numbers of nodes and edges (about 0.02 and 2.9).

Since these networks are random, MATLAB and Python, which draw different random numbers, give slightly different results; the automated checks compare the averages at \(p = 0.1\) and \(p = 1\), within 10%.

3.2.3 Scale-free networks

Erdős–Rényi and small-world networks share one feature that many biological networks do not: most nodes have roughly the same degree. In protein interaction and metabolic networks, by contrast, most nodes have very few neighbours while a few hubs have very many, and the degree distribution has a long tail, close to a power law, \(P(k) \propto k^{-\gamma}\). Such networks are called scale-free.

Barabási and Albert proposed a simple mechanism (Barabási and Albert 1999). The network grows one node at a time, and each new node attaches to \(m\) existing nodes, chosen with probability proportional to their degree: preferential attachment, or “the rich get richer”. For large networks this gives \(P(k) = 2m(m+1)/k(k+1)(k+2)\), which falls as \(k^{-3}\).

There is a neat way to choose a node with probability proportional to its degree: keep a list of the two ends of every edge, so that each node appears in it as many times as it has links, and pick an entry of that list uniformly at random.

Core MATLAB only.

%% Scale-free networks by preferential attachment (Barabási and Albert)
% Nodes are added one at a time; each new node links to m existing nodes,
% chosen with probability proportional to their degree. The resulting
% degree distribution has a heavy tail, P(k) ~ k^-3, with a few highly
% connected hubs. We compare it with an Erdős–Rényi network of the same
% size and mean degree.
% Requires: core MATLAB only.

n = 2000; m = 2;
reps = 10;
rng(1);

k_max = 200;
P_ba = zeros(1, k_max + 1); P_er = zeros(1, k_max + 1);
max_deg_ba = zeros(1, reps); max_deg_er = zeros(1, reps);
for r = 1:reps
    d = degrees(barabasi_albert(n, m), n);
    P_ba = P_ba + histcounts(min(d, k_max), -0.5:k_max + 0.5) / n / reps;
    max_deg_ba(r) = max(d);
    % Erdős–Rényi with the same expected mean degree
    mean_k = mean(d);
    upper = triu(rand(n) < mean_k / (n - 1), 1);
    d = sum(upper | upper', 2)';
    P_er = P_er + histcounts(min(d, k_max), -0.5:k_max + 0.5) / n / reps;
    max_deg_er(r) = max(d);
end

k = 0:k_max;
fprintf('Mean degree %.4f\n', mean_k);
fprintf(['Largest degree, averaged over %d networks: preferential ' ...
    'attachment %.1f, Erdős–Rényi %.1f\n'], reps, mean(max_deg_ba), ...
    mean(max_deg_er));
fprintf(['Fraction of nodes with degree >= 10: %.4f (theory for large ' ...
    'n: %.4f); Erdős–Rényi %.4f\n'], sum(P_ba(11:end)), ...
    m * (m + 1) / (10 * 11), sum(P_er(11:end)));

%% Plot. Right: the fraction of nodes with degree at least k, which is
% much less noisy in the tail than P(k) itself
ccdf_ba = fliplr(cumsum(fliplr(P_ba)));
ccdf_er = fliplr(cumsum(fliplr(P_er)));
blue = [0.000 0.447 0.698]; orange = [0.902 0.624 0.000];
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
plot(k, P_ba, 'o', 'Color', blue, 'MarkerFaceColor', blue, 'MarkerSize', 4);
hold on
plot(k, P_er, 's', 'Color', orange, 'MarkerFaceColor', orange, ...
    'MarkerSize', 4);
xlim([-0.5 30]);
xlabel('Degree k'); ylabel('Fraction of nodes with degree k');
title('Degree distribution');
legend({'preferential attachment', 'Erdős–Rényi'}, 'Box', 'off');
box off

subplot(1, 2, 2)
ok = ccdf_ba > 0 & k > 0;
loglog(k(ok), ccdf_ba(ok), 'o', 'Color', blue, 'MarkerFaceColor', blue, ...
    'MarkerSize', 4);
hold on
ok = ccdf_er > 0 & k > 0;
loglog(k(ok), ccdf_er(ok), 's', 'Color', orange, ...
    'MarkerFaceColor', orange, 'MarkerSize', 4);
kk = k(m + 1:end);
loglog(kk, m * (m + 1) ./ (kk .* (kk + 1)), '-', 'Color', [0.6 0.6 0.6]);
ylim([1e-6 1.5]);
xlabel('Degree k'); ylabel('Fraction of nodes with degree \geq k');
title('Tail, on logarithmic axes');
legend({'preferential attachment', 'Erdős–Rényi', ...
    'theory, m(m+1)/k(k+1)'}, 'Location', 'southwest', 'Box', 'off', ...
    'FontSize', 9);
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-scale-free');

results.mean_degree = mean_k;
results.ba = struct('P2', P_ba(3), 'P3', P_ba(4), ...
    'P_ge_10', sum(P_ba(11:end)), 'mean_max_degree', mean(max_deg_ba));
results.er = struct('mean_max_degree', mean(max_deg_er));
results.er_P_ge_10 = sum(P_er(11:end));
results.P_ba = P_ba(1:51);
results.P_er = P_er(1:51);
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function edges = barabasi_albert(n, m)
% Edge list of a preferential-attachment network. 'ends' lists every
% edge end, so a node appears in it once per link: picking a uniformly
% random element of 'ends' picks a node with probability proportional
% to its degree. Nodes are numbered from 0, as in the Python version.
n_edges = m * (m + 1) / 2 + m * (n - m - 1);
edges = zeros(n_edges, 2);
e = 0;
for i = 0:m                                % start from a clique
    for j = 0:i - 1
        e = e + 1;
        edges(e, :) = [i j];
    end
end
ends = reshape(edges(1:e, :)', 1, []);
ends = [ends, zeros(1, 2 * n_edges - numel(ends))];
n_ends = 2 * e;
for new = m + 1:n - 1
    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 d = degrees(edges, n)
d = accumarray(edges(:) + 1, 1, [n 1])';
end

Needs NumPy.

"""Scale-free networks by preferential attachment (Barabási and Albert).

Nodes are added one at a time; each new node links to m existing nodes,
chosen with probability proportional to their degree. The resulting
degree distribution has a heavy tail, P(k) ~ k^-3, with a few highly
connected hubs. We compare it with an Erdős–Rényi network of the same
size and mean degree.
"""
import numpy as np
import matplotlib.pyplot as plt
import sbp

n, m = 2000, 2
reps = 10
rng = np.random.default_rng(1)


def barabasi_albert(n, m):
    """Edge list of a preferential-attachment network. 'ends' lists every
    edge end, so a node appears in it once per link: picking a uniformly
    random element of 'ends' picks a node with probability proportional
    to its degree."""
    edges = [(i, j) for i in range(m + 1) for j in range(i)]  # a clique
    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 edges


def degrees(edges, n):
    return np.bincount(np.ravel(edges), minlength=n)


k_max = 200
P_ba, P_er = np.zeros(k_max + 1), np.zeros(k_max + 1)
max_deg_ba, max_deg_er = [], []
for _ in range(reps):
    d = degrees(barabasi_albert(n, m), n)
    P_ba += np.bincount(np.minimum(d, k_max), minlength=k_max + 1) / n / reps
    max_deg_ba.append(d.max())
    # Erdős–Rényi with the same expected mean degree
    mean_k = d.mean()
    upper = np.triu(rng.random((n, n)) < mean_k / (n - 1), 1)
    d = (upper | upper.T).sum(axis=1)
    P_er += np.bincount(np.minimum(d, k_max), minlength=k_max + 1) / n / reps
    max_deg_er.append(d.max())

k = np.arange(k_max + 1)
print(f"Mean degree {mean_k:.4f}")
print(f"Largest degree, averaged over {reps} networks: preferential "
      f"attachment {np.mean(max_deg_ba):.1f}, Erdős–Rényi "
      f"{np.mean(max_deg_er):.1f}")
print(f"Fraction of nodes with degree >= 10: {P_ba[10:].sum():.4f} "
      f"(theory for large n: {m * (m + 1) / (10 * 11):.4f}); "
      f"Erdős–Rényi {P_er[10:].sum():.4f}")

# --- Plot. Right: the fraction of nodes with degree at least k, which is
# much less noisy in the tail than P(k) itself
ccdf_ba, ccdf_er = P_ba[::-1].cumsum()[::-1], P_er[::-1].cumsum()[::-1]
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot(k, P_ba, "o", color="#0072B2", ms=4, label="preferential attachment")
ax1.plot(k, P_er, "s", color="#E69F00", ms=4, label="Erdős–Rényi")
ax1.set_xlim(-0.5, 30)
ax1.set_xlabel("Degree k")
ax1.set_ylabel("Fraction of nodes with degree k")
ax1.set_title("Degree distribution")
ax1.legend(frameon=False)
ax2.loglog(k[1:][ccdf_ba[1:] > 0], ccdf_ba[1:][ccdf_ba[1:] > 0], "o",
           color="#0072B2", ms=4, label="preferential attachment")
ax2.loglog(k[1:][ccdf_er[1:] > 0], ccdf_er[1:][ccdf_er[1:] > 0], "s",
           color="#E69F00", ms=4, label="Erdős–Rényi")
ax2.loglog(k[m:], m * (m + 1) / (k[m:] * (k[m:] + 1.0)), "-",
           color="#999999", label="theory, $m(m+1)/k(k+1)$")
ax2.set_ylim(1e-6, 1.5)
ax2.set_xlabel("Degree k")
ax2.set_ylabel("Fraction of nodes with degree $\\geq$ k")
ax2.set_title("Tail, on logarithmic axes")
ax2.legend(frameon=False, loc="lower left", fontsize=9)
sbp.save_figure(fig, __file__, "fig-scale-free")

sbp.save_results(__file__, {
    "mean_degree": mean_k,
    "ba": {"P2": P_ba[2], "P3": P_ba[3], "P_ge_10": P_ba[10:].sum(),
           "mean_max_degree": np.mean(max_deg_ba)},
    "er": {"mean_max_degree": np.mean(max_deg_er)},
    "er_P_ge_10": P_er[10:].sum(),
    "P_ba": P_ba[:51], "P_er": P_er[:51],
})
sbp.show()

Both networks have 2000 nodes and a mean degree of about four. In the random network, no node has more than about a dozen neighbours. With preferential attachment, half of the nodes have only the minimum two links, and the most connected node has, on average over ten networks, more than a hundred. On logarithmic axes the tail of the distribution follows the predicted straight line until it runs out of nodes.

3.2.4 Other models of network generation

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

3.3 Community detection

3.3.1 Modularity maximisation

We find communities in the karate club (§2.4.3) by maximising modularity, using the spectral method of Newman (Newman 2006). The leading eigenvector of the modularity matrix \(\mathbf{B} = \mathbf{A} - \mathbf{k}\mathbf{k}^T/2m\) splits the network in two, by the signs of its entries; each part is then split again, in the same way, until no further split increases \(Q\). Unlike many community detection algorithms, the method involves no random choices, and so gives the same answer every time.

Core MATLAB only.

%% Communities by modularity maximisation: Newman's spectral method
% Modularity (book §3.3.1) compares the edges within communities with the
% number expected at random, for the same degrees:
%     Q = (1/2m) sum_ij [A_ij - k_i k_j / 2m] delta(c_i, c_j).
% The matrix B = A - k k'/2m is the modularity matrix. Newman's method
% splits the network in two by the signs of the leading eigenvector of B,
% and then splits each part again, using the "generalised" modularity
% matrix of that part, until no split increases Q (Newman, 2006, PNAS).
% Unlike many other methods, it involves no random choices.

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
k = sum(A, 2);
two_m = sum(k);
B = A - k * k' / two_m;
Q = @(labels) sum(B .* (labels(:) == labels(:)'), 'all') / two_m;

communities = {}; queue = {1:n}; first_split = {};
while ~isempty(queue)
    group = queue{1}; queue(1) = [];
    parts = split_group(B, group, two_m);
    if isempty(parts)
        communities{end + 1} = group; %#ok<SAGROW>
    else
        if isempty(first_split), first_split = parts; end
        queue = [queue, parts]; %#ok<AGROW>
    end
end

% Label communities 1, 2, ... in order of their lowest-numbered member
[~, order] = sort(cellfun(@min, communities));
communities = communities(order);
labels = zeros(1, n);
for c = 1:numel(communities)
    labels(communities{c}) = c;
end
halves = zeros(1, n);
halves(first_split{1}) = 1; halves(first_split{2}) = 2;
if halves(1) ~= 1, halves = 3 - halves; end      % member 1 in the first half

first = repmat("Officer", 1, n);
first(halves == 1) = "Mr. Hi";
misplaced = find(first ~= faction);
fprintf(['First split: Q = %.4f; it places %d of %d members on the side ' ...
    'they joined (misplaced: %s)\n'], Q(halves), sum(first == faction), n, ...
    strjoin(string(misplaced), ', '));
fprintf('Final: %d communities, Q = %.4f\n', numel(communities), Q(labels));
for c = 1:numel(communities)
    fprintf('  community %d: members %s\n', c, ...
        strjoin(string(communities{c}), ', '));
end

%% Plot
fig = figure('Position', [100 100 600 500]);
palette = [0.000 0.447 0.698; 0.600 0.780 0.878; 0.835 0.369 0.000; ...
           0.933 0.749 0.600; 0.000 0.620 0.451; 0.600 0.847 0.780];
plot(graph(A), 'Layout', 'force', 'NodeColor', palette(labels, :), ...
    'MarkerSize', 8, 'EdgeColor', 'k', 'EdgeAlpha', 0.3);
title(sprintf('%d communities, Q = %.3f', numel(communities), Q(labels)));
axis off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-modularity');

results.halves = halves;
results.q_halves = Q(halves);
results.communities = labels;
results.q = Q(labels);
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function parts = split_group(B, group, two_m)
% Split a group of nodes in two, or return {} if no split increases the
% modularity.
Bg = B(group, group);
Bg = Bg - diag(sum(Bg, 2));               % generalised modularity matrix
[V, D] = eig((Bg + Bg') / 2);
[value, top] = max(diag(D));
parts = {};
if value < 1e-10, return; end
s = ones(numel(group), 1);
s(V(:, top) < 0) = -1;
if s' * Bg * s / (2 * two_m) < 1e-10, return; end   % the gain in Q
parts = {group(s > 0), group(s < 0)};
end

Needs NetworkX (to check \(Q\), and for drawing).

"""Communities by modularity maximisation: Newman's spectral method.

Modularity (book §3.3.1) compares the edges within communities with the
number expected at random, for the same degrees:
    Q = (1/2m) sum_ij [A_ij - k_i k_j / 2m] delta(c_i, c_j).
The matrix B = A - k k'/2m is the modularity matrix. Newman's method
splits the network in two by the signs of the leading eigenvector of B,
and then splits each part again, using the "generalised" modularity
matrix of that part, until no split increases Q (Newman, 2006, PNAS).
Unlike many other methods, it involves no random choices.
"""
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").to_numpy() - 1
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:
    A[i, j] = A[j, i] = 1
k = A.sum(axis=1)
two_m = k.sum()
B = A - np.outer(k, k) / two_m


def modularity(labels):
    same = labels[:, None] == labels[None, :]
    return np.sum(B * same) / two_m


def split(group):
    """Split a group of nodes in two, or return None if no split
    increases the modularity."""
    Bg = B[np.ix_(group, group)]
    Bg = Bg - np.diag(Bg.sum(axis=1))         # generalised modularity matrix
    values, vectors = np.linalg.eigh(Bg)
    if values[-1] < 1e-10:
        return None
    s = np.where(vectors[:, -1] >= 0, 1, -1)
    if s @ Bg @ s / (2 * two_m) < 1e-10:      # the gain in Q
        return None
    return group[s > 0], group[s < 0]


communities, queue = [], [np.arange(n)]
first_split = None
while queue:
    group = queue.pop(0)
    parts = split(group)
    if parts is None:
        communities.append(group)
    else:
        if first_split is None:
            first_split = parts
        queue.extend(parts)

# Label communities 1, 2, ... in order of their lowest-numbered member
communities.sort(key=lambda g: g.min())
labels = np.zeros(n, dtype=int)
for c, g in enumerate(communities, start=1):
    labels[g] = c
halves = np.zeros(n, dtype=int)
halves[first_split[0]], halves[first_split[1]] = 1, 2
if halves[0] != 1:
    halves = 3 - halves                         # member 1 in the first half

# Check against NetworkX's own modularity function
G = nx.from_numpy_array(A)
assert abs(nx.community.modularity(G, [set(g) for g in communities])
           - modularity(labels)) < 1e-12

first = np.where(halves == 1, "Mr. Hi", "Officer")
misplaced = np.flatnonzero(first != faction) + 1
print(f"First split: Q = {modularity(halves):.4f}; it places "
      f"{np.sum(first == faction)} of {n} members on the side they joined "
      f"(misplaced: {', '.join(str(x) for x in misplaced)})")
print(f"Final: {len(communities)} communities, Q = {modularity(labels):.4f}")
for c, g in enumerate(communities, start=1):
    print(f"  community {c}: members {', '.join(str(x) for x in g + 1)}")

# --- Plot
sbp.style()
fig, ax = plt.subplots(figsize=(6, 5))
pos = nx.spring_layout(G, seed=1)
palette = ["#0072B2", "#99C7E0", "#D55E00", "#EEBF99", "#009E73", "#99D8C7"]
nx.draw_networkx_edges(G, pos, ax=ax, alpha=0.3)
nx.draw_networkx_nodes(G, pos, ax=ax, node_size=200,
                       node_color=[palette[c - 1] for c in labels],
                       node_shape="o")
nx.draw_networkx_labels(G, pos, {i: i + 1 for i in range(n)}, ax=ax,
                        font_size=7)
ax.set_title(f"{len(communities)} communities, Q = {modularity(labels):.3f}")
ax.axis("off")
sbp.save_figure(fig, __file__, "fig-modularity")

sbp.save_results(__file__, {
    "halves": halves, "q_halves": modularity(halves),
    "communities": labels, "q": modularity(labels),
})
sbp.show()

The first split already recovers the two factions of the club, misplacing only member 9 (\(Q = 0.371\)). Splitting further yields four communities, with \(Q = 0.393\): each faction divides into two smaller groups. On the instructor’s side, for example, members 5, 6, 7, 11 and 17 form a tight group of their own, attached to the rest of the club almost only through member 1. Newman reports a slightly higher modularity, 0.419, after an additional “fine-tuning” step that moves individual nodes between communities; we leave that as an exercise. Note also that the leading eigenvector of \(\mathbf{B}\) and the Fiedler vector of \(\mathbf{L}\) (§2.4.3) disagree about member 3: both methods are approximations to an intractable problem.

3.3.2 Similarity-based clustering

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

3.3.3 Girvan–Newman algorithm

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

3.3.4 Other methods

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

3.3.5 Community detection in biological networks

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

3.4 Network motifs

The transcriptional regulatory network of E. coli is the network in which motifs were first described. We use the version distributed with the PRECISE-1K compendium (Lamoureux et al. 2023), which collects the transcription factor–gene interactions of RegulonDB: 201 transcription factors and 1773 nodes in all, joined by 4170 edges. A regulator encoded by several genes, such as the complex FlhDC, is a single node (see tools/make_trn.py). We count two three-node patterns: feed-forward loops (FFLs), in which \(X\) regulates \(Y\), and both regulate \(Z\), and feedback loops, \(X \rightarrow Y \rightarrow Z \rightarrow X\). Both are easy to count from the adjacency matrix: the number of FFLs is \(\sum_{ij} a_{ij}(\mathbf{A}^2)_{ij}\), and the number of feedback loops is \(\text{tr}(\mathbf{A}^3)/3\). To decide whether a pattern is a motif, we compare its count with 20 randomised networks, in which every node keeps its in- and out-degree (§3.4.1).

Core MATLAB only.

%% Network motifs in the E. coli transcriptional regulatory network
% A motif is a small pattern of interactions that occurs far more often in
% a real network than in randomised networks with the same degrees (book
% §3.4). We count two three-node patterns in the network of transcription
% factors and their targets (data/ecoli_trn.csv, from RegulonDB via
% PRECISE-1K):
%   feed-forward loop (FFL)   X -> Y, Y -> Z and X -> Z
%   feedback loop (FBL)       X -> Y, Y -> Z and Z -> X
% With A the adjacency matrix (no self-loops), the number of FFLs is
% sum(A .* (A A)), and the number of FBLs is trace(A^3) / 3. We compare
% the counts with 20 randomised networks that keep every node's in- and
% out-degree (book §3.4.1), and classify FFLs as coherent or incoherent
% from the signs of their edges. Random choices come from sbp.uniform, so
% that MATLAB and Python make the same swaps.

trn = readtable(fullfile(sbp.data_dir(), 'ecoli_trn.csv'), ...
    'TextType', 'string');
names = unique([trn.regulator; trn.target]);      % sorted
n = numel(names);
[~, src] = ismember(trn.regulator, names);
[~, dst] = ismember(trn.target, names);
sgn = zeros(size(src));
sgn(trn.effect == "+") = 1;
sgn(trn.effect == "-") = -1;
auto = src == dst;
fprintf('%d nodes, %d edges; %d regulators regulate themselves\n', n, ...
    height(trn), sum(auto));
src = src(~auto); dst = dst(~auto); sgn = sgn(~auto);

[ffl, fbl] = motif_counts(src, dst, n);
random_counts = zeros(20, 2);
for s = 1:20
    [rs, rd] = randomise(src, dst, n, 100 + s, 10);
    [random_counts(s, 1), random_counts(s, 2)] = motif_counts(rs, rd, n);
end
mu = mean(random_counts, 1);
sd = std(random_counts, 0, 1);
z = ([ffl, fbl] - mu) ./ sd;

% Coherent FFLs: the sign of X -> Z equals the product of the signs of
% X -> Y and Y -> Z. For each FFL whose three signs are all known, the
% product of the three signs is +1 if it is coherent and -1 if not.
S = sparse(src, dst, sgn, n, n);                  % +1, -1, 0
K = abs(S);                                       % sign known
signed = full(sum((K * K) .* K, 'all'));          % FFLs with all signs known
product = full(sum((S * S) .* S, 'all'));         % sum of their sign products
coherent = round((signed + product) / 2);
incoherent = round((signed - product) / 2);

fprintf('Feed-forward loops: %d; randomised %.1f ± %.1f; Z = %.1f\n', ...
    ffl, mu(1), sd(1), z(1));
fprintf('Feedback loops:     %d; randomised %.1f ± %.1f; Z = %.1f\n', ...
    fbl, mu(2), sd(2), z(2));
fprintf('FFLs with all signs known: %d coherent, %d incoherent\n', ...
    coherent, incoherent);

%% Plot, with the same bins in both languages
fig = figure('Position', [100 100 900 400]);
labels = {'Feed-forward loops', 'Feedback loops'};
bin_edges = {550:50:900, -0.5:1:8.5};
real_counts = [ffl, fbl];
for k = 1:2
    subplot(1, 2, k); hold on
    h = histogram(random_counts(:, k), bin_edges{k}, ...
        'FaceColor', [0.000 0.447 0.698], 'FaceAlpha', 1, ...
        'EdgeColor', 'white');
    xline(real_counts(k), 'Color', [0.835 0.369 0.000], 'LineWidth', 2);
    yticks(0:max(h.Values))                       % whole-number ticks
    title(sprintf('%s (Z = %.1f)', labels{k}, z(k))); xlabel('Count')
    if k == 1
        ylabel('Randomised networks');
        legend({'randomised', 'E. coli'}, 'Location', 'north', ...
            'Box', 'off');
    end
end
sbp.save_figure(fig, mfilename('fullpath'), 'fig-motifs');

results.nodes = n;
results.edges = height(trn);
results.autoregulated = sum(auto);
results.ffl = ffl;
results.fbl = fbl;
results.random = random_counts;
results.z = z;
results.coherent = coherent;
results.incoherent = incoherent;
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function [ffl, fbl] = motif_counts(src, dst, n)
% Numbers of FFLs and FBLs.
A = sparse(src, dst, 1, n, n);
AA = A * A;
ffl = full(sum(AA .* A, 'all'));
fbl = round(full(trace(AA * A)) / 3);
end

function [src, dst] = randomise(src, dst, n, seed, swaps_per_edge)
% Swap targets between pairs of edges, a->b and c->d becoming a->d and
% c->b, unless that creates a self-loop or an existing edge.
m = numel(src);
A = false(n);
A(sub2ind([n, n], src, dst)) = true;
u = sbp.uniform(seed, 2 * swaps_per_edge * m);
for t = 0:swaps_per_edge * m - 1
    e1 = floor(u(2 * t + 1) * m) + 1;
    e2 = floor(u(2 * t + 2) * m) + 1;
    a = src(e1); b = dst(e1); c = src(e2); d = dst(e2);
    if a == d || c == b || b == d || A(a, d) || A(c, b)
        continue
    end
    A(a, b) = false; A(c, d) = false;
    A(a, d) = true; A(c, b) = true;
    dst(e1) = d; dst(e2) = b;
end
end

Needs SciPy.

"""Network motifs in the E. coli transcriptional regulatory network.

A motif is a small pattern of interactions that occurs far more often in
a real network than in randomised networks with the same degrees (book
§3.4). We count two three-node patterns in the network of transcription
factors and their targets (data/ecoli_trn.csv, from RegulonDB via
PRECISE-1K):
  feed-forward loop (FFL)   X -> Y, Y -> Z and X -> Z
  feedback loop (FBL)       X -> Y, Y -> Z and Z -> X
With A the adjacency matrix (no self-loops), the number of FFLs is
sum(A .* (A A)), and the number of FBLs is trace(A^3) / 3. We compare
the counts with 20 randomised networks that keep every node's in- and
out-degree (book §3.4.1), and classify FFLs as coherent or incoherent
from the signs of their edges. Random choices come from sbp.uniform, so
that MATLAB and Python make the same swaps.
"""
import numpy as np
import pandas as pd
from scipy import sparse
import matplotlib.pyplot as plt
import sbp

trn = pd.read_csv(sbp.DATA / "ecoli_trn.csv")
names = np.unique(trn[["regulator", "target"]].to_numpy())
index = {name: i for i, name in enumerate(names)}
n = len(names)
src = trn["regulator"].map(index).to_numpy()
dst = trn["target"].map(index).to_numpy()
sign = trn["effect"].map({"+": 1, "-": -1}).fillna(0).to_numpy()
auto = src == dst
print(f"{n} nodes, {len(trn)} edges; {auto.sum()} regulators regulate "
      "themselves")
src, dst, sign = src[~auto], dst[~auto], sign[~auto]


def counts(src, dst):
    """Numbers of FFLs and FBLs."""
    A = sparse.csr_matrix((np.ones(len(src)), (src, dst)), shape=(n, n))
    AA = A @ A
    fbl = int(round((AA @ A).diagonal().sum() / 3))
    return int(AA.multiply(A).sum()), fbl


def randomise(src, dst, seed, swaps_per_edge=10):
    """Swap targets between pairs of edges, a->b and c->d becoming a->d
    and c->b, unless that creates a self-loop or an existing edge."""
    src, dst = src.copy(), dst.copy()
    m = len(src)
    A = np.zeros((n, n), dtype=bool)
    A[src, dst] = True
    u = sbp.uniform(seed, 2 * swaps_per_edge * m)
    for t in range(swaps_per_edge * m):
        e1, e2 = int(u[2 * t] * m), int(u[2 * t + 1] * m)
        a, b, c, d = src[e1], dst[e1], src[e2], dst[e2]
        if a == d or c == b or b == d or A[a, d] or A[c, b]:
            continue
        A[a, b] = A[c, d] = False
        A[a, d] = A[c, b] = True
        dst[e1], dst[e2] = d, b
    return src, dst


ffl, fbl = counts(src, dst)
random_counts = np.array([counts(*randomise(src, dst, 100 + s))
                          for s in range(1, 21)])
mean, sd = random_counts.mean(axis=0), random_counts.std(axis=0, ddof=1)
z = (np.array([ffl, fbl]) - mean) / sd

# Coherent FFLs: the sign of X -> Z equals the product of the signs of
# X -> Y and Y -> Z. For each FFL whose three signs are all known, the
# product of the three signs is +1 if it is coherent and -1 if not.
S = sparse.csr_matrix((sign, (src, dst)), shape=(n, n))       # +1, -1, 0
K = abs(S)                                                    # sign known
signed = (K @ K).multiply(K).sum()          # FFLs with all signs known
product = (S @ S).multiply(S).sum()         # sum of their sign products
coherent = int(round((signed + product) / 2))
incoherent = int(round((signed - product) / 2))

print(f"Feed-forward loops: {ffl}; randomised {mean[0]:.1f} ± {sd[0]:.1f}; "
      f"Z = {z[0]:.1f}")
print(f"Feedback loops:     {fbl}; randomised {mean[1]:.1f} ± {sd[1]:.1f}; "
      f"Z = {z[1]:.1f}")
print(f"FFLs with all signs known: {coherent} coherent, {incoherent} "
      "incoherent")

# --- Plot, with the same bins in both languages
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
labels = ("Feed-forward loops", "Feedback loops")
bin_edges = (np.arange(550, 901, 50), np.arange(-0.5, 9))
for k, ax in enumerate(axes):
    ax.hist(random_counts[:, k], bins=bin_edges[k], color="#0072B2",
            edgecolor="white", label="randomised")
    ax.axvline([ffl, fbl][k], color="#D55E00", lw=2, label="E. coli")
    ax.locator_params(integer=True)                 # whole-number ticks
    ax.set_title(f"{labels[k]} (Z = {z[k]:.1f})")
    ax.set_xlabel("Count")
axes[0].set_ylabel("Randomised networks")
axes[0].legend(loc="upper center", frameon=False)
sbp.save_figure(fig, __file__, "fig-motifs")

sbp.save_results(__file__, {
    "nodes": n, "edges": len(trn), "autoregulated": int(auto.sum()),
    "ffl": ffl, "fbl": fbl, "random": random_counts, "z": z,
    "coherent": coherent, "incoherent": incoherent,
})
sbp.show()

The network has 1996 feed-forward loops, against \(761 \pm 100\) in the randomised networks: a \(Z\)-score of 12, and a clear motif, as Shen-Orr et al. first showed (Shen-Orr et al. 2002). Of the FFLs whose three edges all have known signs, 907 are coherent (the direct path from \(X\) to \(Z\) has the same sign as the indirect one, through \(Y\)) and 603 incoherent; recall from the book that the two types have quite different dynamics, a sign-sensitive delay and a pulse generator, respectively. Feedback loops, on the other hand, are rare: only 12, although this is still more than in the randomised networks. In E. coli, feedback is mostly found elsewhere: 127 regulators regulate their own genes, most of them negatively.

3.4.1 Randomising networks

Each step of the randomisation takes two edges, \(a \rightarrow b\) and \(c \rightarrow d\), and swaps their targets, to give \(a \rightarrow d\) and \(c \rightarrow b\), unless this creates a self-loop or an edge that already exists. Every node thus keeps both its in-degree and its out-degree. Ten attempted swaps per edge are usually enough to randomise a network thoroughly. The undirected version, which swaps the ends of two edges in the same way, is used for the assortativity example of §3.1.3. In both, the random numbers come from sbp.uniform, so that MATLAB and Python produce exactly the same randomised networks.

3.5 Perturbations to networks

3.5.1 Quantifying effects of perturbation

The size of the largest connected component is perhaps the simplest measure of the integrity of a network, and the one we follow in the example below (§3.5.2).

3.5.2 Network structure and attack strategies

We remove an increasing fraction of the proteins of the E. coli STRING network, either at random (failures), or in decreasing order of their degree (an attack on the hubs), and compare it with an Erdős–Rényi graph with the same numbers of nodes and edges. Once again, sbp.uniform makes the random choices identical in both languages.

Core MATLAB only.

%% Robustness of a network to random failures and targeted attacks
% We remove an increasing fraction of the nodes of the E. coli STRING
% network (combined score at least 700), and follow the size of the
% largest connected component (book §3.5.1). Nodes are removed either in
% random order (failures) or in decreasing order of their degree in the
% intact network (an attack on the hubs; ties broken by name). The random
% order comes from sbp.uniform, so that it is the same in MATLAB and
% Python. For comparison, we do the same for an Erdős–Rényi random graph
% with the same numbers of nodes and edges, also drawn with sbp.uniform.

T = readtable(fullfile(sbp.data_dir(), 'ecoli_string_ppi.csv'), ...
    'TextType', 'string');
names = unique([T.protein1; T.protein2]);         % sorted
[~, ia] = ismember(T.protein1, names);
[~, ib] = ismember(T.protein2, names);
edges = [ia, ib];
n = numel(names); m = size(edges, 1);

steps = 0:19;                                     % remove 0%, 5%, ..., 95%
fractions = steps / 20;
counts = floor(steps * n / 20);                   % whole numbers of nodes
results.fractions = fractions;
labels = {'string', 'random_graph'};
networks = {edges, er_graph(n, m, 7)};
for net = 1:2
    e = networks{net};
    degree = accumarray(e(:), 1, [n, 1]);
    [~, by_degree] = sortrows([-degree, (1:n)']);  % ties: by name
    [~, random_order] = sort(sbp.uniform(2024, n));
    orders = {by_degree, random_order};
    strategies = {'attack', 'failure'};
    for s = 1:2
        curve = zeros(1, numel(counts));
        for c = 1:numel(counts)
            curve(c) = giant_fraction(e, n, orders{s}(1:counts(c)));
        end
        results.(labels{net}).(strategies{s}) = curve;
    end
    r = results.(labels{net});
    fprintf(['%s: largest component after removing 20%%, 50%%, 70%% of ' ...
        'nodes: failures %.2f, %.2f, %.2f; attack %.2f, %.2f, %.2f\n'], ...
        labels{net}, r.failure([5, 11, 15]), r.attack([5, 11, 15]));
end

%% Plot
fig = figure('Position', [100 100 600 450]); hold on
blue = [0.000 0.447 0.698]; red = [0.835 0.369 0.000];
styles = {'string', 'failure', blue, '-'; 'string', 'attack', red, '-';
          'random_graph', 'failure', blue, ':';
          'random_graph', 'attack', red, ':'};
for k = 1:4
    plot(fractions, results.(styles{k, 1}).(styles{k, 2}), styles{k, 4}, ...
        'Color', styles{k, 3}, 'Marker', 'o', 'MarkerSize', 3, ...
        'MarkerFaceColor', styles{k, 3});
end
legend({'STRING, failure', 'STRING, attack', 'random graph, failure', ...
    'random graph, attack'}, 'Box', 'off');
xlabel('Fraction of nodes removed');
ylabel('Largest component (fraction of nodes)'); box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-attacks');

sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function e = er_graph(n, m, seed)
% m distinct random edges among n nodes (Erdős–Rényi G(n, m)).
u = sbp.uniform(seed, 4 * m);
A = false(n);
e = zeros(m, 2);
found = 0; k = 1;
while found < m
    a = floor(u(k) * n) + 1; b = floor(u(k + 1) * n) + 1;
    k = k + 2;
    if a ~= b && ~A(min(a, b), max(a, b))
        A(min(a, b), max(a, b)) = true;
        found = found + 1;
        e(found, :) = [min(a, b), max(a, b)];
    end
end
e = sortrows(e);
end

function f = giant_fraction(e, n, removed)
% Size of the largest component, as a fraction of all n nodes.
G = graph(e(:, 1), e(:, 2), [], n);
G = rmnode(G, removed);
if numnodes(G) == 0, f = 0; return; end
f = max(accumarray(conncomp(G)', 1)) / n;
end

Needs NetworkX.

"""Robustness of a network to random failures and targeted attacks.

We remove an increasing fraction of the nodes of the E. coli STRING
network (combined score at least 700), and follow the size of the
largest connected component (book §3.5.1). Nodes are removed either in
random order (failures) or in decreasing order of their degree in the
intact network (an attack on the hubs; ties broken by name). The random
order comes from sbp.uniform, so that it is the same in MATLAB and
Python. For comparison, we do the same for an Erdős–Rényi random graph
with the same numbers of nodes and edges, also drawn with sbp.uniform.
"""
import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import sbp

table = pd.read_csv(sbp.DATA / "ecoli_string_ppi.csv")
table = table[["protein1", "protein2"]]
names = np.unique(table.to_numpy())
index = {name: i for i, name in enumerate(names)}
edges = np.array([[index[a], index[b]] for a, b in table.to_numpy()])
n, m = len(names), len(edges)


def er_graph(n, m, seed):
    """m distinct random edges among n nodes (Erdős–Rényi G(n, m))."""
    u = sbp.uniform(seed, 4 * m)
    chosen, k = set(), 0
    while len(chosen) < m:
        a, b = int(u[k] * n), int(u[k + 1] * n)
        k += 2
        if a != b:
            chosen.add((min(a, b), max(a, b)))
    return np.array(sorted(chosen))


def giant_fraction(edges, n, removed):
    """Size of the largest component, as a fraction of all n nodes."""
    G = nx.Graph()
    G.add_nodes_from(range(n))
    G.add_edges_from(edges)
    G.remove_nodes_from(removed)
    return max((len(c) for c in nx.connected_components(G)), default=0) / n


steps = np.arange(20)                       # remove 0%, 5%, ..., 95%
fractions = steps / 20
counts = steps * n // 20                    # whole numbers of nodes
results = {"fractions": fractions}
for label, e in (("string", edges), ("random_graph", er_graph(n, m, 7))):
    degree = np.bincount(e.ravel(), minlength=n)
    by_degree = np.lexsort((np.arange(n), -degree))   # ties: by name
    random_order = np.argsort(sbp.uniform(2024, n))
    curves = {}
    for strategy, order in (("attack", by_degree), ("failure", random_order)):
        curves[strategy] = [giant_fraction(e, n, order[:c]) for c in counts]
    results[label] = curves
    print(f"{label}: largest component after removing 20%, 50%, 70% of nodes:"
          f" failures {curves['failure'][4]:.2f}, {curves['failure'][10]:.2f},"
          f" {curves['failure'][14]:.2f}; attack {curves['attack'][4]:.2f}, "
          f"{curves['attack'][10]:.2f}, {curves['attack'][14]:.2f}")

# --- Plot
sbp.style()
fig, ax = plt.subplots(figsize=(6, 4.5))
styles = {("string", "failure"): ("#0072B2", "-"),
          ("string", "attack"): ("#D55E00", "-"),
          ("random_graph", "failure"): ("#0072B2", ":"),
          ("random_graph", "attack"): ("#D55E00", ":")}
titles = {"string": "STRING", "random_graph": "random graph"}
for (network, strategy), (colour, ls) in styles.items():
    ax.plot(fractions, results[network][strategy], ls, color=colour,
            marker="o", ms=3, label=f"{titles[network]}, {strategy}")
ax.set_xlabel("Fraction of nodes removed")
ax.set_ylabel("Largest component (fraction of nodes)")
ax.legend(frameon=False, fontsize=9)
sbp.save_figure(fig, __file__, "fig-attacks")

sbp.save_results(__file__, results)
sbp.show()

Both networks hold together remarkably well under random failures: the largest component simply shrinks with the number of nodes removed. Under attack, the STRING network survives the loss of a surprising number of hubs, because it is dense (each protein has 16 partners on average), but it collapses once about 60% of its proteins are gone; the random graph lasts until about 80%. The difference is the heterogeneity of the degrees: in the STRING network, the hubs hold together much more of the network than they do in a random graph. In sparser networks, such as the Internet and the World Wide Web studied by Albert, Jeong and Barabási (Albert et al. 2000), the collapse under attack comes much earlier.

3.6 Troubleshooting

3.6.1 Is your network really scale-free?

Plotting the fraction of nodes with degree at least \(k\) (right panel of the figure in §3.2.3), in place of the fraction with degree exactly \(k\), avoids most of the noise in the tail, where only one or two nodes have each degree. Even so, deciding whether a real network is truly scale-free from a straight-looking line on a log–log plot is risky; the book discusses better tests (§3.6.1).

3.7 Software tools

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

Exercises

  1. Remove node E from the example network. Recompute all the parameters. What happens to the diameter, and why do the shortest-path functions report infinite distances?
  2. Generate Erdős–Rényi networks with \(n = 1000\) and mean degree from 0.2 to 3. Plot the size of the largest connected component (conncomp in MATLAB, nx.connected_components in Python) against the mean degree. What happens at a mean degree of 1?
  3. For the scale-free network, remove nodes one at a time, either at random or in order of decreasing degree, and track the size of the largest connected component. Repeat for the Erdős–Rényi network. Which network is more robust to random failures, and which to targeted attack (book, §3.5.2 and Exercise 3.13)?
  4. Download a biological network, for example a protein interaction network from https://networkrepository.com/, and compute its degree distribution, mean clustering coefficient and characteristic path length. Compare them with an Erdős–Rényi network with the same numbers of nodes and edges. (This is the second problem of the BT5240 network assignment.)
  5. The book’s code repository has a function barabasi_albert.m for \(m = 1\). What kind of network does it always produce, and why is its clustering coefficient zero (book Exercise 3.10)?
  6. Book Exercise 3.11: is the clustering coefficient of the E. coli STRING network used in Chapter 4 (data/ecoli_string_ppi.csv) high? Compare it with Erdős–Rényi networks of the same size, and with randomised networks that keep every node’s degree (book, §3.4.1).
  7. Check the code of the first example against the worked values in the book: build the networks of book Figure 3.1 and compare their clustering coefficients (Eq. 3.9), diameters and characteristic path lengths with those given in §3.1.1.

Going further

Chapter 4 of the book applies these ideas to biological questions, from predicting essential genes to finding disease modules; Chapter 4 works through several of them in code.