Note
Go to the end to download the full example code.
One command, every method: dirconn as a BIDS App#
Tutorials 1 to 16 call the library from Python: simulate or load a recording, build an estimator, fit it, test it, plot it, one method at a time. Since 0.2.0 the same analysis of a whole dataset is one command:
dirconn-bids BIDS_DIR OUTPUT_DIR participant --config dirconn.toml
It finds the recordings of a BIDS dataset, prepares them, runs every configured method with its significance test and the time-reversal control, and writes the results as a BIDS-Derivatives dataset with provenance. This tutorial simulates a small network with a known truth, writes it as a BIDS dataset, runs eight directed-connectivity methods on it with one command (and says what the other six cost or need), and then reads what the command wrote: the edge tables, the result files, the diagnostics and the run’s logs.
It needs the app extra (pip install "dirconn[app]").
Setup#
Four nodes: three cortical regions and one deep (STN) contact, as in a DBS recording. Two influences are true, precuneus -> postcentral and postcentral -> STN, each with a 12 ms delay. The pair precuneus -> STN is linked only through postcentral (indirect).
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 Edge, Network, direct_node, dk_node, write_roi_bids
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__}")
cortical = ["precuneus-lh", "postcentral-lh", "superiorfrontal-lh"]
nodes = [dk_node(n, region=n.removesuffix("-lh"), hemisphere="lh", atlas="DK") for n in cortical]
nodes.append(direct_node("STN-L", region="STN", hemisphere="lh"))
names = [*cortical, "STN-L"]
true_edges = {("precuneus-lh", "postcentral-lh"), ("postcentral-lh", "STN-L")}
network = Network(
nodes=nodes,
edges=[Edge(s, t, strength=0.4, delay_ms=12.0) for s, t in sorted(true_edges)],
name="showcase",
)
dynamics = {
name: NodeDynamics(kind="oscillator", freq_hz=freq)
for name, freq in zip(names, (10.0, 20.0, 15.0, 8.0), strict=True)
}
dirconn 0.2.0, numpy 2.5.5
The input: a BIDS dataset#
dirconn-bids reads BIDS. Region-level series (here simulated; in practice from a source
reconstruction) are stored as a BIDS-Derivatives dataset with write_roi_bids();
sensor-level EEG/MEG/iEEG in BIDS works as well (--set input.level=sensor). Two subjects with
one resting recording each, 250 Hz, observed with white noise at 10 dB.
SFREQ = 250.0
DURATION_S = 30.0 if QUICK else 60.0
work = Path(tempfile.mkdtemp(prefix="dirconn_showcase_"))
bids_dir = work / "bids"
out_dir = work / "out"
for index, subject in enumerate(["01", "02"]):
sim = simulate(
network,
sfreq=SFREQ,
n_times=int(DURATION_S * SFREQ),
seed=SEED + index,
dynamics=dynamics,
snr_db=10.0,
n_background=0,
node_scale="unit",
)
write_roi_bids(
sim.roi_observations(snr_db=10.0, seed=SEED + 100 + index),
bids_dir / "derivatives" / "dirconn-roi",
subject=subject,
task="rest",
description="DK",
)
# A minimal raw dataset around the derivatives, as BIDS requires.
(bids_dir / "dataset_description.json").write_text(
'{"Name": "dirconn showcase", "BIDSVersion": "1.9.0"}', encoding="utf-8"
)
for path in sorted(bids_dir.rglob("*")):
if path.is_file():
print(path.relative_to(bids_dir).as_posix())
Writing '/tmp/dirconn_showcase_3b32w2kc/bids/derivatives/dirconn-roi/dataset_description.json'...
dataset_description.json
derivatives/dirconn-roi/dataset_description.json
derivatives/dirconn-roi/sub-01/eeg/sub-01_task-rest_desc-DK_channels.json
derivatives/dirconn-roi/sub-01/eeg/sub-01_task-rest_desc-DK_channels.tsv
derivatives/dirconn-roi/sub-01/eeg/sub-01_task-rest_desc-DK_eeg.fif
derivatives/dirconn-roi/sub-01/eeg/sub-01_task-rest_desc-DK_eeg.json
derivatives/dirconn-roi/sub-02/eeg/sub-02_task-rest_desc-DK_channels.json
derivatives/dirconn-roi/sub-02/eeg/sub-02_task-rest_desc-DK_channels.tsv
derivatives/dirconn-roi/sub-02/eeg/sub-02_task-rest_desc-DK_eeg.fif
derivatives/dirconn-roi/sub-02/eeg/sub-02_task-rest_desc-DK_eeg.json
The configuration#
The analysis is a TOML file (dirconn-bids validate-config FILE checks it; omitted keys keep
their defaults, listed in the documentation’s configuration page). Two things here are not
defaults, and both matter:
Methods. Eight of the fourteen directed methods of
dirconn-bids list-methods(trgcis the time-reversal control and runs by itself). The other six cost more time or add little here. With the settings below, on a workstation (4 workers), a run with all of them but te took 31 min, per recording:mtgc: 22 to 26 min. Its surrogate test refits a multitaper spectral factorisation for every surrogate.pcmci: about 3 min for one fit; it is tested with its own p-values, without surrogates.adtf,tpdc: about 1 min each. Likewdtfthey are time resolved, and on a continuous record they are not tested (see the edge tables below).psi: 20 s. It is a phase-slope index per band, not a model of the network.te: one pairwise fit of these 60 s took more than nine minutes. Use it for a chosen hypothesis (tutorials 12, 13, 15).
Add them to
methodswhen the time is there;dirconn-bidsfills in what they need (segment lengths, windows, psi’s bands).Enough surrogates. With 12 directed pairs per band, a corrected test can only reject when the smallest possible p-value,
1 / (n_surrogates + 1), is below0.05 / 12: at least 239 surrogates. With 19 nothing is ever significant (dirconn warns about it).
order = "bic" (the default) selects the VAR order once per recording, on the prepared
record, and every method with an order and the surrogates of its test use it; the selection is
in each result’s provenance and in the recording’s diagnostics file.
METHODS = ["gc", "dtf", "pdc", "gpdc", "rpdc", "ssgc", "imcoh", "wdtf"]
config = f"""
schema_version = 1
[estimation]
methods = {METHODS!r}
order = "bic"
bands = {{ alpha = [8.0, 12.0], beta_low = [13.0, 20.0], beta_high = [20.0, 30.0] }}
[statistics]
n_surrogates = 239
"""
config_file = work / "dirconn.toml"
config_file.write_text(config.replace("'", '"'), encoding="utf-8")
print(config_file.read_text(encoding="utf-8"))
schema_version = 1
[estimation]
methods = ["gc", "dtf", "pdc", "gpdc", "rpdc", "ssgc", "imcoh", "wdtf"]
order = "bic"
bands = { alpha = [8.0, 12.0], beta_low = [13.0, 20.0], beta_high = [20.0, 30.0] }
[statistics]
n_surrogates = 239
The one command#
In a shell:
dirconn-bids bids out participant --config dirconn.toml --skip-bids-validation --nprocs 4
Here it runs in-process with the same arguments; the return value is the exit code (0 every task succeeded; 1 a task failed and the other results are kept; 2 invalid input or configuration).
from dirconn.cli.run import main as dirconn_bids # noqa: E402
argv = [str(bids_dir), str(out_dir), "participant", "--config", str(config_file)]
argv += ["--skip-bids-validation", "--nprocs", "2" if QUICK else "4"]
print("dirconn-bids " + " ".join(argv))
exit_code = dirconn_bids(argv)
print("exit code", exit_code)
dirconn-bids /tmp/dirconn_showcase_3b32w2kc/bids /tmp/dirconn_showcase_3b32w2kc/out participant --config /tmp/dirconn_showcase_3b32w2kc/dirconn.toml --skip-bids-validation --nprocs 4
dirconn-bids: done 18, skipped 0, failed 0; run directory /tmp/dirconn_showcase_3b32w2kc/out/dirconn/logs/run-20261130T152759-2859
dirconn-bids: report /tmp/dirconn_showcase_3b32w2kc/out/dirconn/sub-01.html
dirconn-bids: report /tmp/dirconn_showcase_3b32w2kc/out/dirconn/sub-02.html
dirconn-bids: methods boilerplate /tmp/dirconn_showcase_3b32w2kc/out/dirconn/logs/CITATION.*
exit code 0
What the command wrote#
One BIDS-Derivatives dataset, out/dirconn. Per recording and method: the full result
(_conn.nc, NetCDF with its provenance), a sidecar (_conn.json, written last: it marks the
task as done, so a rerun skips it) and a long edge table (_edges.tsv). Per recording:
figures/<recording>_diagnostics.json and the time-reversal control desc-trgc. Per run:
logs/run-<time>-<pid>/ with the log, the progress of each task, the effective configuration,
the installed packages and provenance.json.
root = out_dir / "dirconn"
for path in sorted(root.rglob("*")):
if path.is_file() and "sub-02" not in path.as_posix():
print(path.relative_to(root).as_posix())
dataset_description.json
dirconn.toml
logs/CITATION.bib
logs/CITATION.html
logs/CITATION.md
logs/CITATION.tex
logs/run-20261130T152759-2859/dirconn.log
logs/run-20261130T152759-2859/dirconn.toml
logs/run-20261130T152759-2859/environment-lock.txt
logs/run-20261130T152759-2859/progress.jsonl
logs/run-20261130T152759-2859/provenance.json
sub-01/eeg/figures/sub-01_task-rest_desc-diag_assumptions.json
sub-01/eeg/figures/sub-01_task-rest_desc-diag_order.json
sub-01/eeg/figures/sub-01_task-rest_desc-diag_order.svg
sub-01/eeg/figures/sub-01_task-rest_desc-diag_psd.json
sub-01/eeg/figures/sub-01_task-rest_desc-diag_psd.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_matrix-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_matrix-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_matrix-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_matrix-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_matrix-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_matrix-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_net-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_net-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_net-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_net-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_net-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_net-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_pvalues.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_pvalues.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_significant.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_spectra.json
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_spectra.svg
sub-01/eeg/figures/sub-01_task-rest_desc-dtf_tests.json
sub-01/eeg/figures/sub-01_task-rest_desc-gc_matrix-broadband.json
sub-01/eeg/figures/sub-01_task-rest_desc-gc_matrix-broadband.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gc_net-broadband.json
sub-01/eeg/figures/sub-01_task-rest_desc-gc_net-broadband.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gc_pvalues.json
sub-01/eeg/figures/sub-01_task-rest_desc-gc_pvalues.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gc_significant.json
sub-01/eeg/figures/sub-01_task-rest_desc-gc_tests.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_matrix-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_matrix-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_matrix-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_matrix-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_matrix-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_matrix-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_net-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_net-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_net-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_net-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_net-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_net-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_pvalues.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_pvalues.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_significant.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_spectra.json
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_spectra.svg
sub-01/eeg/figures/sub-01_task-rest_desc-gpdc_tests.json
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_matrix-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_matrix-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_matrix-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_matrix-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_matrix-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_matrix-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_pvalues.json
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_pvalues.svg
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_significant.json
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_spectra.json
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_spectra.svg
sub-01/eeg/figures/sub-01_task-rest_desc-imcoh_tests.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_matrix-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_matrix-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_matrix-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_matrix-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_matrix-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_matrix-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_net-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_net-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_net-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_net-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_net-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_net-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_pvalues.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_pvalues.svg
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_significant.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_spectra.json
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_spectra.svg
sub-01/eeg/figures/sub-01_task-rest_desc-pdc_tests.json
sub-01/eeg/figures/sub-01_task-rest_desc-prep_nodes.json
sub-01/eeg/figures/sub-01_task-rest_desc-prep_record.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_matrix-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_matrix-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_matrix-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_matrix-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_matrix-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_matrix-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_net-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_net-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_net-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_net-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_net-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_net-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_pvalues.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_pvalues.svg
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_significant.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_spectra.json
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_spectra.svg
sub-01/eeg/figures/sub-01_task-rest_desc-rpdc_tests.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_matrix-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_matrix-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_matrix-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_matrix-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_matrix-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_matrix-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_net-alpha.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_net-alpha.svg
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_net-beta-high.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_net-beta-high.svg
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_net-beta-low.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_net-beta-low.svg
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_pvalues.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_pvalues.svg
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_significant.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_spectra.json
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_spectra.svg
sub-01/eeg/figures/sub-01_task-rest_desc-ssgc_tests.json
sub-01/eeg/figures/sub-01_task-rest_desc-trgc_agreement.json
sub-01/eeg/figures/sub-01_task-rest_desc-trgc_matrix.json
sub-01/eeg/figures/sub-01_task-rest_desc-trgc_matrix.svg
sub-01/eeg/figures/sub-01_task-rest_desc-wdtf_tests.json
sub-01/eeg/figures/sub-01_task-rest_desc-wdtf_tf.json
sub-01/eeg/figures/sub-01_task-rest_desc-wdtf_tf.svg
sub-01/eeg/figures/sub-01_task-rest_diagnostics.json
sub-01/eeg/sub-01_task-rest_desc-dtf_conn.json
sub-01/eeg/sub-01_task-rest_desc-dtf_conn.nc
sub-01/eeg/sub-01_task-rest_desc-dtf_edges.tsv
sub-01/eeg/sub-01_task-rest_desc-gc_conn.json
sub-01/eeg/sub-01_task-rest_desc-gc_conn.nc
sub-01/eeg/sub-01_task-rest_desc-gc_edges.tsv
sub-01/eeg/sub-01_task-rest_desc-gpdc_conn.json
sub-01/eeg/sub-01_task-rest_desc-gpdc_conn.nc
sub-01/eeg/sub-01_task-rest_desc-gpdc_edges.tsv
sub-01/eeg/sub-01_task-rest_desc-imcoh_conn.json
sub-01/eeg/sub-01_task-rest_desc-imcoh_conn.nc
sub-01/eeg/sub-01_task-rest_desc-imcoh_edges.tsv
sub-01/eeg/sub-01_task-rest_desc-pdc_conn.json
sub-01/eeg/sub-01_task-rest_desc-pdc_conn.nc
sub-01/eeg/sub-01_task-rest_desc-pdc_edges.tsv
sub-01/eeg/sub-01_task-rest_desc-rpdc_conn.json
sub-01/eeg/sub-01_task-rest_desc-rpdc_conn.nc
sub-01/eeg/sub-01_task-rest_desc-rpdc_edges.tsv
sub-01/eeg/sub-01_task-rest_desc-ssgc_conn.json
sub-01/eeg/sub-01_task-rest_desc-ssgc_conn.nc
sub-01/eeg/sub-01_task-rest_desc-ssgc_edges.tsv
sub-01/eeg/sub-01_task-rest_desc-trgc_conn.json
sub-01/eeg/sub-01_task-rest_desc-trgc_conn.nc
sub-01/eeg/sub-01_task-rest_desc-trgc_edges.tsv
sub-01/eeg/sub-01_task-rest_desc-wdtf_conn.json
sub-01/eeg/sub-01_task-rest_desc-wdtf_conn.nc
sub-01/eeg/sub-01_task-rest_desc-wdtf_edges.tsv
sub-01/figures/sub-01_desc-summary_errors.json
sub-01/figures/sub-01_desc-summary_overview.json
sub-01.html
The edge tables#
One row per directed pair and band (or one broadband row for methods without a frequency
axis): the band value, its p-value, the corrected p-value and the decision. A time-resolved
method (wdtf here; adtf, tpdc) has one row per pair, band and time point. On a continuous record
it is not tested: the surrogate test shuffles 5 s blocks and fits the observed value on them,
which leaves no time points of the result. Its test columns are n/a and its sidecar says why
(StatisticsNote); on epoched data each time point is tested against shuffled trials.
unit = root / "sub-01" / "eeg"
edges = pd.read_csv(unit / "sub-01_task-rest_desc-gc_edges.tsv", sep="\t")
print(edges.to_string(index=False))
source target band value p p_adj significant
precuneus-lh postcentral-lh broadband 0.412847 0.004167 0.012500 True
precuneus-lh superiorfrontal-lh broadband 0.000792 0.841667 0.912500 False
precuneus-lh STN-L broadband 0.018783 0.004167 0.012500 True
postcentral-lh precuneus-lh broadband 0.004100 0.004167 0.012500 True
postcentral-lh superiorfrontal-lh broadband 0.001385 0.379167 0.583333 False
postcentral-lh STN-L broadband 0.040654 0.004167 0.012500 True
superiorfrontal-lh precuneus-lh broadband 0.001189 0.383333 0.583333 False
superiorfrontal-lh postcentral-lh broadband 0.000695 0.912500 0.912500 False
superiorfrontal-lh STN-L broadband 0.000712 0.870833 0.912500 False
STN-L precuneus-lh broadband 0.001062 0.437500 0.583333 False
STN-L postcentral-lh broadband 0.001376 0.208333 0.500000 False
STN-L superiorfrontal-lh broadband 0.001319 0.400000 0.583333 False
All methods against the truth#
The true influences are precuneus -> postcentral and postcentral -> STN; the pair precuneus ->
STN is indirect, and superiorfrontal is not connected. For every tested method, the beta-low
band (13-20 Hz; broadband for gc, which has no frequency axis) of subject 01 as a matrix,
read from the result file (_conn.nc), with the decisions of the edge table marked by *:
FDR-BH at 0.05 (the defaults of [statistics]) over the 12 directed pairs of one method and
one band (for imcoh over its 6 pairs, because its two directions repeat one test).
The values of different methods are on different scales and mean different things (a share of a
spectrum, a variance ratio, a coherence), so every panel has its own colour bar, which names the
method and the band; compare where each method puts its largest values, not the numbers. imcoh
is signed and drawn in red and blue around zero: the two directions of a pair have the same
magnitude and opposite signs. Its edge table and its test use the magnitude.
BETA_LOW = (13.0, 20.0)
tables = {}
for method in METHODS:
path = unit / f"sub-01_task-rest_desc-{method}_edges.tsv"
table = pd.read_csv(path, sep="\t")
if "time" not in table: # time-resolved results are descriptive here
band = "beta_low" if "beta_low" in set(table["band"]) else table["band"].iloc[0]
tables[method] = table[table["band"] == band]
n_cols = 4
n_rows = int(np.ceil(len(tables) / n_cols))
fig, axes = plt.subplots(n_rows, n_cols, figsize=(4.2 * n_cols, 3.6 * n_rows), layout="constrained")
for ax in np.ravel(axes)[len(tables) :]:
ax.remove()
summary = []
for ax, (method, table) in zip(np.ravel(axes), tables.items(), strict=False):
result = dirconn.Connectivity.from_netcdf(unit / f"sub-01_task-rest_desc-{method}_conn.nc")
is_significant = table["significant"].astype(str).eq("True")
significant = np.zeros((len(result.source), len(result.target)), dtype=bool)
for row, flag in zip(table.itertuples(), is_significant, strict=True):
significant[result.source.index(row.source), result.target.index(row.target)] = flag
where = {"band": BETA_LOW} if result.is_frequency_resolved else {}
result.plot(ax=ax, significance=significant, **where)
is_true = [(r.source, r.target) in true_edges for r in table.itertuples()]
true_values = table["value"][is_true]
other_values = table["value"][[not t for t in is_true]]
summary.append(
{
"method": method,
"band": table["band"].iloc[0],
"true edges above every other pair": bool(true_values.min() > other_values.max()),
"significant true": int(is_significant[is_true].sum()),
"significant other": int(is_significant[[not t for t in is_true]].sum()),
}
)
print(pd.DataFrame(summary).to_string(index=False))

method band true edges above every other pair significant true significant other
gc broadband True 2 2
dtf beta_low False 2 2
pdc beta_low True 2 2
gpdc beta_low True 2 2
rpdc beta_low True 2 3
ssgc beta_low True 2 2
imcoh beta_low False 2 6
In this run the two largest values of gc, PDC, gPDC, rPDC and SSGC are the two true influences.
DTF puts the indirect precuneus -> STN above postcentral -> STN: it counts the flow through
postcentral by definition. imcoh gives the reversed directions the same magnitude, so it ranks
no direction. The cells marked * are true influences and other pairs among the three nodes
of the chain; none involves superiorfrontal.
Diagnostics, control and provenance#
The diagnostics file holds the share of valid samples, each channel’s spread and the spectral
dynamic range check; the time-reversal control is an ordinary result (desc-trgc); every run
directory has provenance.json (command, times, host, versions, inputs and their hashes).
import json # noqa: E402
diagnostics = json.loads((unit / "figures" / "sub-01_task-rest_diagnostics.json").read_text())
print({k: diagnostics[k] for k in ("valid_fraction", "n_times", "sfreq")})
for check in diagnostics["checks"]:
print("diagnostic:", check["name"], check["status"])
run_dir = sorted((root / "logs").glob("run-*"))[-1]
provenance = json.loads((run_dir / "provenance.json").read_text())
print("command:", " ".join(provenance["command"]))
print("tasks:", provenance["tasks"])
progress = pd.read_json(run_dir / "progress.jsonl", lines=True)
print(progress[["label", "status", "seconds"]].to_string(index=False))
{'valid_fraction': 1.0, 'n_times': 15000, 'sfreq': 250.0}
diagnostic: spectral_dynamic_range pass
command: dirconn-bids /tmp/dirconn_showcase_3b32w2kc/bids /tmp/dirconn_showcase_3b32w2kc/out participant --config /tmp/dirconn_showcase_3b32w2kc/dirconn.toml --skip-bids-validation --nprocs 4
tasks: {'done': 18, 'skipped': 0, 'failed': 0}
label status seconds
sub-01_task-rest:controls done 2.059578
sub-01_task-rest:gc done 48.098000
sub-01_task-rest:dtf done 18.566740
sub-01_task-rest:pdc done 18.670227
sub-01_task-rest:gpdc done 19.789852
sub-01_task-rest:rpdc done 17.559807
sub-01_task-rest:ssgc done 55.336921
sub-01_task-rest:imcoh done 3.476369
sub-01_task-rest:wdtf done 1.337032
sub-02_task-rest:controls done 2.187158
sub-02_task-rest:gc done 49.323130
sub-02_task-rest:dtf done 16.383807
sub-02_task-rest:pdc done 20.878025
sub-02_task-rest:gpdc done 14.813483
sub-02_task-rest:rpdc done 16.485995
sub-02_task-rest:ssgc done 31.250147
sub-02_task-rest:imcoh done 3.079588
sub-02_task-rest:wdtf done 1.656054
Limitations#
One command ran eight methods on every recording of the dataset, tested each band of the seven that are not time resolved against surrogates and wrote results that a second run would skip. It does not choose the methods, bands or model order for you: the defaults are a starting point, set in
--configor--set, and the run’sdirconn.tomlrecords what was used.The comparison above is one short simulation with a known truth, not an evaluation of the methods (see the benchmark in the documentation). Methods answer different questions: imcoh is not conditional on the other nodes and is blind to zero-lag coupling, gc is not spectral, and DTF counts indirect paths (precuneus -> STN here goes through postcentral).
In the full version every tested method found both true influences significant, and also two to four pairs that are not true influences: all of them among the three nodes of the chain (the indirect precuneus -> STN and reversed directions), none involving the unconnected superiorfrontal. With observation noise the best VAR of coupled signals has small real terms where the network has none, and 60 s are enough to find them (tutorial 16). imcoh gives both directions of a pair the same magnitude, so its “significant” says coupled, not which way.
The surrogate test here shuffles 5 s blocks of a 60 s record (12 blocks); with 30 s (the quick version) only 6 blocks are left to shuffle, which limits how small a p-value can get.
All of these are predictive, not interventional, measures. Each result lists the assumptions it checked (
not_checkedmeans not tested, not that it holds):
stationarity not_checked
linearity not_checked
sampling_adequacy pass 68 coefficients per equation are estimated from 14983 observations (ratio 0.00454; 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 519.1 over lags 1 to 27 (df 160, p = 1.6e-39); largest absolute residual autocorrelation 0.075 (warning when p < 0.05 and it exceeds 0.1).
order_stability pass the direction of every pair at order 17 agrees with models of order 34.
order_selection pass the bic criterion chose order 17 of 30 candidates.
Total running time of the script: (1 minutes 53.635 seconds)