.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_15_multivariate_te.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_15_multivariate_te.py: ================================================================ Multivariate transfer entropy: indirect paths and shared drivers ================================================================ Pairwise transfer entropy (tutorial 12) looks at two signals at a time. When A drives B and B drives C, the past of A tells something about C, because it passes through B, and a pairwise measure reports A -> C. When A drives both B and C, B and C share information that neither sends to the other. Tutorial 5 showed the same two traps for Granger causality and the control: put the other regions into the condition. For transfer entropy the full condition is costly: every added signal adds dimensions, and the nearest-neighbour estimator degrades quickly with the dimension. The **multivariate** mode of :class:`~dirconn.TE` (its default) instead *selects* the past samples that carry information about each target, one at a time, and tests every step by permutation (the algorithm of IDTxl, Novelli et al. 2019). The result is a network of selected sources with their transfer entropy; a source that is not selected is zero. .. GENERATED FROM PYTHON SOURCE LINES 21-26 Setup ----- The two shipped scenarios of tutorial 5, simulated at the region level. ``N_PERM`` is the number of permutations of every test: IDTxl's defaults (200 and 500) are the library's defaults too, but they take long, and 99 already reaches a level of 0.01 per test. .. GENERATED FROM PYTHON SOURCE LINES 26-109 .. code-block:: Python import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import dirconn from dirconn import TE 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 DURATION_S = 15.0 if QUICK else 40.0 MAX_ORDER = 4 if QUICK else 6 # candidate lags of the target past N_PERM = 19 if QUICK else 99 PERMUTATIONS = { "n_perm_max_stat": N_PERM, "n_perm_min_stat": N_PERM, "n_perm_omnibus": N_PERM, "n_perm_max_seq": N_PERM, } WORKERS = -1 # the targets in parallel processes (needs joblib, extra "parallel") print(f"dirconn {dirconn.__version__}, numpy {np.__version__}") def run_scenario(name): """Simulate a shipped scenario; return its specification, the simulation and the region data.""" spec = load_scenario(name) sim = dirconn.simulate( spec.network, sfreq=spec.sfreq, n_times=int(DURATION_S * spec.sfreq), seed=SEED, dynamics=spec.dynamics, snr_db=spec.snr_db, n_background=0, node_scale="unit", ) return spec, sim, sim.roi_observations(snr_db=spec.snr_db, seed=SEED + 1) def both_modes(data): """Pairwise and multivariate transfer entropy of the same data.""" return { "pairwise": TE(mode="pairwise", max_delay=3, workers=WORKERS).fit(data), "multivariate (default)": TE( max_order=MAX_ORDER, max_delay=3, workers=WORKERS, seed=SEED, **PERMUTATIONS ).fit(data), } def show(estimates): """One panel per estimate, on one colour scale: both are transfer entropy, in nats.""" connectivity_grids(list(estimates.values()), names=list(estimates)) def values_table(estimates, cells): """The value of some named cells in several estimates; ``cells`` is {label: (source, target)}.""" rows = {} for label, (source, target) in cells.items(): rows[label] = { name: result.values[result.source.index(source), result.target.index(target), 0, 0] for name, result in estimates.items() } return pd.DataFrame(rows).T def selection_table(result): """What the multivariate mode selected for every target, with its omnibus test.""" details = result.provenance.details names = result.source rows = {} for j, target in enumerate(names): rows[target] = { "target lags": details["selected_target_lags"][j], "sources (lag)": [f"{names[i]} ({lag})" for i, lag in details["selected_sources"][j]], "omnibus TE": round(details["omnibus"][j]["te"], 3), "omnibus p": round(details["omnibus"][j]["p"], 3), } return pd.DataFrame(rows).T .. rst-class:: sphx-glr-script-out .. code-block:: none dirconn 0.2.0, numpy 2.5.5 .. GENERATED FROM PYTHON SOURCE LINES 110-115 An indirect path ---------------- In the chain A drives B and B drives C, each one sample (10 ms) later; A does not drive C. Both estimates are transfer entropy in nats and share one colour scale; raw pairwise values can be slightly negative, so the scale is centred on zero (red above, blue below). .. GENERATED FROM PYTHON SOURCE LINES 115-126 .. code-block:: Python spec, sim, data = run_scenario("chain") A, B, C = spec.network.names print(f"A = {A}, B = {B}, C = {C}") estimates = both_modes(data) show(estimates) print( values_table(estimates, {"A -> C (no such influence)": (A, C), "A -> B (real)": (A, B)}).round( 3 ) ) .. image-sg:: /auto_tutorials/images/sphx_glr_plot_15_multivariate_te_001.png :alt: pairwise, multivariate (default) :srcset: /auto_tutorials/images/sphx_glr_plot_15_multivariate_te_001.png, /auto_tutorials/images/sphx_glr_plot_15_multivariate_te_001_2_00x.png 2.00x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none A = transversetemporal-rh, B = cuneus-rh, C = transversetemporal-lh pairwise multivariate (default) A -> C (no such influence) 0.061 0.000 A -> B (real) 0.187 0.155 .. GENERATED FROM PYTHON SOURCE LINES 127-132 Both modes show the two true influences, A -> B and B -> C, as their two strongest cells. The pairwise mode also reports A -> C, with about a fifth of the value of A -> B in this run, and small values in the reverse directions. The multivariate mode, once it has selected the past of B for C, finds nothing left in the past of A, and A -> C is zero, like every source it did not select. The selection per target: .. GENERATED FROM PYTHON SOURCE LINES 132-136 .. code-block:: Python pd.set_option("display.width", 140) pd.set_option("display.max_columns", None) print(selection_table(estimates["multivariate (default)"])) .. rst-class:: sphx-glr-script-out .. code-block:: none target lags sources (lag) omnibus TE omnibus p transversetemporal-rh [1, 3] [] 0.0 1.0 cuneus-rh [1, 2, 3, 6] [transversetemporal-rh (1)] 0.155 0.01 transversetemporal-lh [1, 2, 3, 5, 6] [cuneus-rh (1), cuneus-rh (2)] 0.138 0.01 .. GENERATED FROM PYTHON SOURCE LINES 137-141 A shared driver --------------- In ``common_driver`` region A drives B (10 ms) and C (20 ms); B and C are not connected, and D is unconnected. .. GENERATED FROM PYTHON SOURCE LINES 141-152 .. code-block:: Python spec, sim, data = run_scenario("common_driver") A, B, C, D = spec.network.names print(f"A = {A}, B = {B}, C = {C}, D = {D}") estimates = both_modes(data) show(estimates) print( values_table(estimates, {"B -> C (no such influence)": (B, C), "A -> C (real)": (A, C)}).round( 3 ) ) .. image-sg:: /auto_tutorials/images/sphx_glr_plot_15_multivariate_te_002.png :alt: pairwise, multivariate (default) :srcset: /auto_tutorials/images/sphx_glr_plot_15_multivariate_te_002.png, /auto_tutorials/images/sphx_glr_plot_15_multivariate_te_002_2_00x.png 2.00x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none A = transversetemporal-rh, B = cuneus-rh, C = transversetemporal-lh, D = rostralanteriorcingulate-lh pairwise multivariate (default) B -> C (no such influence) 0.046 0.000 A -> C (real) 0.165 0.175 .. GENERATED FROM PYTHON SOURCE LINES 153-157 Again both modes show the two true influences, A -> B and A -> C, as their two strongest cells. The pairwise mode also reports B -> C, with about a fifth of the value of A -> C in this run, and small values for every other pair. The multivariate mode selects A for B and for C and nothing else: B -> C and every pair with D are zero. .. GENERATED FROM PYTHON SOURCE LINES 157-159 .. code-block:: Python print(selection_table(estimates["multivariate (default)"])) .. rst-class:: sphx-glr-script-out .. code-block:: none target lags sources (lag) omnibus TE omnibus p transversetemporal-rh [1, 3] [] 0.0 1.0 cuneus-rh [1, 2, 3, 6] [transversetemporal-rh (1)] 0.153 0.01 transversetemporal-lh [1, 3, 4] [transversetemporal-rh (2), transversetemporal... 0.175 0.01 rostralanteriorcingulate-lh [1, 3] [] 0.0 1.0 .. GENERATED FROM PYTHON SOURCE LINES 160-172 Limitations ----------- * On two simulated networks the multivariate mode removed the indirect link of a chain and the link between two regions that share a driver, which the pairwise mode reported. This is one seed of each (a demonstration, not an evaluation). * The result is already a decision: every selected source passed its permutation tests at ``alpha`` (0.05 by default). ``fdr=True`` adds a correction over the targets. Running :func:`dirconn.significance_test` on top would test again. * It is still predictive information transfer between the *recorded* signals: a driver that was not recorded makes the regions it drives look linked (tutorial 5), whatever the mode. Each result lists its assumptions; ``not_checked`` means the library did not test one, not that it holds: .. GENERATED FROM PYTHON SOURCE LINES 172-175 .. code-block:: Python for check in estimates["multivariate (default)"].provenance.assumptions.checks: print(f"{check.name:24s} {check.status:12s} {check.detail}") .. rst-class:: sphx-glr-script-out .. code-block:: none stationarity not_checked linearity not_checked sampling_adequacy not_checked instantaneous_coupling not_checked causal_sufficiency not_checked filtering not_checked .. GENERATED FROM PYTHON SOURCE LINES 176-179 * It is slow: every step estimates the information of every candidate for every permutation. ``workers`` runs the targets in parallel, and ``device="cuda"`` computes the neighbour searches on a GPU with PyTorch (extra ``gpu``). .. GENERATED FROM PYTHON SOURCE LINES 179-180 .. code-block:: Python plt.close("all") .. rst-class:: sphx-glr-timing **Total running time of the script:** (23 minutes 55.739 seconds) .. _sphx_glr_download_auto_tutorials_plot_15_multivariate_te.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_15_multivariate_te.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_15_multivariate_te.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_15_multivariate_te.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_