Tutorial 3: Network Topologies#
This tutorial covers the graph-style connectivity generators in braintools.conn: small-world, scale-free, regular random, modular, hierarchical, and core-periphery networks.
The examples use current ConnectionResult conventions:
call connectors with
pre_size=andpost_size=use
result.n_connectionsandresult.shapeuse
result.weight2dense()for matrix visualizationread topology-specific settings from
result.metadataseed stochastic connectors for reproducible tutorials
Several topological connectors require square recurrent populations. Equivalent tuple and integer sizes are accepted when they have the same flattened size, for example pre_size=(10, 10) and post_size=100.
1. Imports#
from collections import deque
import brainunit as u
import matplotlib.pyplot as plt
import numpy as np
from braintools import conn, visualize as vis
from braintools.init import Constant, Normal
rng = np.random.default_rng(42)
plt.rcParams["figure.figsize"] = (12, 4)
plt.rcParams["font.size"] = 10
print("Imports successful")
Imports successful
2. Helper Functions#
The helpers below keep graph summaries and visualizations consistent across topology types.
def as_plain(values):
"""Return a NumPy array of mantissas for arrays or brainunit quantities."""
return np.asarray(u.get_mantissa(values))
def topology_matrix(result):
"""Dense binary adjacency matrix from a ConnectionResult."""
return (as_plain(result.weight2dense()) != 0).astype(float)
def in_degrees(result):
return np.bincount(result.post_indices, minlength=result.shape[1])
def out_degrees(result):
return np.bincount(result.pre_indices, minlength=result.shape[0])
def total_degrees(result):
return in_degrees(result) + out_degrees(result)
def summarize_result(name, result):
"""Print compact topology information."""
print(name)
print("=" * len(name))
print(f"shape: {result.shape}")
print(f"connections: {result.n_connections}")
print(f"mean out-degree: {np.mean(out_degrees(result)):.2f}")
print(f"mean in-degree: {np.mean(in_degrees(result)):.2f}")
print(f"self-connections: {int(np.sum(result.pre_indices == result.post_indices))}")
if result.weights is not None and u.math.size(result.weights) > 0:
print(f"weight mean: {u.math.mean(result.weights):.3f}")
print(f"metadata: {result.metadata}")
def labels_from_sizes(sizes):
"""Assign sequential labels from group sizes."""
return np.repeat(np.arange(len(sizes)), sizes)
def balanced_sizes(n, groups):
"""Balanced partition used by ModularRandom when n is not exactly divisible."""
base = n // groups
remainder = n % groups
return [base + (1 if group < remainder else 0) for group in range(groups)]
def block_density_matrix(result, labels):
"""Connection density between label groups."""
labels = np.asarray(labels)
n_groups = int(labels.max()) + 1
counts = np.zeros((n_groups, n_groups), dtype=int)
sizes = np.bincount(labels, minlength=n_groups)
for pre, post in zip(result.pre_indices, result.post_indices):
counts[labels[pre], labels[post]] += 1
possible = np.outer(sizes, sizes)
for group in range(n_groups):
possible[group, group] -= sizes[group]
with np.errstate(divide="ignore", invalid="ignore"):
density = np.divide(counts, possible, out=np.zeros_like(counts, dtype=float), where=possible > 0)
return density, counts, possible
def print_block_density(title, density):
print(title)
for row in density:
print(" " + " ".join(f"{value:0.3f}" for value in row))
3. Small-World Networks#
SmallWorld implements a Watts-Strogatz-style directed topology. It starts from a ring lattice where each source has exactly k outgoing edges and rewires each edge with probability p.
Current constraints:
kmust be positive, even, and smaller than the network sizethe generated result has exactly
n * kdirected edgesself-connections and duplicate edges are avoided
changing
pchanges shortcut placement but preserves the edge count
n_neurons = 500
small_world = conn.SmallWorld(
k=10,
p=0.1,
weight=Constant(1.0 * u.nS),
seed=42,
)
small_world_result = small_world(pre_size=n_neurons, post_size=n_neurons)
summarize_result("SmallWorld(k=10, p=0.1)", small_world_result)
print(f"expected directed edges: {n_neurons * 10}")
sparse_weights = small_world_result.weight2csr()
print(f"CSR shape: {sparse_weights.shape}")
print(f"CSR nonzeros: {len(sparse_weights.indices)}")
SmallWorld(k=10, p=0.1)
=======================
shape: (500, 500)
connections: 5000
mean out-degree: 10.00
mean in-degree: 10.00
self-connections: 0
weight mean: 1.000 nS
metadata: {'pattern': 'small_world', 'k': 10, 'p': 0.1}
expected directed edges: 5000
CSR shape: (500, 500)
CSR nonzeros: 5000
Rewiring Probability#
Out-degree remains exactly k for every source. In-degree varies more as p increases because rewired targets are no longer purely local.
rewiring_probs = [0.0, 0.05, 0.1, 0.3, 0.5, 1.0]
n_test = 200
small_world_by_p = {}
print("Rewiring probability effects")
print("=" * 72)
print(f"{'p':<8} {'edges':<10} {'out-degree range':<20} {'in-degree std':<14}")
print("=" * 72)
for p in rewiring_probs:
sample = conn.SmallWorld(k=6, p=p, seed=42)(pre_size=n_test, post_size=n_test)
small_world_by_p[p] = sample
out_deg = out_degrees(sample)
in_deg = in_degrees(sample)
print(f"{p:<8.2f} {sample.n_connections:<10} {out_deg.min()}..{out_deg.max():<16} {np.std(in_deg):<14.3f}")
Rewiring probability effects
========================================================================
p edges out-degree range in-degree std
========================================================================
0.00 1200 6..6 0.000
0.05 1200 6..6 0.742
0.10 1200 6..6 1.082
0.30 1200 6..6 1.778
0.50 1200 6..6 1.965
1.00 1200 6..6 2.278
fig, axes = plt.subplots(2, 3, figsize=(16, 9))
axes = axes.ravel()
for ax, p in zip(axes, rewiring_probs):
in_deg = in_degrees(small_world_by_p[p])
vis.distribution_plot(
in_deg,
bins=15,
density=False,
alpha=0.7,
colors=["tab:blue"],
edgecolor="black",
ax=ax,
xlabel="in-degree",
ylabel="neuron count",
title=f"p = {p:.2f}",
)
plt.suptitle("SmallWorld in-degree distributions", fontsize=14, y=1.00)
plt.tight_layout()
plt.show()
4. Scale-Free Networks#
ScaleFree implements a Barabasi-Albert preferential-attachment model. Each new node attaches to m existing nodes, and each undirected attachment is represented as two directed edges in the result.
Current constraints:
mmust satisfy1 <= m < npre_sizeandpost_sizemust have the same flattened sizehub nodes appear as high total-degree nodes
scale_free = conn.ScaleFree(
m=3,
weight=Constant(1.0 * u.nS),
seed=42,
)
scale_free_result = scale_free(pre_size=n_neurons, post_size=n_neurons)
sf_total_degree = total_degrees(scale_free_result)
top_hubs = sorted(
[(int(node), int(degree)) for node, degree in enumerate(sf_total_degree)],
key=lambda item: item[1],
reverse=True,
)[:5]
summarize_result("ScaleFree(m=3)", scale_free_result)
print(f"approx undirected attachments: {scale_free_result.n_connections // 2}")
print(f"top 5 hubs: {top_hubs}")
ScaleFree(m=3)
==============
shape: (500, 500)
connections: 2988
mean out-degree: 5.98
mean in-degree: 5.98
self-connections: 0
weight mean: 1.000 nS
metadata: {'pattern': 'scale_free', 'm': 3}
approx undirected attachments: 1494
top 5 hubs: [(0, 188), (1, 148), (2, 130), (3, 108), (15, 64)]
sw_in_degree = in_degrees(small_world_result)
sf_in_degree = in_degrees(scale_free_result)
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
for ax, label, degrees, color in [
(axes[0], "SmallWorld", sw_in_degree, "tab:blue"),
(axes[1], "ScaleFree", sf_in_degree, "tab:orange"),
]:
vis.distribution_plot(
degrees,
bins=25,
density=False,
alpha=0.7,
colors=[color],
edgecolor="black",
ax=ax,
xlabel="in-degree",
ylabel="neuron count",
title=label,
)
plt.tight_layout()
plt.show()
print(f"SmallWorld in-degree CV: {np.std(sw_in_degree) / np.mean(sw_in_degree):.3f}")
print(f"ScaleFree in-degree CV: {np.std(sf_in_degree) / np.mean(sf_in_degree):.3f}")
SmallWorld in-degree CV: 0.138
ScaleFree in-degree CV: 1.208
nonzero_total_degree = sf_total_degree[sf_total_degree > 0]
unique_degree, degree_count = np.unique(nonzero_total_degree, return_counts=True)
fig, ax = plt.subplots(figsize=(9, 6))
ax.loglog(unique_degree, degree_count, "o", markersize=7, alpha=0.75, color="tab:orange")
x_ref = np.array([unique_degree.min(), unique_degree.max()])
y_ref = degree_count.max() * (x_ref / x_ref[0]) ** -2
ax.loglog(x_ref, y_ref, "--", color="gray", linewidth=2, alpha=0.6, label="slope -2 reference")
ax.set_xlabel("total degree")
ax.set_ylabel("node count")
ax.set_title("ScaleFree total-degree distribution")
ax.grid(True, alpha=0.3, which="both")
ax.legend()
plt.tight_layout()
plt.show()
5. Regular Random and Local Ring Networks#
Regular(degree=...) creates a random network with fixed out-degree. It does not create a local ring lattice, and it does not guarantee fixed in-degree. Use Ring for local banded ring structure.
regular = conn.Regular(
degree=8,
weight=Constant(1.0 * u.nS),
seed=42,
)
regular_result = regular(pre_size=200, post_size=200)
regular_out = out_degrees(regular_result)
regular_in = in_degrees(regular_result)
summarize_result("Regular(degree=8)", regular_result)
print(f"all out-degrees equal 8: {bool(np.all(regular_out == 8))}")
print(f"in-degree range: {regular_in.min()}..{regular_in.max()}")
Regular(degree=8)
=================
shape: (200, 200)
connections: 1600
mean out-degree: 8.00
mean in-degree: 8.00
self-connections: 0
weight mean: 1.000 nS
metadata: {'pattern': 'regular', 'degree': 8}
all out-degrees equal 8: True
in-degree range: 2..15
n_viz = 40
ring_viz = conn.Ring(neighbors=2, seed=42)(pre_size=n_viz, post_size=n_viz)
sw_viz = conn.SmallWorld(k=4, p=0.1, seed=42)(pre_size=n_viz, post_size=n_viz)
regular_viz = conn.Regular(degree=4, seed=42)(pre_size=n_viz, post_size=n_viz)
random_viz = conn.Random(prob=4 / (n_viz - 1), seed=42)(pre_size=n_viz, post_size=n_viz)
fig, axes = plt.subplots(1, 4, figsize=(18, 4.5))
for ax, sample, title in [
(axes[0], ring_viz, "Ring neighbors=2"),
(axes[1], sw_viz, "SmallWorld k=4"),
(axes[2], regular_viz, "Regular degree=4"),
(axes[3], random_viz, "Random matched density"),
]:
vis.connectivity_matrix(
topology_matrix(sample),
cmap="binary",
center_zero=False,
show_colorbar=False,
ax=ax,
title=title,
)
plt.tight_layout()
plt.show()
6. Modular Networks#
ModularRandom divides neurons into balanced sequential modules and uses separate probabilities for within-module and between-module pairs. Self-connections are excluded.
modular = conn.ModularRandom(
n_modules=4,
intra_prob=0.30,
inter_prob=0.02,
weight=Constant(1.0 * u.nS),
seed=42,
)
modular_result = modular(pre_size=400, post_size=400)
module_sizes_balanced = balanced_sizes(400, 4)
module_labels = labels_from_sizes(module_sizes_balanced)
modular_density, _, _ = block_density_matrix(modular_result, module_labels)
summarize_result("ModularRandom", modular_result)
print(f"balanced module sizes: {module_sizes_balanced}")
print_block_density("block densities", modular_density)
ModularRandom
=============
shape: (400, 400)
connections: 14189
mean out-degree: 35.47
mean in-degree: 35.47
self-connections: 0
weight mean: 1.000 nS
metadata: {'pattern': 'modular', 'n_modules': 4, 'intra_prob': 0.3, 'inter_prob': 0.02}
balanced module sizes: [100, 100, 100, 100]
block densities
0.295 0.020 0.020 0.019
0.018 0.301 0.021 0.020
0.019 0.019 0.301 0.020
0.019 0.022 0.018 0.299
ModularGeneral With Unequal Module Sizes#
ModularGeneral uses connector objects for each module and each optional inter-module pair. To request unequal module sizes, pass module_ratios for the first n_modules - 1 modules; the final module receives the remaining neurons.
module_sizes = [80, 120, 100, 100]
prob_matrix = np.array([
[0.40, 0.05, 0.02, 0.01],
[0.05, 0.30, 0.10, 0.02],
[0.02, 0.10, 0.35, 0.05],
[0.01, 0.02, 0.05, 0.25],
])
intra_connectors = [
conn.Random(prob=float(prob_matrix[i, i]), seed=100 + i)
for i in range(len(module_sizes))
]
inter_connectors = {
(i, j): conn.Random(prob=float(prob_matrix[i, j]), seed=200 + 10 * i + j)
for i in range(len(module_sizes))
for j in range(len(module_sizes))
if i != j and prob_matrix[i, j] > 0
}
modular_general = conn.ModularGeneral(
intra_conn=intra_connectors,
inter_conn_pair=inter_connectors,
module_ratios=module_sizes[:-1],
)
modular_general_result = modular_general(pre_size=sum(module_sizes), post_size=sum(module_sizes))
custom_labels = labels_from_sizes(modular_general_result.metadata["module_sizes"])
custom_density, _, _ = block_density_matrix(modular_general_result, custom_labels)
summarize_result("ModularGeneral unequal modules", modular_general_result)
print(f"requested module sizes: {module_sizes}")
print(f"actual module sizes: {modular_general_result.metadata['module_sizes']}")
print_block_density("realized block densities", custom_density)
ModularGeneral unequal modules
==============================
shape: (400, 400)
connections: 17813
mean out-degree: 44.53
mean in-degree: 44.53
self-connections: 0
metadata: {'pattern': 'modular_general', 'n_modules': 4, 'module_sizes': [80, 120, 100, 100], 'module_ratios': [80, 120, 100], 'inter_conn': None, 'inter_conn_pair': {(0, 1): 'Random', (0, 2): 'Random', (0, 3): 'Random', (1, 0): 'Random', (1, 2): 'Random', (1, 3): 'Random', (2, 0): 'Random', (2, 1): 'Random', (2, 3): 'Random', (3, 0): 'Random', (3, 1): 'Random', (3, 2): 'Random'}, 'intra_conn': ['Random', 'Random', 'Random', 'Random']}
requested module sizes: [80, 120, 100, 100]
actual module sizes: [80, 120, 100, 100]
realized block densities
0.400 0.047 0.020 0.010
0.048 0.300 0.101 0.020
0.016 0.099 0.346 0.051
0.007 0.019 0.049 0.239
modular_viz = conn.ModularRandom(
n_modules=4,
intra_prob=0.4,
inter_prob=0.05,
seed=42,
)(pre_size=120, post_size=120)
modular_matrix = topology_matrix(modular_viz)
fig, ax = plt.subplots(figsize=(8, 7))
vis.connectivity_matrix(
modular_matrix,
cmap="binary",
center_zero=False,
show_colorbar=False,
ax=ax,
title="ModularRandom matrix, 4 balanced modules",
)
for boundary in [30, 60, 90]:
ax.axhline(boundary, color="tab:red", linewidth=1.8, alpha=0.7)
ax.axvline(boundary, color="tab:red", linewidth=1.8, alpha=0.7)
plt.tight_layout()
plt.show()
7. Hierarchical Networks#
HierarchicalRandom organizes neurons into sequential levels. Adjacent upward connections use feedforward_prob, adjacent downward connections use feedback_prob, within-level connections use recurrent_prob, and forward non-adjacent skip connections use skip_prob.
level_ratios follows the same convention as module_ratios: provide the first n_levels - 1 sizes or proportions, and the last level receives the remainder.
hierarchical = conn.HierarchicalRandom(
n_levels=4,
level_ratios=[0.40, 0.30, 0.20],
feedforward_prob=0.30,
feedback_prob=0.10,
recurrent_prob=0.20,
skip_prob=0.03,
weight=Constant(1.0 * u.nS),
seed=42,
)
hierarchical_result = hierarchical(pre_size=300, post_size=300)
level_labels = labels_from_sizes(hierarchical_result.metadata["level_sizes"])
hierarchical_density, _, _ = block_density_matrix(hierarchical_result, level_labels)
summarize_result("HierarchicalRandom", hierarchical_result)
print(f"level sizes: {hierarchical_result.metadata['level_sizes']}")
print_block_density("level-to-level densities", hierarchical_density)
HierarchicalRandom
==================
shape: (300, 300)
connections: 12848
mean out-degree: 42.83
mean in-degree: 42.83
self-connections: 0
weight mean: 1.000 nS
metadata: {'pattern': 'hierarchical', 'n_levels': 4, 'level_sizes': [120, 90, 60, 30], 'level_ratios': [0.4, 0.3, 0.2], 'feedforward_prob': 0.3, 'feedback_prob': 0.1, 'recurrent_prob': 0.2, 'skip_prob': 0.03}
level sizes: [120, 90, 60, 30]
level-to-level densities
0.200 0.293 0.030 0.030
0.101 0.197 0.304 0.026
0.000 0.093 0.197 0.314
0.000 0.000 0.093 0.229
hierarchical_viz = conn.HierarchicalRandom(
n_levels=4,
feedforward_prob=0.4,
feedback_prob=0.15,
recurrent_prob=0.3,
skip_prob=0.04,
seed=42,
)(pre_size=120, post_size=120)
hierarchical_matrix = topology_matrix(hierarchical_viz)
fig, ax = plt.subplots(figsize=(8, 7))
vis.connectivity_matrix(
hierarchical_matrix,
cmap="binary",
center_zero=False,
show_colorbar=False,
ax=ax,
title="HierarchicalRandom matrix, 4 levels",
)
for boundary in [30, 60, 90]:
ax.axhline(boundary, color="tab:blue", linewidth=1.8, alpha=0.7)
ax.axvline(boundary, color="tab:blue", linewidth=1.8, alpha=0.7)
plt.tight_layout()
plt.show()
8. Core-Periphery Networks#
CorePeripheryRandom uses independent probabilities for core-core, core-to-periphery, periphery-to-core, and periphery-periphery blocks. core_size can be an integer count or a float proportion in (0, 1).
core_periphery = conn.CorePeripheryRandom(
core_size=0.25,
core_core_prob=0.50,
core_periphery_prob=0.10,
periphery_core_prob=0.15,
periphery_periphery_prob=0.02,
weight=Constant(1.0 * u.nS),
seed=42,
)
core_periphery_result = core_periphery(pre_size=400, post_size=400)
core_size = core_periphery_result.metadata["core_size"]
core_labels = np.r_[np.zeros(core_size, dtype=int), np.ones(400 - core_size, dtype=int)]
core_density, _, _ = block_density_matrix(core_periphery_result, core_labels)
summarize_result("CorePeripheryRandom", core_periphery_result)
print_block_density("core/periphery block densities", core_density)
core_in = in_degrees(core_periphery_result)[:core_size]
periphery_in = in_degrees(core_periphery_result)[core_size:]
print(f"core mean in-degree: {np.mean(core_in):.1f}")
print(f"periphery mean in-degree: {np.mean(periphery_in):.1f}")
CorePeripheryRandom
===================
shape: (400, 400)
connections: 14203
mean out-degree: 35.51
mean in-degree: 35.51
self-connections: 0
weight mean: 1.000 nS
metadata: {'pattern': 'core_periphery', 'core_size': 100, 'core_core_prob': 0.5, 'core_periphery_prob': 0.1, 'periphery_core_prob': 0.15, 'periphery_periphery_prob': 0.02}
core/periphery block densities
0.496 0.102
0.148 0.020
core mean in-degree: 93.6
periphery mean in-degree: 16.2
cp_viz = conn.CorePeripheryRandom(
core_size=30,
core_core_prob=0.6,
core_periphery_prob=0.15,
periphery_core_prob=0.2,
periphery_periphery_prob=0.03,
seed=42,
)(pre_size=120, post_size=120)
cp_matrix = topology_matrix(cp_viz)
fig, ax = plt.subplots(figsize=(8, 7))
vis.connectivity_matrix(
cp_matrix,
cmap="binary",
center_zero=False,
show_colorbar=False,
ax=ax,
title="CorePeripheryRandom matrix",
)
ax.axhline(30, color="tab:red", linewidth=2.2, alpha=0.75)
ax.axvline(30, color="tab:red", linewidth=2.2, alpha=0.75)
plt.tight_layout()
plt.show()
9. Comparing Network Types#
The next examples compare degree distributions across several networks with roughly similar mean in-degree.
n_compare = 300
networks = {
"Ring": conn.Ring(neighbors=5, seed=42)(pre_size=n_compare, post_size=n_compare),
"SmallWorld": conn.SmallWorld(k=10, p=0.1, seed=42)(pre_size=n_compare, post_size=n_compare),
"Regular": conn.Regular(degree=10, seed=42)(pre_size=n_compare, post_size=n_compare),
"ScaleFree": conn.ScaleFree(m=5, seed=42)(pre_size=n_compare, post_size=n_compare),
"Random": conn.Random(prob=10 / (n_compare - 1), seed=42)(pre_size=n_compare, post_size=n_compare),
}
degree_by_name = {name: in_degrees(result) for name, result in networks.items()}
colors = {
"Ring": "tab:green",
"SmallWorld": "tab:blue",
"Regular": "tab:olive",
"ScaleFree": "tab:orange",
"Random": "gray",
}
fig, axes = plt.subplots(2, 3, figsize=(16, 9))
axes = axes.ravel()
for ax, (name, degrees) in zip(axes, degree_by_name.items()):
vis.distribution_plot(
degrees,
bins=25,
density=False,
alpha=0.7,
colors=[colors[name]],
edgecolor="black",
ax=ax,
xlabel="in-degree",
ylabel="neuron count",
title=name,
)
axes[-1].axis("off")
plt.tight_layout()
plt.show()
print("Topology comparison")
print("=" * 78)
print(f"{'network':<14} {'edges':<8} {'mean in':<10} {'std in':<10} {'CV':<8} {'max total':<10}")
print("=" * 78)
for name, result in networks.items():
in_deg = in_degrees(result)
total_deg = total_degrees(result)
mean_deg = np.mean(in_deg)
std_deg = np.std(in_deg)
cv = std_deg / mean_deg if mean_deg > 0 else 0.0
print(f"{name:<14} {result.n_connections:<8} {mean_deg:<10.2f} {std_deg:<10.2f} {cv:<8.3f} {int(total_deg.max()):<10}")
Topology comparison
==============================================================================
network edges mean in std in CV max total
==============================================================================
Ring 3000 10.00 0.00 0.000 20
SmallWorld 3000 10.00 1.39 0.139 24
Regular 3000 10.00 3.19 0.319 30
ScaleFree 2970 9.90 9.44 0.953 164
Random 2972 9.91 3.00 0.303 34
10. Worked Graph Analyses#
The following analyses use small set-based graph routines, avoiding an extra dependency such as NetworkX.
10.1 Small-World Transition#
def undirected_neighbors(result):
"""Build undirected adjacency sets from directed edges."""
n = result.shape[0]
neighbors = [set() for _ in range(n)]
for pre, post in zip(result.pre_indices, result.post_indices):
if pre == post:
continue
neighbors[int(pre)].add(int(post))
neighbors[int(post)].add(int(pre))
return neighbors
def mean_clustering_coefficient(result):
"""Average undirected local clustering coefficient."""
neighbors = undirected_neighbors(result)
coeffs = []
for nbrs in neighbors:
degree = len(nbrs)
if degree < 2:
coeffs.append(0.0)
continue
nbr_list = list(nbrs)
links = 0
for i, src in enumerate(nbr_list):
src_neighbors = neighbors[src]
for dst in nbr_list[i + 1:]:
if dst in src_neighbors:
links += 1
coeffs.append(links / (degree * (degree - 1) / 2))
return float(np.mean(coeffs))
def sampled_average_path_length(result, n_sources=25):
"""Average shortest path length from a deterministic source sample."""
neighbors = undirected_neighbors(result)
n = len(neighbors)
sources = np.linspace(0, n - 1, min(n_sources, n), dtype=int)
distances = []
for source in sources:
seen = {int(source): 0}
queue = deque([int(source)])
while queue:
node = queue.popleft()
for nbr in neighbors[node]:
if nbr not in seen:
seen[nbr] = seen[node] + 1
queue.append(nbr)
distances.extend(distance for node, distance in seen.items() if node != source)
return float(np.mean(distances)) if distances else np.nan
def analyze_small_world_transition(n_neurons=200, k=6, p_values=None):
if p_values is None:
p_values = [0.0, 0.01, 0.05, 0.1, 0.3, 1.0]
summary = {}
for p in p_values:
sample = conn.SmallWorld(k=k, p=p, seed=42)(pre_size=n_neurons, post_size=n_neurons)
summary[p] = {
"connections": sample.n_connections,
"clustering": mean_clustering_coefficient(sample),
"path_length": sampled_average_path_length(sample),
}
return summary
transition = analyze_small_world_transition()
for p, metrics in transition.items():
print(f"p={p:>4.2f}: clustering={metrics['clustering']:.3f}, path_length={metrics['path_length']:.2f}")
p=0.00: clustering=0.600, path_length=17.09
p=0.01: clustering=0.591, path_length=10.80
p=0.05: clustering=0.506, path_length=4.20
p=0.10: clustering=0.427, path_length=3.51
p=0.30: clustering=0.222, path_length=2.74
p=1.00: clustering=0.061, path_length=2.40
p_values = np.array(list(transition.keys()))
clustering_values = np.array([transition[p]["clustering"] for p in p_values])
path_values = np.array([transition[p]["path_length"] for p in p_values])
fig, axes = plt.subplots(1, 2, figsize=(13, 5))
axes[0].plot(p_values, clustering_values, "o-", linewidth=2, color="tab:blue")
axes[0].set_xlabel("rewiring probability p")
axes[0].set_ylabel("mean clustering coefficient")
axes[0].set_title("Local clustering")
axes[0].grid(True, alpha=0.3)
axes[1].plot(p_values, path_values, "o-", linewidth=2, color="tab:orange")
axes[1].set_xlabel("rewiring probability p")
axes[1].set_ylabel("sampled average path length")
axes[1].set_title("Path length")
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
10.2 Hierarchical Modular Architecture#
def create_hierarchical_modular_network(
n_super_modules=2,
n_sub_modules=3,
neurons_per_sub=25,
seed=0,
):
"""Create sub-modules nested inside larger super-modules."""
n_modules = n_super_modules * n_sub_modules
module_sizes = [neurons_per_sub] * n_modules
intra_conn = [
conn.Random(prob=0.35, seed=seed + i)
for i in range(n_modules)
]
inter_conn_pair = {}
for pre_mod in range(n_modules):
for post_mod in range(n_modules):
if pre_mod == post_mod:
continue
same_super = (pre_mod // n_sub_modules) == (post_mod // n_sub_modules)
prob = 0.08 if same_super else 0.01
inter_conn_pair[(pre_mod, post_mod)] = conn.Random(
prob=prob,
seed=seed + 100 + 10 * pre_mod + post_mod,
)
pattern = conn.ModularGeneral(
intra_conn=intra_conn,
inter_conn_pair=inter_conn_pair,
module_ratios=module_sizes[:-1],
)
return pattern(pre_size=sum(module_sizes), post_size=sum(module_sizes))
hier_mod_result = create_hierarchical_modular_network()
hier_mod_labels = labels_from_sizes(hier_mod_result.metadata["module_sizes"])
hier_mod_density, _, _ = block_density_matrix(hier_mod_result, hier_mod_labels)
summarize_result("Hierarchical modular network", hier_mod_result)
print(f"module sizes: {hier_mod_result.metadata['module_sizes']}")
print_block_density("sub-module block densities", hier_mod_density)
Hierarchical modular network
============================
shape: (150, 150)
connections: 1985
mean out-degree: 13.23
mean in-degree: 13.23
self-connections: 0
metadata: {'pattern': 'modular_general', 'n_modules': 6, 'module_sizes': [25, 25, 25, 25, 25, 25], 'module_ratios': [25, 25, 25, 25, 25], 'inter_conn': None, 'inter_conn_pair': {(0, 1): 'Random', (0, 2): 'Random', (0, 3): 'Random', (0, 4): 'Random', (0, 5): 'Random', (1, 0): 'Random', (1, 2): 'Random', (1, 3): 'Random', (1, 4): 'Random', (1, 5): 'Random', (2, 0): 'Random', (2, 1): 'Random', (2, 3): 'Random', (2, 4): 'Random', (2, 5): 'Random', (3, 0): 'Random', (3, 1): 'Random', (3, 2): 'Random', (3, 4): 'Random', (3, 5): 'Random', (4, 0): 'Random', (4, 1): 'Random', (4, 2): 'Random', (4, 3): 'Random', (4, 5): 'Random', (5, 0): 'Random', (5, 1): 'Random', (5, 2): 'Random', (5, 3): 'Random', (5, 4): 'Random'}, 'intra_conn': ['Random', 'Random', 'Random', 'Random', 'Random', 'Random']}
module sizes: [25, 25, 25, 25, 25, 25]
sub-module block densities
0.357 0.086 0.064 0.013 0.010 0.010
0.090 0.357 0.102 0.010 0.010 0.011
0.059 0.094 0.363 0.011 0.013 0.018
0.011 0.013 0.006 0.348 0.066 0.077
0.013 0.011 0.008 0.069 0.327 0.082
0.005 0.003 0.008 0.104 0.091 0.342
hier_mod_matrix = topology_matrix(hier_mod_result)
fig, ax = plt.subplots(figsize=(8, 7))
vis.connectivity_matrix(
hier_mod_matrix,
cmap="binary",
center_zero=False,
show_colorbar=False,
ax=ax,
title="Hierarchical modular network",
)
module_size = 25
for boundary in range(module_size, hier_mod_matrix.shape[0], module_size):
width = 2.2 if boundary % (module_size * 3) == 0 else 0.8
ax.axhline(boundary, color="tab:red", linewidth=width, alpha=0.65)
ax.axvline(boundary, color="tab:red", linewidth=width, alpha=0.65)
plt.tight_layout()
plt.show()
10.3 Resilience to Node Removal#
def largest_component_fraction(result, removed_nodes=None):
"""Largest undirected component size divided by remaining node count."""
if removed_nodes is None:
removed_nodes = set()
else:
removed_nodes = set(int(node) for node in removed_nodes)
neighbors = undirected_neighbors(result)
remaining = [node for node in range(result.shape[0]) if node not in removed_nodes]
if not remaining:
return 0.0
remaining_set = set(remaining)
seen = set()
largest = 0
for start in remaining:
if start in seen:
continue
queue = deque([start])
seen.add(start)
size = 0
while queue:
node = queue.popleft()
size += 1
for nbr in neighbors[node]:
if nbr in remaining_set and nbr not in seen:
seen.add(nbr)
queue.append(nbr)
largest = max(largest, size)
return largest / len(remaining)
def analyze_network_resilience(result, removal_fraction=0.2, strategy="random", seed=0):
"""Measure edge retention and largest component after node removal."""
n = result.shape[0]
n_remove = int(round(removal_fraction * n))
if strategy == "random":
local_rng = np.random.default_rng(seed)
removed = set(local_rng.choice(n, size=n_remove, replace=False).tolist())
elif strategy == "targeted":
degree = total_degrees(result)
removed = set(np.argsort(degree)[-n_remove:].tolist())
else:
raise ValueError("strategy must be 'random' or 'targeted'")
keep_mask = [pre not in removed and post not in removed for pre, post in zip(result.pre_indices, result.post_indices)]
remaining_fraction = float(np.mean(keep_mask)) if result.n_connections else 0.0
return {
"removed_nodes": n_remove,
"remaining_connections": remaining_fraction,
"largest_component": largest_component_fraction(result, removed),
}
print("Resilience after removing 20% of nodes")
print("=" * 86)
print(f"{'network':<14} {'random edges':<14} {'targeted edges':<16} {'random LCC':<12} {'targeted LCC':<12}")
print("=" * 86)
for name, result in networks.items():
random_metrics = analyze_network_resilience(result, strategy="random", seed=1)
targeted_metrics = analyze_network_resilience(result, strategy="targeted", seed=1)
print(
f"{name:<14} "
f"{random_metrics['remaining_connections']:<14.1%} "
f"{targeted_metrics['remaining_connections']:<16.1%} "
f"{random_metrics['largest_component']:<12.1%} "
f"{targeted_metrics['largest_component']:<12.1%}"
)
Resilience after removing 20% of nodes
======================================================================================
network random edges targeted edges random LCC targeted LCC
======================================================================================
Ring 64.2% 79.0% 100.0% 100.0%
SmallWorld 64.1% 62.0% 100.0% 100.0%
Regular 64.1% 56.1% 100.0% 100.0%
ScaleFree 66.6% 26.8% 100.0% 97.9%
Random 64.1% 54.5% 100.0% 100.0%
11. Key Takeaways#
SmallWorldpreserves exactlyn * kdirected edges;kmust be an even positive integer smaller thann.ScaleFreerepresents each preferential-attachment edge in both directions, so hub analysis should usually use total degree.Regularfixes out-degree, not in-degree, and is random rather than spatially banded.ModularGeneralneedsmodule_ratiosto express custom module sizes; otherwise modules are balanced automatically.HierarchicalRandomandCorePeripheryRandomexpose realized group sizes and probabilities inresult.metadata.ConnectionResult.weight2dense()and small graph helper functions are enough for most tutorial-level topology diagnostics.