Tutorial 4: Advanced Connectivity Patterns#
This tutorial uses the current braintools.conn API for biologically inspired and kernel-based connectivity patterns.
We will cover:
ExcitatoryInhibitorynetworks following Dale’s principlespatial kernels:
GaussianKernel,GaborKernel,DoGKernel, andMexicanHatconvolution-style kernels:
Conv2dKernel,SobelKernel, andLaplacianKernelCustomKernelfunctionsmanual composition of spatial E/I projections
Every connector returns a ConnectionResult. Prefer result.n_connections, result.shape, result.weight2dense(), result.delay2matrix(), and result.get_distances() over rebuilding these values by hand.
import brainunit as u
import matplotlib.pyplot as plt
import numpy as np
import braintools.conn as conn
import braintools.visualize as vis
plt.rcParams["figure.dpi"] = 110
def to_values(x, unit=None):
"""Return plain NumPy values from a scalar, array, or brainunit Quantity."""
if unit is None:
values, _ = u.split_mantissa_unit(x)
else:
values = u.Quantity(x).to(unit).mantissa
return np.asarray(values)
def dense_values(result, unit=None):
return to_values(result.weight2dense(), unit)
def describe_result(name, result):
density = result.n_connections / np.prod(result.shape)
print(f"{name}")
print(f" shape: {result.shape}")
print(f" connections: {result.n_connections}")
print(f" density: {density:.4f}")
if result.weights is not None and result.n_connections:
weights = to_values(result.weights)
print(f" weight range: {weights.min():.4g} to {weights.max():.4g}")
if result.delays is not None and result.n_connections:
delays = to_values(result.delays)
print(f" delay range: {delays.min():.4g} to {delays.max():.4g}")
1. Excitatory-Inhibitory Networks#
ExcitatoryInhibitory partitions the presynaptic population by index. The first int(pre_size * exc_ratio) neurons are excitatory and the remaining presynaptic neurons are inhibitory.
Weights and delays are optional, but E and I values must be supplied in pairs: either provide both exc_weight and inh_weight, or provide neither. The same rule applies to exc_delay and inh_delay. A connector given only one of a pair raises ValueError when it is called.
n_neurons = 400
ei = conn.ExcitatoryInhibitory(
exc_ratio=0.8,
exc_prob=0.10,
inh_prob=0.22,
exc_weight=1.0 * u.nS,
inh_weight=-0.8 * u.nS,
exc_delay=1.5 * u.ms,
inh_delay=0.8 * u.ms,
seed=42,
)
ei_result = ei(pre_size=n_neurons, post_size=n_neurons)
n_exc = ei_result.metadata["n_excitatory"]
n_inh = ei_result.metadata["n_inhibitory"]
exc_edges = ei_result.pre_indices < n_exc
inh_edges = ~exc_edges
describe_result("E/I result", ei_result)
print(f" excitatory neurons: {n_exc}")
print(f" inhibitory neurons: {n_inh}")
print(f" observed E probability: {exc_edges.sum() / (n_exc * n_neurons):.3f}")
print(f" observed I probability: {inh_edges.sum() / (n_inh * n_neurons):.3f}")
E/I result
shape: (400, 400)
connections: 19872
density: 0.1242
weight range: -0.8 to 1
delay range: 0.8 to 1.5
excitatory neurons: 320
inhibitory neurons: 80
observed E probability: 0.101
observed I probability: 0.219
ei_dense = dense_values(ei_result, u.nS)
fig, ax = plt.subplots(figsize=(7, 6))
vis.connectivity_matrix(
ei_dense,
cmap="RdBu_r",
center_zero=True,
show_colorbar=True,
ax=ax,
title="E/I weight matrix",
xlabel="postsynaptic neuron",
ylabel="presynaptic neuron",
)
ax.axhline(n_exc - 0.5, color="black", linewidth=1.5, linestyle="--", alpha=0.6)
ax.axvline(n_exc - 0.5, color="black", linewidth=1.5, linestyle="--", alpha=0.6)
plt.tight_layout()
plt.show()
in_degree_from_e = np.bincount(ei_result.post_indices[exc_edges], minlength=n_neurons)
in_degree_from_i = np.bincount(ei_result.post_indices[inh_edges], minlength=n_neurons)
total_in_degree = np.bincount(ei_result.post_indices, minlength=n_neurons)
weights_ns = to_values(ei_result.weights, u.nS)
delays_ms = to_values(ei_result.delays, u.ms)
fig, axes = plt.subplots(1, 3, figsize=(14, 3.8))
vis.distribution_plot(
in_degree_from_e,
bins=20,
density=False,
colors=["steelblue"],
edgecolor="black",
ax=axes[0],
xlabel="in-degree from E",
ylabel="neurons",
title="Excitatory input",
)
vis.distribution_plot(
in_degree_from_i,
bins=20,
density=False,
colors=["firebrick"],
edgecolor="black",
ax=axes[1],
xlabel="in-degree from I",
ylabel="neurons",
title="Inhibitory input",
)
vis.distribution_plot(
total_in_degree,
bins=25,
density=False,
colors=["dimgray"],
edgecolor="black",
ax=axes[2],
xlabel="total in-degree",
ylabel="neurons",
title="Total input",
)
plt.tight_layout()
plt.show()
print(f"mean E weight: {weights_ns[exc_edges].mean():.2f} nS")
print(f"mean I weight: {weights_ns[inh_edges].mean():.2f} nS")
print(f"mean E delay: {delays_ms[exc_edges].mean():.2f} ms")
print(f"mean I delay: {delays_ms[inh_edges].mean():.2f} ms")
mean E weight: 1.00 nS
mean I weight: -0.80 nS
mean E delay: 1.50 ms
mean I delay: 0.80 ms
3. Gaussian Kernel#
GaussianKernel creates distance-weighted connectivity. The current default is normalize=True, which applies a two-dimensional Gaussian normalization constant. That is useful when treating the kernel as a density, but it makes raw weights small and can prune low values. For visual amplitude examples, use normalize=False explicitly.
gaussian = conn.GaussianKernel(
sigma=90 * u.um,
max_distance=270 * u.um,
normalize=False,
allow_self_connections=True,
weight=1.5 * u.nS,
seed=1,
)
gaussian_result = gaussian(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
gaussian_no_self = conn.GaussianKernel(
sigma=90 * u.um,
max_distance=270 * u.um,
normalize=False,
weight=1.5 * u.nS,
seed=1,
)(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
gaussian_normalized = conn.GaussianKernel(
sigma=90 * u.um,
max_distance=270 * u.um,
normalize=True,
allow_self_connections=True,
weight=1.5 * u.nS,
seed=1,
)(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
describe_kernel("Gaussian, unnormalized", gaussian_result)
print(f" self connections when enabled: {np.count_nonzero(gaussian_result.pre_indices == gaussian_result.post_indices)}")
print(f" self connections by default: {np.count_nonzero(gaussian_no_self.pre_indices == gaussian_no_self.post_indices)}")
print(f" max normalized weight: {to_values(gaussian_normalized.weights, u.nS).max():.6f} nS")
Gaussian, unnormalized
shape: (441, 441)
connections: 33741
density: 0.1735
weight range: 0.01708 to 1.5
distance range: 0.0 to 269.3 um
mean distance: 178.7 um
self connections when enabled: 441
self connections by default: 0
max normalized weight: 0.000029 nS
gaussian_dense = dense_values(gaussian_result, u.nS)
gaussian_rf = receptive_field(gaussian_result)
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2))
vis.connectivity_matrix(
gaussian_dense,
cmap="viridis",
center_zero=False,
show_colorbar=True,
ax=axes[0],
title="Gaussian matrix",
xlabel="post",
ylabel="pre",
)
im = axes[1].imshow(gaussian_rf, cmap="viridis", origin="lower", extent=image_extent)
axes[1].set_title("Center receptive field")
axes[1].set_xlabel("x (um)")
axes[1].set_ylabel("y (um)")
plt.colorbar(im, ax=axes[1], label="weight (nS)")
vis.distribution_plot(
to_values(gaussian_result.weights, u.nS),
bins=40,
density=False,
colors=["teal"],
edgecolor="black",
ax=axes[2],
xlabel="weight (nS)",
ylabel="connections",
title="Weight distribution",
)
plt.tight_layout()
plt.show()
4. Gabor Kernel#
GaborKernel combines a Gaussian envelope with a sinusoidal carrier. The frequency argument is interpreted in cycles per position unit after positions are converted internally, so with micrometer positions frequency=1/180 means a wavelength of 180 um.
gabor = conn.GaborKernel(
sigma=110 * u.um,
frequency=1 / 180,
theta=np.pi / 4,
phase=0.0,
max_distance=330 * u.um,
allow_self_connections=True,
weight=1.0 * u.nS,
seed=2,
)
gabor_result = gabor(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
describe_kernel("Gabor, theta=45 degrees", gabor_result)
Gabor, theta=45 degrees
shape: (441, 441)
connections: 45317
density: 0.2330
weight range: -0.6358 to 1
distance range: 0.0 to 320.2 um
mean distance: 210.9 um
orientations = [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4]
orientation_names = ["0 deg", "45 deg", "90 deg", "135 deg"]
fig, axes = plt.subplots(2, 4, figsize=(15, 7))
for col, (theta, label) in enumerate(zip(orientations, orientation_names)):
result = conn.GaborKernel(
sigma=110 * u.um,
frequency=1 / 180,
theta=theta,
max_distance=330 * u.um,
allow_self_connections=True,
weight=1.0 * u.nS,
seed=2,
)(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
weights = to_values(result.weights, u.nS)
rf = receptive_field(result)
im = axes[0, col].imshow(rf, cmap="RdBu_r", origin="lower", extent=image_extent)
axes[0, col].set_title(label)
axes[0, col].set_xlabel("x (um)")
axes[0, col].set_ylabel("y (um)")
plt.colorbar(im, ax=axes[0, col])
vis.distribution_plot(
weights,
bins=35,
density=False,
colors=["slateblue"],
edgecolor="black",
ax=axes[1, col],
xlabel="weight (nS)",
ylabel="connections",
title=f"Weights, {label}",
)
plt.tight_layout()
plt.show()
5. Center-Surround Kernels#
DoGKernel implements a difference of Gaussians. MexicanHat is a convenience subclass that chooses the surround sigma and amplitude ratio for a Laplacian-of-Gaussian-like profile.
dog_result = conn.DoGKernel(
sigma_center=55 * u.um,
sigma_surround=140 * u.um,
amplitude_center=1.4,
amplitude_surround=0.7,
max_distance=420 * u.um,
allow_self_connections=True,
weight=1.0 * u.nS,
seed=3,
)(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
mexican_result = conn.MexicanHat(
sigma=80 * u.um,
max_distance=320 * u.um,
allow_self_connections=True,
weight=0.8 * u.nS,
seed=4,
)(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
describe_kernel("DoG center-surround", dog_result)
describe_kernel("MexicanHat", mexican_result)
DoG center-surround
shape: (441, 441)
connections: 67073
density: 0.3449
weight range: -0.3689 to 0.7
distance range: 0.0 to 412.3 um
mean distance: 264.3 um
MexicanHat
shape: (441, 441)
connections: 43141
density: 0.2218
weight range: -0.09847 to 0.8
distance range: 0.0 to 316.2 um
mean distance: 205.3 um
fig, axes = plt.subplots(2, 2, figsize=(11, 8))
for row, (name, result) in enumerate([("DoG", dog_result), ("MexicanHat", mexican_result)]):
rf = receptive_field(result)
weights = to_values(result.weights, u.nS)
im = axes[row, 0].imshow(rf, cmap="RdBu_r", origin="lower", extent=image_extent)
axes[row, 0].set_title(f"{name} receptive field")
axes[row, 0].set_xlabel("x (um)")
axes[row, 0].set_ylabel("y (um)")
plt.colorbar(im, ax=axes[row, 0], label="weight (nS)")
vis.distribution_plot(
weights,
bins=40,
density=False,
colors=["indigo"],
edgecolor="black",
ax=axes[row, 1],
xlabel="weight (nS)",
ylabel="connections",
title=f"{name} weights",
)
plt.tight_layout()
plt.show()
6. Convolution Kernels#
The current general convolution class is Conv2dKernel. Older notes may call this ConvKernel; use Conv2dKernel in new code.
Conv2dKernel, SobelKernel, and LaplacianKernel threshold on absolute coefficient magnitude, so negative coefficients are retained. For Laplacian filters, the negative center coefficient only appears when allow_self_connections=True.
conv2d_kernel = np.array(
[
[0.00, 0.25, 0.00],
[0.25, 1.00, 0.25],
[0.00, 0.25, 0.00],
],
dtype=float,
)
conv_results = {
"Conv2dKernel": conn.Conv2dKernel(
kernel=conv2d_kernel,
kernel_size=160 * u.um,
threshold=0.0,
allow_self_connections=True,
weight=0.6 * u.nS,
seed=5,
),
"Sobel vertical": conn.SobelKernel(
direction="vertical",
kernel_size=160 * u.um,
allow_self_connections=True,
weight=0.25 * u.nS,
seed=6,
),
"Laplacian 4-neighbor": conn.LaplacianKernel(
kernel_type="4-connected",
kernel_size=160 * u.um,
allow_self_connections=True,
weight=0.2 * u.nS,
seed=7,
),
}
conv_outputs = {}
for name, pattern in conv_results.items():
conv_outputs[name] = pattern(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
describe_kernel(name, conv_outputs[name])
lap_weights = to_values(conv_outputs["Laplacian 4-neighbor"].weights, u.nS)
print(f"Laplacian has negative weights: {np.any(lap_weights < 0)}")
Conv2dKernel
shape: (441, 441)
connections: 2121
density: 0.0109
weight range: 0.15 to 0.6
distance range: 0.0 to 50.0 um
mean distance: 39.6 um
Sobel vertical
shape: (441, 441)
connections: 2440
density: 0.0125
weight range: -0.5 to 0.5
distance range: 50.0 to 70.7 um
mean distance: 63.6 um
Laplacian 4-neighbor
shape: (441, 441)
connections: 2121
density: 0.0109
weight range: -0.8 to 0.2
distance range: 0.0 to 50.0 um
mean distance: 39.6 um
Laplacian has negative weights: True
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
for ax, (name, result) in zip(axes, conv_outputs.items()):
rf = receptive_field(result)
im = ax.imshow(rf, cmap="RdBu_r", origin="lower", extent=image_extent)
ax.set_title(name)
ax.set_xlabel("x (um)")
ax.set_ylabel("y (um)")
plt.colorbar(im, ax=ax)
plt.tight_layout()
plt.show()
7. Custom Kernels#
CustomKernel accepts a vectorized function kernel_func(x, y) and applies it to relative presynaptic coordinates around each postsynaptic neuron. The function should return one value per (x, y) pair.
def ring_spiral_kernel(x, y):
r = np.sqrt(x**2 + y**2)
theta = np.arctan2(y, x)
ring = np.exp(-((r - 180) / 70) ** 2)
angular_modulation = 0.55 + 0.45 * np.cos(3 * theta + r / 120)
return ring * angular_modulation
custom_result = conn.CustomKernel(
kernel_func=ring_spiral_kernel,
kernel_size=520 * u.um,
threshold=0.08,
allow_self_connections=False,
weight=1.2 * u.nS,
seed=8,
)(
pre_size=n_grid,
post_size=n_grid,
pre_positions=grid_positions,
post_positions=grid_positions,
)
describe_kernel("Custom ring-spiral kernel", custom_result)
Custom ring-spiral kernel
shape: (441, 441)
connections: 24899
density: 0.1280
weight range: 0.1028 to 1.196
distance range: 70.7 to 255.0 um
mean distance: 185.2 um
custom_dense = dense_values(custom_result, u.nS)
custom_rf = receptive_field(custom_result)
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2))
im = axes[0].imshow(custom_rf, cmap="magma", origin="lower", extent=image_extent)
axes[0].set_title("Custom receptive field")
axes[0].set_xlabel("x (um)")
axes[0].set_ylabel("y (um)")
plt.colorbar(im, ax=axes[0], label="weight (nS)")
vis.connectivity_matrix(
custom_dense[:120, :120],
cmap="magma",
center_zero=False,
show_colorbar=True,
ax=axes[1],
title="Matrix subset",
xlabel="post",
ylabel="pre",
)
vis.distribution_plot(
to_values(custom_result.weights, u.nS),
bins=40,
density=False,
colors=["darkorange"],
edgecolor="black",
ax=axes[2],
xlabel="weight (nS)",
ylabel="connections",
title="Custom weights",
)
plt.tight_layout()
plt.show()
8. Combining E/I Identity with Spatial Kernels#
ExcitatoryInhibitory assigns E/I identity and random connection probabilities. When you need distance-dependent E and I projections, build the excitatory and inhibitory projections separately and combine their indices into a new ConnectionResult.
n_combined = 320
rng = np.random.default_rng(2026)
combined_positions = rng.uniform(0, 1000, size=(n_combined, 2)) * u.um
n_exc_combined = int(0.8 * n_combined)
exc_spatial = conn.GaussianKernel(
sigma=140 * u.um,
max_distance=420 * u.um,
normalize=False,
weight=0.9 * u.nS,
seed=9,
)
inh_spatial = conn.GaussianKernel(
sigma=75 * u.um,
max_distance=230 * u.um,
normalize=False,
weight=-1.1 * u.nS,
seed=10,
)
exc_result = exc_spatial(
pre_size=n_exc_combined,
post_size=n_combined,
pre_positions=combined_positions[:n_exc_combined],
post_positions=combined_positions,
)
inh_result = inh_spatial(
pre_size=n_combined - n_exc_combined,
post_size=n_combined,
pre_positions=combined_positions[n_exc_combined:],
post_positions=combined_positions,
)
combined_pre = np.concatenate([exc_result.pre_indices, inh_result.pre_indices + n_exc_combined])
combined_post = np.concatenate([exc_result.post_indices, inh_result.post_indices])
combined_weights = np.concatenate([
to_values(exc_result.weights, u.nS),
to_values(inh_result.weights, u.nS),
]) * u.nS
combined_result = conn.ConnectionResult(
pre_indices=combined_pre,
post_indices=combined_post,
pre_size=n_combined,
post_size=n_combined,
weights=combined_weights,
model_type="point",
pre_positions=combined_positions,
post_positions=combined_positions,
metadata={
"pattern": "spatial_ei_composite",
"n_excitatory": n_exc_combined,
"n_inhibitory": n_combined - n_exc_combined,
},
)
describe_result("Spatial E/I composite", combined_result)
print(f" E connections: {exc_result.n_connections}")
print(f" I connections: {inh_result.n_connections}")
Spatial E/I composite
shape: (320, 320)
connections: 34888
density: 0.3407
weight range: -1.1 to 0.9
E connections: 32001
I connections: 2887
combined_dense = dense_values(combined_result, u.nS)
combined_distances = to_values(combined_result.get_distances(), u.um)
combined_weights_ns = to_values(combined_result.weights, u.nS)
combined_exc_edges = combined_result.pre_indices < n_exc_combined
combined_inh_edges = ~combined_exc_edges
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2))
vis.connectivity_matrix(
combined_dense,
cmap="RdBu_r",
center_zero=True,
show_colorbar=True,
ax=axes[0],
title="Spatial E/I matrix",
xlabel="post",
ylabel="pre",
)
axes[0].axhline(n_exc_combined - 0.5, color="black", linewidth=1.5, linestyle="--", alpha=0.6)
vis.distribution_plot(
combined_weights_ns,
bins=45,
density=False,
colors=["steelblue"],
edgecolor="black",
ax=axes[1],
xlabel="weight (nS)",
ylabel="connections",
title="Combined weights",
)
vis.distribution_plot(
combined_distances[combined_exc_edges],
bins=30,
density=False,
colors=["steelblue"],
edgecolor="black",
alpha=0.7,
ax=axes[2],
xlabel="distance (um)",
ylabel="connections",
title="Distance by projection",
)
vis.distribution_plot(
combined_distances[combined_inh_edges],
bins=30,
density=False,
colors=["firebrick"],
edgecolor="black",
alpha=0.55,
ax=axes[2],
)
axes[2].legend(["E", "I"])
plt.tight_layout()
plt.show()
print(f"mean E distance: {combined_distances[combined_exc_edges].mean():.1f} um")
print(f"mean I distance: {combined_distances[combined_inh_edges].mean():.1f} um")
mean E distance: 264.3 um
mean I distance: 146.0 um
Current API Checklist#
Use
ConnectionResult.n_connectionsinstead oflen(result.pre_indices)in tutorials.Use
weight2dense()anddelay2matrix()when converting a result to matrices.Kernel connectors require positions; they use only the first two position dimensions.
GaussianKernel(normalize=True)is density-normalized. Usenormalize=Falsefor examples whereweightshould be the peak amplitude.The general convolution class is
Conv2dKernel.Self-connections are disabled by default for same-population kernel connectors.