.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_17_one_command_all_methods.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_tutorials_plot_17_one_command_all_methods.py: ========================================================== 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]"``). .. GENERATED FROM PYTHON SOURCE LINES 23-28 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). .. GENERATED FROM PYTHON SOURCE LINES 28-59 .. code-block:: Python 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) } .. rst-class:: sphx-glr-script-out .. code-block:: none dirconn 0.2.0, numpy 2.5.5 .. GENERATED FROM PYTHON SOURCE LINES 60-66 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 :func:`~dirconn.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. .. GENERATED FROM PYTHON SOURCE LINES 66-97 .. code-block:: Python 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()) .. rst-class:: sphx-glr-script-out .. code-block:: none 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 .. GENERATED FROM PYTHON SOURCE LINES 98-127 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`` (``trgc`` is 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. Like ``wdtf`` they 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 ``methods`` when the time is there; ``dirconn-bids`` fills 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 below ``0.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. .. GENERATED FROM PYTHON SOURCE LINES 127-143 .. code-block:: Python 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")) .. rst-class:: sphx-glr-script-out .. code-block:: none 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 .. GENERATED FROM PYTHON SOURCE LINES 144-152 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). .. GENERATED FROM PYTHON SOURCE LINES 152-160 .. code-block:: Python 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) .. rst-class:: sphx-glr-script-out .. code-block:: none 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 .. GENERATED FROM PYTHON SOURCE LINES 161-169 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/_diagnostics.json`` and the time-reversal control ``desc-trgc``. Per run: ``logs/run-