Note
Go to the end to download the full example code.
Your first directed connectivity#
This tutorial simulates three brain regions that drive each other in a chain, estimates who
drives whom with Granger causality, and compares the answer with the truth that we put into the
simulation. Along the way you meet the objects every other tutorial uses: a Network with a
known truth, a TimeSeries, a Connectivity result and the provenance it carries.
Only simulated data are used, so the tutorial runs in about a minute and needs no download.
Setup#
QUICK shortens the simulated recording so the tests can run this file in seconds; you get the
full version. The seed makes the simulation repeatable, and the versions are printed so a figure
can be traced back to the software that made it.
import os
import tempfile
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import dirconn
from dirconn import Connectivity, Edge, Network, dk_node
from dirconn.simulation import NodeDynamics, simulate
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__}")
dirconn 0.2.0, numpy 2.5.5
A network whose truth we know#
Three cortical regions, named with Desikan-Killiany labels. Region cuneus-rh drives
precuneus-rh and precuneus-rh drives insula-rh; each influence has a coupling
strength of 0.4 and a delay of one sample (10 ms at 100 Hz). There is no other connection, and in
particular no direct one from the first region to the last.
A, B, C = "cuneus-rh", "precuneus-rh", "insula-rh"
network = Network(
nodes=[dk_node(A), dk_node(B), dk_node(C)],
edges=[Edge(A, B, strength=0.4, delay_ms=10.0), Edge(B, C, strength=0.4, delay_ms=10.0)],
name="chain",
)
# Each region has its own rhythm, so the three signals are not copies of each other.
dynamics = {
A: NodeDynamics(kind="oscillator", freq_hz=10.0),
B: NodeDynamics(kind="oscillator", freq_hz=20.0),
C: NodeDynamics(kind="oscillator", freq_hz=15.0),
}
Simulate the recording#
simulate produces sensor data from the network; here we want the region time series
themselves (a head model is the subject of tutorial 7), so we ask for the region-level
observations: every region’s activity plus independent noise at an SNR of 10 dB.
TimeSeries(n_trials=1, n_channels=3, n_times=12000, sfreq=100, segmentation='continuous')
What the truth looks like#
sim.truth is a Connectivity too: 1 where a region drives another, 0 elsewhere, and an empty
diagonal (a region does not influence itself in this sense). In every matrix of dirconn
row i is the source and column j is the target: the cell in row cuneus-rh and column
precuneus-rh answers “how much does the first region influence the second?”. The truth is
drawn below, next to the estimate.
Estimate with Granger causality#
Granger causality asks whether the past of one signal helps to predict another signal beyond what
that signal’s own past and the other signals’ pasts already do. The estimator fits a
multivariate autoregressive (MVAR) model; order="bic" lets the Bayesian information
criterion choose how many past samples the model uses (tutorial 2 looks at that choice).
result = dirconn.gc(data, order="bic")
print(result)
print("model order:", result.provenance.model_order)
Connectivity(method='gc', shape=3x3x1x1, complex=False)
model order: 6
The result as a table, and as a picture next to the truth.
cuneus-rh precuneus-rh insula-rh
cuneus-rh NaN 0.383 0.007
precuneus-rh 0.003 NaN 0.253
insula-rh 0.000 0.003 NaN

The truth (left) is drawn in two colours: dark grey for a true connection, white for none. The estimate (right) writes its value in each cell, and its colour bar runs from 0 to its largest value; the diagonal is light grey in both, because a region’s influence on itself is not drawn. Both true connections are the two largest values of the estimate, and none of the four other cells stands out: they stay below 0.01. The value is in nats and has no upper limit of 1: it can only be compared between cells of the same result, not read as a probability. Note also that the matrix is not symmetric: the influence of the first region on the second is a different number from the influence of the second on the first.
What a result remembers#
Every result carries its provenance: how it was made, so that a figure or a number can be traced back. It is read-only and it is saved with the result.
provenance = result.provenance
print("method:", provenance.method)
print("order:", provenance.model_order)
print("claim:", provenance.claim)
method: gc
order: 6
claim: predictive, not interventional
Saving and loading a result keeps the values, the axes and the provenance.
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "chain_gc.nc"
result.to_netcdf(path)
again = Connectivity.from_netcdf(path)
np.testing.assert_array_equal(np.nan_to_num(again.values), np.nan_to_num(result.values))
print("reloaded:", again.source == result.source, again.provenance.method)
reloaded: True gc
Limitations#
The estimate is predictive: it says that the past of the source helps to predict the target. It does not say that the source causes the target; every result states this in its
claim.The result rests on assumptions. The library checks those it can;
not_checkedmeans that it did not test the assumption, not that the assumption holds. They are printed with the result:
for check in result.provenance.assumptions.checks:
print(f"{check.name:24s} {check.status:12s} {check.detail}")
stationarity not_checked
linearity not_checked
sampling_adequacy pass 18 coefficients per equation are estimated from 11994 observations (ratio 0.0015; 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 135.8 over lags 1 to 16 (df 90, p = 0.00131); largest absolute residual autocorrelation 0.0373 (warning when p < 0.05 and it exceeds 0.1).
order_selection pass the bic criterion chose order 6 of 10 candidates.
order_stability pass the direction of every pair at order 6 agrees with models of order 12, 24, 48.
What this tutorial did not test: it uses one simulated recording, so it says nothing about how stable the numbers are from one recording to another; it applies no significance test (tutorial 4); and it does not look at frequency (tutorial 3), at the model order (tutorial 2) or at situations in which the estimate is misleading (tutorial 5).
plt.close("all")