.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_01_first_directed_connectivity.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_01_first_directed_connectivity.py: ================================ 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. .. GENERATED FROM PYTHON SOURCE LINES 15-20 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. .. GENERATED FROM PYTHON SOURCE LINES 20-36 .. 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 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__}") .. rst-class:: sphx-glr-script-out .. code-block:: none dirconn 0.2.0, numpy 2.5.5 .. GENERATED FROM PYTHON SOURCE LINES 37-43 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. .. GENERATED FROM PYTHON SOURCE LINES 43-56 .. code-block:: Python 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), } .. GENERATED FROM PYTHON SOURCE LINES 57-62 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. .. GENERATED FROM PYTHON SOURCE LINES 62-78 .. code-block:: Python SFREQ = 100.0 DURATION_S = 30.0 if QUICK else 120.0 SNR_DB = 10.0 sim = simulate( network, sfreq=SFREQ, n_times=int(DURATION_S * SFREQ), seed=SEED, dynamics=dynamics, snr_db=SNR_DB, n_background=0, node_scale="unit", ) data = sim.roi_observations(snr_db=SNR_DB, seed=SEED + 1) print(data) .. rst-class:: sphx-glr-script-out .. code-block:: none TimeSeries(n_trials=1, n_channels=3, n_times=12000, sfreq=100, segmentation='continuous') .. GENERATED FROM PYTHON SOURCE LINES 79-86 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. .. GENERATED FROM PYTHON SOURCE LINES 88-94 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). .. GENERATED FROM PYTHON SOURCE LINES 94-98 .. code-block:: Python result = dirconn.gc(data, order="bic") print(result) print("model order:", result.provenance.model_order) .. rst-class:: sphx-glr-script-out .. code-block:: none Connectivity(method='gc', shape=3x3x1x1, complex=False) model order: 6 .. GENERATED FROM PYTHON SOURCE LINES 99-100 The result as a table, and as a picture next to the truth. .. GENERATED FROM PYTHON SOURCE LINES 100-103 .. code-block:: Python table = pd.DataFrame(result.values[:, :, 0, 0], index=result.source, columns=result.target) print(table.round(3)) .. rst-class:: sphx-glr-script-out .. code-block:: none 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 .. GENERATED FROM PYTHON SOURCE LINES 104-106 .. code-block:: Python left, right = result.plot(kind="truth_comparison", truth=sim.truth) .. image-sg:: /auto_tutorials/images/sphx_glr_plot_01_first_directed_connectivity_001.png :alt: plot 01 first directed connectivity :srcset: /auto_tutorials/images/sphx_glr_plot_01_first_directed_connectivity_001.png, /auto_tutorials/images/sphx_glr_plot_01_first_directed_connectivity_001_2_00x.png 2.00x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 107-115 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. .. GENERATED FROM PYTHON SOURCE LINES 117-121 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. .. GENERATED FROM PYTHON SOURCE LINES 121-126 .. code-block:: Python provenance = result.provenance print("method:", provenance.method) print("order:", provenance.model_order) print("claim:", provenance.claim) .. rst-class:: sphx-glr-script-out .. code-block:: none method: gc order: 6 claim: predictive, not interventional .. GENERATED FROM PYTHON SOURCE LINES 127-128 Saving and loading a result keeps the values, the axes and the provenance. .. GENERATED FROM PYTHON SOURCE LINES 128-135 .. code-block:: Python 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) .. rst-class:: sphx-glr-script-out .. code-block:: none reloaded: True gc .. GENERATED FROM PYTHON SOURCE LINES 136-143 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_checked`` means that it did not test the assumption, not that the assumption holds. They are printed with the result: .. GENERATED FROM PYTHON SOURCE LINES 143-146 .. code-block:: Python for check in result.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 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. .. GENERATED FROM PYTHON SOURCE LINES 147-151 * 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). .. GENERATED FROM PYTHON SOURCE LINES 151-152 .. code-block:: Python plt.close("all") .. _sphx_glr_download_auto_tutorials_plot_01_first_directed_connectivity.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_01_first_directed_connectivity.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_01_first_directed_connectivity.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_01_first_directed_connectivity.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_