.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_08_sources_and_sinks.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_08_sources_and_sinks.py: ========================================= Sources and sinks: reading them with care ========================================= A common way to summarise directed connectivity is to say which regions are *sources* (they send more than they receive) and which are *sinks*, and to show it on the brain or between networks. This tutorial computes these summaries (``net_direction`` and ``degree_imbalance``), draws them (a chord diagram between resting-state networks and a map of the cortical surface), and then does what the figures cannot do on their own: compares them with the known truth of a simulation, once with the regions' own time series and once with regions estimated from sensors. Every source/sink figure of dirconn carries the caption "Predictive, not causal. No leakage correction." on purpose, and this tutorial shows why. It needs the MNE ``sample`` dataset (about 1.5 GB), which dirconn never downloads without being asked. .. GENERATED FROM PYTHON SOURCE LINES 17-20 .. code-block:: Python NEEDS_SAMPLE = True .. GENERATED FROM PYTHON SOURCE LINES 21-23 Setup ----- .. GENERATED FROM PYTHON SOURCE LINES 23-42 .. code-block:: Python import os import matplotlib.pyplot as plt import numpy as np import pandas as pd from dirconn.datasets import require_sample import dirconn from dirconn import viz from dirconn.simulation import simulate_on_head from dirconn.simulation.headmodel import load_head_model from dirconn.simulation.inverse import roi_series 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__}") print("sample data:", require_sample()) .. rst-class:: sphx-glr-script-out .. code-block:: none dirconn 0.2.0, numpy 2.5.5 sample data: /home/runner/mne_data/MNE-sample-data .. GENERATED FROM PYTHON SOURCE LINES 43-49 A network with known sources and sinks -------------------------------------- The shipped scenario ``random_10`` has ten regions and fifteen influences between them, drawn at random. We count, for every region, how many influences leave it and how many arrive: a region with only outgoing influences is a source in the truth, one with only incoming influences is a sink. .. GENERATED FROM PYTHON SOURCE LINES 49-69 .. code-block:: Python spec = load_scenario("random_10") names = list(spec.network.names) head = load_head_model("eeg") sim = simulate_on_head( spec.network, head, sfreq=spec.sfreq, n_times=int((30.0 if QUICK else 60.0) * spec.sfreq), seed=SEED, dynamics=spec.dynamics, snr_db=spec.snr_db, n_background=10, ) truth = np.nan_to_num(sim.truth.values[:, :, 0, 0]) known = pd.DataFrame( {"edges out": truth.sum(axis=1).astype(int), "edges in": truth.sum(axis=0).astype(int)}, index=names, ) print(known) .. rst-class:: sphx-glr-script-out .. code-block:: none edges out edges in caudalmiddlefrontal-lh 1 1 paracentral-lh 4 0 parsorbitalis-rh 0 0 transversetemporal-rh 3 3 superiorfrontal-rh 3 0 rostralanteriorcingulate-rh 2 2 parstriangularis-lh 1 2 temporalpole-rh 1 1 cuneus-lh 0 2 bankssts-rh 0 4 .. GENERATED FROM PYTHON SOURCE LINES 70-74 Two sets of region time series ------------------------------ As in tutorial 7: the regions' own activity (the oracle), and the regions estimated from the simulated sensors with an inverse solution. Granger causality is estimated on both. .. GENERATED FROM PYTHON SOURCE LINES 74-82 .. code-block:: Python ORDER = 4 if QUICK else 5 oracle = sim.roi_observations(snr_db=spec.snr_db, seed=SEED + 1) estimated = roi_series(sim.data, head, names) results = { "oracle": dirconn.gc(oracle, order=ORDER, check_order_stability=False), "from sensors": dirconn.gc(estimated, order=ORDER, check_order_stability=False), } .. rst-class:: sphx-glr-script-out .. code-block:: none /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/dirconn/methods/granger.py:313: DirconnWarning: The residuals of the VAR fit are not white: Hosking portmanteau statistic 1438 over lags 1 to 15 (df 1000, p = 2.34e-18); largest absolute residual autocorrelation 0.113 (warning when p < 0.05 and it exceeds 0.1). The model order may be too low or the process not a finite VAR (for example with observation noise); estimates and asymptotic tests built on it are less reliable. return GC(**params).fit(data) /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/dirconn/methods/granger.py:313: DirconnWarning: The residuals of the VAR fit are not white: Hosking portmanteau statistic 3781 over lags 1 to 15 (df 1000, p = 0); largest absolute residual autocorrelation 0.178 (warning when p < 0.05 and it exceeds 0.1). The model order may be too low or the process not a finite VAR (for example with observation noise); estimates and asymptotic tests built on it are less reliable. return GC(**params).fit(data) .. GENERATED FROM PYTHON SOURCE LINES 83-91 Net direction and degree imbalance ---------------------------------- ``net_direction()`` is, for every pair, the influence of one on the other minus the reverse; it is antisymmetric. ``degree_imbalance()`` sums, for every region, the influences it sends and the influences it receives and takes ``log(sent) - log(received)``: positive for a source, negative for a sink. By default every defined edge counts, with its raw value; a boolean ``mask`` chooses the edges instead, and the choice is recorded in the result's provenance. Below the raw values and only the edges with a value of at least 0.05: .. GENERATED FROM PYTHON SOURCE LINES 91-103 .. code-block:: Python imbalance = {label: result.degree_imbalance() for label, result in results.items()} masked = { label: result.degree_imbalance(mask=result.values[:, :, 0, 0] >= 0.05) for label, result in results.items() } table = known.copy() for label in results: table[f"{label}, all edges"] = imbalance[label].values[:, 0, 0] table[f"{label}, edges >= 0.05"] = masked[label].values[:, 0, 0] print(table.round(2).to_string()) print("NaN: a region without a counted edge in or out has no ratio") .. rst-class:: sphx-glr-script-out .. code-block:: none edges out edges in oracle, all edges oracle, edges >= 0.05 from sensors, all edges from sensors, edges >= 0.05 caudalmiddlefrontal-lh 1 1 -0.56 -0.64 -1.24 NaN paracentral-lh 4 0 4.25 NaN 2.83 NaN parsorbitalis-rh 0 0 -0.37 NaN 0.14 NaN transversetemporal-rh 3 3 0.16 0.03 0.25 NaN superiorfrontal-rh 3 0 4.05 NaN 0.05 NaN rostralanteriorcingulate-rh 2 2 -0.01 0.15 -0.66 NaN parstriangularis-lh 1 2 -1.82 NaN -0.52 NaN temporalpole-rh 1 1 -0.63 -0.68 0.35 NaN cuneus-lh 0 2 -2.53 NaN -0.31 NaN bankssts-rh 0 4 -3.93 NaN -1.08 NaN NaN: a region without a counted edge in or out has no ratio .. GENERATED FROM PYTHON SOURCE LINES 104-109 Look at the thresholded columns: a region with no counted edge into it (or out of it) has no ratio, because the logarithm of zero does not exist, so its value is NaN and the map leaves it uncoloured. A threshold therefore removes exactly the clearest sources and sinks, the regions that only send or only receive. Whether that is what you want depends on the question; the point is that the choice changes the picture, and that the figure must say which one was made. .. GENERATED FROM PYTHON SOURCE LINES 111-114 The regions with a clear truth (several influences out and none in, or the reverse) are the ones to look at. For them, with the regions' own series the sign of the imbalance is that of the truth. With the regions estimated from sensors, compare the sizes: .. GENERATED FROM PYTHON SOURCE LINES 114-128 .. code-block:: Python clear = known[ ((known["edges out"] >= 2) & (known["edges in"] == 0)) | ((known["edges in"] >= 2) & (known["edges out"] == 0)) ].index comparison = pd.DataFrame( { "truth": ["source" if known.loc[n, "edges out"] > 0 else "sink" for n in clear], "oracle": [imbalance["oracle"].sel(node=n).item() for n in clear], "from sensors": [imbalance["from sensors"].sel(node=n).item() for n in clear], }, index=clear, ) print(comparison.round(2)) .. rst-class:: sphx-glr-script-out .. code-block:: none truth oracle from sensors paracentral-lh source 4.25 2.83 superiorfrontal-rh source 4.05 0.05 cuneus-lh sink -2.53 -0.31 bankssts-rh sink -3.93 -1.08 .. GENERATED FROM PYTHON SOURCE LINES 129-132 The imbalances of the sensor-based estimate point the same way for these regions but are much smaller in size, and for one of them close to zero. The overall pattern of the brain map therefore changes with the data the regions come from. .. GENERATED FROM PYTHON SOURCE LINES 134-140 Between networks ---------------- Regions can be grouped, for example into the seven resting-state networks of Yeo and colleagues (2011). ``viz.yeo_groups`` assigns every Desikan-Killiany region to the network that holds most of its vertices on the template brain, computed from the annotation files of the sample dataset. For regions that straddle networks, the table says how much of the region the network holds. .. GENERATED FROM PYTHON SOURCE LINES 140-144 .. code-block:: Python yeo = viz.yeo_networks().loc[names] print(yeo.round(2)) groups = viz.yeo_groups(names) .. rst-class:: sphx-glr-script-out .. code-block:: none network share dominant caudalmiddlefrontal-lh Default 0.46 False paracentral-lh Somatomotor 0.82 True parsorbitalis-rh Default 0.55 True transversetemporal-rh Somatomotor 1.00 True superiorfrontal-rh Default 0.48 False rostralanteriorcingulate-rh Default 0.85 True parstriangularis-lh Default 0.53 True temporalpole-rh Limbic 0.98 True cuneus-lh Visual 1.00 True bankssts-rh Somatomotor 0.35 False .. GENERATED FROM PYTHON SOURCE LINES 145-147 The chord diagram shows, between networks, the stronger direction of every pair. Look at the caption at the bottom of the figure: it is there by design. .. GENERATED FROM PYTHON SOURCE LINES 147-149 .. code-block:: Python fig = viz.chord_diagram(results["oracle"], groups, measure="net_direction") .. image-sg:: /auto_tutorials/images/sphx_glr_plot_08_sources_and_sinks_001.png :alt: plot 08 sources and sinks :srcset: /auto_tutorials/images/sphx_glr_plot_08_sources_and_sinks_001.png, /auto_tutorials/images/sphx_glr_plot_08_sources_and_sinks_001_2_00x.png 2.00x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 150-155 On the cortical surface ----------------------- ``degree_imbalance_map`` colours every region by its imbalance, red for sources and blue for sinks, on the template brain, with MNE's 3D plot (this needs a 3D backend of MNE and takes a little while). The title says which edges were counted. Both maps use the same colour scale. .. GENERATED FROM PYTHON SOURCE LINES 155-164 .. code-block:: Python vmax = max(np.nanmax(np.abs(v.values)) for v in imbalance.values()) fig, axes = plt.subplots(1, 2, figsize=(15.0, 5.0), layout="constrained") for ax, (label, values) in zip(axes, imbalance.items(), strict=True): brain = viz.degree_imbalance_map(values, vmax=vmax, degrees="all edges, raw values") ax.imshow(brain.screenshot()) brain.close() ax.axis("off") ax.set_title(f"regions: {label}") .. image-sg:: /auto_tutorials/images/sphx_glr_plot_08_sources_and_sinks_002.png :alt: regions: oracle, regions: from sensors :srcset: /auto_tutorials/images/sphx_glr_plot_08_sources_and_sinks_002.png, /auto_tutorials/images/sphx_glr_plot_08_sources_and_sinks_002_2_00x.png 2.00x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 165-180 Limitations ----------- * A source or a sink here is a statement about **prediction**: the past of the region helps to predict others more than the other way round. It is not a statement that the region drives the others. Tutorial 5 showed influences that are not there, and tutorial 7 showed leakage; neither is corrected in these figures. * With the regions' own series the summaries recover the sources and sinks that were built into the simulation. With regions estimated from sensors the same summaries are weaker for the same regions and the picture differs. This was seen for one simulation of one network on one head model with one inverse method; how much it changes in general is not shown here. * The summaries depend on choices: which edges are counted (all, or only the strong ones), how the regions are grouped, how the regions were obtained. The figures state the first two; the third is yours to state. * Every result lists the assumptions it rests on; ``not_checked`` means that the library did not test an assumption, not that it holds: .. GENERATED FROM PYTHON SOURCE LINES 180-183 .. code-block:: Python for check in results["from sensors"].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 50 coefficients per equation are estimated from 5995 observations (ratio 0.00834; the rule of thumb is at most 0.1). instantaneous_coupling not_checked causal_sufficiency not_checked filtering not_checked residual_whiteness warn Hosking portmanteau statistic 3781 over lags 1 to 15 (df 1000, p = 0); largest absolute residual autocorrelation 0.178 (warning when p < 0.05 and it exceeds 0.1). .. GENERATED FROM PYTHON SOURCE LINES 184-186 * Not tested here: the significance of an imbalance (a ``mask`` made from a significance test can be passed to ``degree_imbalance``), and anything about real recordings. .. GENERATED FROM PYTHON SOURCE LINES 186-187 .. code-block:: Python plt.close("all") .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 11.574 seconds) .. _sphx_glr_download_auto_tutorials_plot_08_sources_and_sinks.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_08_sources_and_sinks.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_08_sources_and_sinks.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_08_sources_and_sinks.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_