Directed connectivity across frequency#

Granger causality gives one number per pair of regions. Brain rhythms live at particular frequencies, so it is often more useful to ask at which frequencies one region influences another. This tutorial uses three measures that do that, the directed transfer function (DTF), partial directed coherence (PDC) and generalised PDC (GPDC), on a simulation in which one region drives another only inside the alpha band.

Setup and data#

The scenario band_alpha ships with dirconn: region A drives region B with a delay of 20 ms, and the influence acts only inside the alpha band (8 to 13 Hz); a third region, C, is not connected to anything. The truth is therefore a function of frequency.

import os

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

import dirconn
from dirconn.data.bands import BANDS
from dirconn.simulation.scenario import load_scenario

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__}")

spec = load_scenario("band_alpha")
A, B, C = spec.network.names
print(spec.description)
sim = dirconn.simulate(
    spec.network,
    sfreq=spec.sfreq,
    n_times=int((30.0 if QUICK else spec.duration_s) * spec.sfreq),
    seed=SEED,
    dynamics=spec.dynamics,
    snr_db=spec.snr_db,
    n_background=0,
    node_scale="unit",
)
data = sim.roi_observations(snr_db=spec.snr_db, seed=SEED + 1)
print(data)
dirconn 0.2.0, numpy 2.5.5
A -> B acting only in the alpha band [8.0, 13.0] Hz (the limits are those of dirconn.data.bands.BANDS), coupling 0.4, delay 20 ms; both oscillate at 10 Hz, in the middle of the band. C is unconnected and gives the null edges. The truth is 1 only inside the band.
TimeSeries(n_trials=1, n_channels=3, n_times=12000, sfreq=100, segmentation='continuous')

Three measures, one call each#

All three fit the same kind of MVAR model as Granger causality (tutorial 2) and then look at its frequency response. They differ in how they normalise:

  • DTF measures the influence of a source on a target as a fraction of everything that flows into the target at that frequency.

  • PDC measures it as a fraction of everything that flows out of the source.

  • GPDC is PDC with each signal weighted by the inverse of its own noise level, which makes it independent of the scale of the signals.

The values lie between 0 and 1. n_freqs is the number of frequencies between 0 Hz and fmax.

results = {
    "DTF": dirconn.dtf(data, n_freqs=64, fmax=40.0),
    "PDC": dirconn.pdc(data, n_freqs=64, fmax=40.0),
    "GPDC": dirconn.gpdc(data, n_freqs=64, fmax=40.0),
}
for name, result in results.items():
    print(name, result, "order", result.provenance.model_order)
DTF Connectivity(method='dtf', shape=3x3x64x1, complex=False) order 8
PDC Connectivity(method='pdc', shape=3x3x64x1, complex=False) order 8
GPDC Connectivity(method='gpdc', shape=3x3x64x1, complex=False) order 8

Both directions of one pair#

kind="directed_spectrum" draws one pair in both directions. The grey band is the alpha band, where the truth of A to B is 1 and elsewhere 0.

fig, axes = plt.subplots(1, 3, sharey=True, figsize=(12.0, 3.6), layout="constrained")
for ax, (name, result) in zip(axes, results.items(), strict=True):
    result.plot(kind="directed_spectrum", source=A, target=B, ax=ax)
    ax.axvspan(*BANDS["alpha"], color="0.5", alpha=0.15)
    ax.set_title(name)
DTF, PDC, GPDC

In all three, the influence of A on B peaks inside the alpha band and falls away on both sides, and the reverse direction stays close to zero. The estimate does not fall away as sharply as the truth does, so the neighbouring theta band also gets values above zero (see the table below). In this simulation DTF and PDC give almost the same curve and GPDC a higher one. The measures normalise differently, so their heights cannot be compared between measures; compare frequencies and directions within a measure.

From a spectrum to a band#

Often one number per band is wanted. reduce_freq averages a spectrum over a band; the names come from dirconn.data.bands.BANDS and you can also pass (fmin, fmax) in Hz. Other reductions are "median", "max" and "peak_freq" (the frequency of the peak, instead of its height).

print(BANDS)
rows = []
for name, result in results.items():
    for band in ("theta", "alpha", "beta"):
        values = result.reduce_freq(band).values[:, :, 0, 0]
        rows.append({"measure": name, "band": band, "A -> B": values[0, 1], "B -> A": values[1, 0]})
print(pd.DataFrame(rows).round(3).to_string(index=False))
{'delta': (1.0, 4.0), 'theta': (4.0, 8.0), 'alpha': (8.0, 13.0), 'beta': (13.0, 30.0), 'gamma': (30.0, 80.0)}
measure  band  A -> B  B -> A
    DTF theta   0.163   0.000
    DTF alpha   0.341   0.001
    DTF  beta   0.022   0.001
    PDC theta   0.163   0.000
    PDC alpha   0.340   0.001
    PDC  beta   0.022   0.001
   GPDC theta   0.255   0.000
   GPDC alpha   0.475   0.000
   GPDC  beta   0.037   0.000

The whole matrix of a band, next to the truth for that band. sim.truth_at gives the truth on the frequency axis of the estimate; inside the band it is 1. The truth panel shows a connection that is present in the band in dark grey and no connection in white; the estimate panel shows the mean PDC over the band, on the fixed scale of PDC from 0 to 1, and its colour bar names the measure and the band.

pdc = results["PDC"]
left, right = pdc.plot(kind="truth_comparison", truth=sim.truth_at(freqs=pdc.freqs), band="alpha")
plot 03 frequency domain

The rows and columns are A, B and C in that order. The one true connection, A to B, is the only cell that stands out (about 0.3, as in the table above); every other cell, among them all those of region C, which is not connected to anything, stays near 0. On the scale from 0 to 1 even the true connection has a light colour, so read the number in the cell as well. The diagonal is light grey in every matrix, also where a measure defines it: the share of a region’s own activity is not a connection between regions.

Limitations#

  • The three measures are predictive, like Granger causality: they show where the past of one signal helps to predict another, not that one region causes another.

  • In this simulation the influence is confined to one band, both regions oscillate in the middle of that band, and there is no region that drives both; this is the easy case. Whether the same holds when the coupling is weaker, when rhythms overlap, or when a hidden region drives both is not shown here (tutorial 5 shows some such cases).

  • Every result lists the assumptions it rests on; not_checked means that the library did not test an assumption, not that it holds:

for check in pdc.provenance.assumptions.checks:
    print(f"{check.name:24s} {check.status:12s} {check.detail}")
stationarity             pass         the fitted VAR model is stable (spectral radius 0.9495).
linearity                not_checked
sampling_adequacy        pass         24 coefficients per equation are estimated from 11992 observations (ratio 0.002; 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 777.8 over lags 1 to 18 (df 90, p = 4.81e-110); largest absolute residual autocorrelation 0.0985 (warning when p < 0.05 and it exceeds 0.1).
order_selection          pass         the bic criterion chose order 8 of 10 candidates.
order_stability          pass         the direction of every pair at order 8 agrees with models of order 16, 32.
  • Not tested here: whether any single value is significantly different from what noise would give (tutorial 4), how the result depends on the model order, and anything about real recordings.

plt.close("all")

Gallery generated by Sphinx-Gallery