Note
Go to the end to download the full example code.
From sensors to regions, and leakage#
Recordings are made at sensors, but the questions are about brain regions. The usual bridge is an inverse solution: it estimates the activity of each region from the sensors. This tutorial simulates sensor data from known regions on a real head model, estimates the region time series back from the sensors, and compares the directed connectivity of the estimated series with that of the true ones. Two neighbouring regions show what goes wrong: the estimate of one contains the other, and the connectivity then contains influences that were never there.
This tutorial needs the MNE sample dataset (about 1.5 GB). It is never downloaded by
dirconn without being asked; see dirconn.datasets.require_sample.
NEEDS_SAMPLE = True
Setup#
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from dirconn.datasets import require_sample
import dirconn
from dirconn.diagnostics.regions import centre_distances
from dirconn.simulation import simulate_on_head
from dirconn.simulation.headmodel import load_head_model
from dirconn.simulation.inverse import crosstalk, roi_series
from dirconn.simulation.scenario import load_scenario
from dirconn.viz import connectivity_grids
QUICK = os.environ.get("DIRCONN_QUICK") == "1" # the tests set this; readers get the full version
SEED = 0
print(f"dirconn {dirconn.__version__}, numpy {np.__version__}")
print("sample data:", require_sample()) # stops with instructions when the data are missing
dirconn 0.2.0, numpy 2.5.5
sample data: /home/runner/mne_data/MNE-sample-data
A head model#
The head model of the sample subject links every cortical region to the 59 EEG sensors: the leadfield says how the activity of a region appears at each sensor. It also holds the parcellation into 68 Desikan-Killiany regions. Loading takes a few seconds.
head = load_head_model("eeg")
print(f"{head.n_channels} EEG channels, {len(head.roi_names)} regions")
59 EEG channels, 68 regions
A scenario with two close regions#
The shipped scenario leakage_adjacent has three regions: Z drives X, and Y is a close
neighbour of X that nothing drives. Every influence into Y that an analysis reports is therefore
false. The distances are those between the region centres on the head model, in millimetres.
spec = load_scenario("leakage_adjacent")
Z, X, Y = spec.network.names
print(spec.description)
distances = centre_distances(head)
index = {name: head.roi_names.index(name) for name in spec.network.names}
for a, b in ((X, Y), (Z, X)):
print(f"distance {a} - {b}: {distances[index[a], index[b]]:.0f} mm")
Z -> X is the only edge (0.4, 10 ms). Y is the neighbour of X into whose series X leaks most: cuneus-lh (X) and pericalcarine-lh (Y) are 10 mm apart and the pair is in the leakiest tenth of all region pairs on EEG and on gradiometers (tools/pick_regions.py leakage). Z is far from both and leaks little into them. Nothing drives Y, so every edge into Y that an estimator finds at source level (Z -> Y, X -> Y) is leakage; at region level there is none.
distance cuneus-lh - pericalcarine-lh: 10 mm
distance transversetemporal-rh - cuneus-lh: 76 mm
Simulate the recording#
simulate_on_head lets every region of the network oscillate, projects it through the leadfield
to the sensors, adds the activity of other sources in the brain (n_background) and noise, so
that the sensors have a signal-to-noise ratio of 10 dB. The simulation also keeps the true
time series of the regions, which a real recording never has.
sim = simulate_on_head(
spec.network,
head,
sfreq=spec.sfreq,
n_times=int((30.0 if QUICK else 60.0) * spec.sfreq),
seed=SEED,
dynamics=spec.dynamics,
snr_db=spec.snr_db,
n_background=10,
)
print(sim.data)
TimeSeries(n_trials=1, n_channels=59, n_times=6000, sfreq=100, segmentation='continuous')
Two ways to the regions’ time series#
sim.roi_observationsgives the regions’ own activity plus a little noise (tutorial 1 did this): the oracle, the data we would like to have.roi_seriesis what an analysis of a real recording has to do: estimate the regions from the sensors with an inverse method (here the minimum-norm estimate, with the sign of every source aligned by a principal component,"pca_flip").
oracle = sim.roi_observations(snr_db=spec.snr_db, seed=SEED + 1)
estimated = roi_series(sim.data, head, list(spec.network.names))
print(oracle.names == estimated.names)
True
The same Granger causality on both#
The only true influence is Z -> X. The matrices name the regions: Z is transversetemporal-rh, X cuneus-lh and Y pericalcarine-lh. Both panels are the same measure, so they share one colour bar. oracle: the regions’ own series; from sensors: the regions estimated by the inverse method
results = {
"oracle": dirconn.gc(oracle, order=5, check_order_stability=False),
"from sensors": dirconn.gc(estimated, order=5, check_order_stability=False),
}
connectivity_grids(list(results.values()), names=list(results))
cells = {
"Z -> X (real)": (Z, X),
"Z -> Y (no such influence)": (Z, Y),
"X -> Y (no such influence)": (X, Y),
"Y -> X (no such influence)": (Y, X),
}
table = pd.DataFrame(
{
label: {
name: result.values[result.source.index(a), result.target.index(b), 0, 0]
for name, (a, b) in cells.items()
}
for label, result in results.items()
}
)
print(table.round(3))

oracle from sensors
Z -> X (real) 0.380 0.200
Z -> Y (no such influence) 0.001 0.280
X -> Y (no such influence) 0.001 0.118
Y -> X (no such influence) 0.000 0.144
With the regions’ own series the one real influence is the only cell that stands out. With the regions estimated from the sensors, the real influence is about half as strong, and three cells that are not real stand out: Z -> Y, the largest in that panel, which points into Y, which nothing drives, and X -> Y and Y -> X, between X and Y in both directions.
Where it comes from: leakage#
An inverse solution cannot separate close sources perfectly: the estimate of one region contains
a part of the activity of its neighbours. crosstalk measures it. It makes every region of the
head model active with independent white activity, projects it to the sensors, adds sensor noise,
extracts the regions of interest exactly as roi_series does, and asks how much of each
region’s activity arrives in each extracted series. Entry [i, j] is the response of series
i to the activity of region j, relative to the response of series i to its own
region (so the diagonal is 1 and a value above 1 means that a neighbour is heard louder than the
region itself). It is estimated from random probe data, so it changes a little with the seed.
leak = crosstalk(head, list(spec.network.names), seed=SEED + 2)
leak_table = pd.DataFrame(leak.matrix, index=leak.rois, columns=leak.rois)
print("rows: series that receives; columns: region that leaks in")
print(leak_table.round(2))
print(f"X leaks into the series of Y with {leak.matrix[2, 1]:.2f} times Y's own response")
rows: series that receives; columns: region that leaks in
transversetemporal-rh cuneus-lh pericalcarine-lh
transversetemporal-rh 1.00 0.14 -0.19
cuneus-lh -0.15 1.00 0.77
pericalcarine-lh -0.05 2.94 1.00
X leaks into the series of Y with 2.94 times Y's own response
The series that was estimated for Y contains the activity of X, in this simulation more strongly than Y’s own activity. That explains the influences into Y: Z drives X, and X is in Y’s series. The oracle series, which have no such mixing, are the control: with them the influences into Y are absent.
Limitations#
The influences into Y that appear in the sensor-based analysis are leakage, not connections: nothing drives Y in the simulation, and the same estimator finds none in the regions’ own series.
This is one simulated recording of one pair of close regions on one head model, with one inverse method and EEG only. How much leakage there is for other pairs, other methods and MEG is not shown here. The benchmark report (
docs/benchmark_results.md) measures leakage across many pairs under stated conditions.dirconn does not correct for leakage. The crosstalk matrix is a way to see where it is likely to be a problem, and an estimate of its size, not a correction.
Every result lists the assumptions it rests on;
not_checkedmeans that the library did not test an assumption, not that it holds:
stationarity not_checked
linearity not_checked
sampling_adequacy pass 15 coefficients per equation are estimated from 5995 observations (ratio 0.0025; the rule of thumb is at most 0.1).
instantaneous_coupling not_checked
causal_sufficiency not_checked
filtering not_checked
residual_whiteness pass Hosking portmanteau statistic 507.1 over lags 1 to 15 (df 90, p = 2.12e-59); largest absolute residual autocorrelation 0.0812 (warning when p < 0.05 and it exceeds 0.1).
Not tested here: whether a different inverse method or a different head model changes the picture, and what happens with real recordings, where neither the regions nor their number are known.
plt.close("all")