.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_07_sensors_to_regions.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_07_sensors_to_regions.py: ==================================== From sensors to regions, and leakage ==================================== Recordings are made at sensors, but the questions are about brain regions. The usual bridge is an inverse solution: it estimates the activity of each region from the sensors. This tutorial simulates sensor data from known regions on a real head model, estimates the region time series back from the sensors, and compares the directed connectivity of the estimated series with that of the true ones. Two neighbouring regions show what goes wrong: the estimate of one contains the other, and the connectivity then contains influences that were never there. This tutorial needs the MNE ``sample`` dataset (about 1.5 GB). It is never downloaded by dirconn without being asked; see ``dirconn.datasets.require_sample``. .. GENERATED FROM PYTHON SOURCE LINES 16-19 .. code-block:: Python NEEDS_SAMPLE = True .. GENERATED FROM PYTHON SOURCE LINES 20-22 Setup ----- .. GENERATED FROM PYTHON SOURCE LINES 22-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.diagnostics.regions import centre_distances from dirconn.simulation import simulate_on_head from dirconn.simulation.headmodel import load_head_model from dirconn.simulation.inverse import crosstalk, roi_series 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 print(f"dirconn {dirconn.__version__}, numpy {np.__version__}") print("sample data:", require_sample()) # stops with instructions when the data are missing .. 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-48 A head model ------------ The head model of the sample subject links every cortical region to the 59 EEG sensors: the *leadfield* says how the activity of a region appears at each sensor. It also holds the parcellation into 68 Desikan-Killiany regions. Loading takes a few seconds. .. GENERATED FROM PYTHON SOURCE LINES 48-51 .. code-block:: Python head = load_head_model("eeg") print(f"{head.n_channels} EEG channels, {len(head.roi_names)} regions") .. rst-class:: sphx-glr-script-out .. code-block:: none 59 EEG channels, 68 regions .. GENERATED FROM PYTHON SOURCE LINES 52-57 A scenario with two close regions --------------------------------- The shipped scenario ``leakage_adjacent`` has three regions: Z drives X, and Y is a close neighbour of X that nothing drives. Every influence into Y that an analysis reports is therefore false. The distances are those between the region centres on the head model, in millimetres. .. GENERATED FROM PYTHON SOURCE LINES 57-65 .. code-block:: Python spec = load_scenario("leakage_adjacent") Z, X, Y = spec.network.names print(spec.description) distances = centre_distances(head) index = {name: head.roi_names.index(name) for name in spec.network.names} for a, b in ((X, Y), (Z, X)): print(f"distance {a} - {b}: {distances[index[a], index[b]]:.0f} mm") .. rst-class:: sphx-glr-script-out .. code-block:: none Z -> X is the only edge (0.4, 10 ms). Y is the neighbour of X into whose series X leaks most: cuneus-lh (X) and pericalcarine-lh (Y) are 10 mm apart and the pair is in the leakiest tenth of all region pairs on EEG and on gradiometers (tools/pick_regions.py leakage). Z is far from both and leaks little into them. Nothing drives Y, so every edge into Y that an estimator finds at source level (Z -> Y, X -> Y) is leakage; at region level there is none. distance cuneus-lh - pericalcarine-lh: 10 mm distance transversetemporal-rh - cuneus-lh: 76 mm .. GENERATED FROM PYTHON SOURCE LINES 66-72 Simulate the recording ---------------------- ``simulate_on_head`` lets every region of the network oscillate, projects it through the leadfield to the sensors, adds the activity of other sources in the brain (``n_background``) and noise, so that the sensors have a signal-to-noise ratio of 10 dB. The simulation also keeps the true time series of the regions, which a real recording never has. .. GENERATED FROM PYTHON SOURCE LINES 72-84 .. code-block:: Python 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, ) print(sim.data) .. rst-class:: sphx-glr-script-out .. code-block:: none TimeSeries(n_trials=1, n_channels=59, n_times=6000, sfreq=100, segmentation='continuous') .. GENERATED FROM PYTHON SOURCE LINES 85-92 Two ways to the regions' time series ------------------------------------ * ``sim.roi_observations`` gives the regions' own activity plus a little noise (tutorial 1 did this): the *oracle*, the data we would like to have. * ``roi_series`` is what an analysis of a real recording has to do: estimate the regions from the sensors with an inverse method (here the minimum-norm estimate, with the sign of every source aligned by a principal component, ``"pca_flip"``). .. GENERATED FROM PYTHON SOURCE LINES 92-96 .. code-block:: Python oracle = sim.roi_observations(snr_db=spec.snr_db, seed=SEED + 1) estimated = roi_series(sim.data, head, list(spec.network.names)) print(oracle.names == estimated.names) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 97-102 The same Granger causality on both ---------------------------------- The only true influence is Z -> X. The matrices name the regions: Z is transversetemporal-rh, X cuneus-lh and Y pericalcarine-lh. Both panels are the same measure, so they share one colour bar. oracle: the regions' own series; from sensors: the regions estimated by the inverse method .. GENERATED FROM PYTHON SOURCE LINES 102-124 .. code-block:: Python results = { "oracle": dirconn.gc(oracle, order=5, check_order_stability=False), "from sensors": dirconn.gc(estimated, order=5, check_order_stability=False), } connectivity_grids(list(results.values()), names=list(results)) cells = { "Z -> X (real)": (Z, X), "Z -> Y (no such influence)": (Z, Y), "X -> Y (no such influence)": (X, Y), "Y -> X (no such influence)": (Y, X), } table = pd.DataFrame( { label: { name: result.values[result.source.index(a), result.target.index(b), 0, 0] for name, (a, b) in cells.items() } for label, result in results.items() } ) print(table.round(3)) .. image-sg:: /auto_tutorials/images/sphx_glr_plot_07_sensors_to_regions_001.png :alt: oracle, from sensors :srcset: /auto_tutorials/images/sphx_glr_plot_07_sensors_to_regions_001.png, /auto_tutorials/images/sphx_glr_plot_07_sensors_to_regions_001_2_00x.png 2.00x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none oracle from sensors Z -> X (real) 0.380 0.200 Z -> Y (no such influence) 0.001 0.280 X -> Y (no such influence) 0.001 0.118 Y -> X (no such influence) 0.000 0.144 .. GENERATED FROM PYTHON SOURCE LINES 125-129 With the regions' own series the one real influence is the only cell that stands out. With the regions estimated from the sensors, the real influence is about half as strong, and three cells that are not real stand out: Z -> Y, the largest in that panel, which points *into* Y, which nothing drives, and X -> Y and Y -> X, between X and Y in both directions. .. GENERATED FROM PYTHON SOURCE LINES 131-141 Where it comes from: leakage ---------------------------- An inverse solution cannot separate close sources perfectly: the estimate of one region contains a part of the activity of its neighbours. ``crosstalk`` measures it. It makes every region of the head model active with independent white activity, projects it to the sensors, adds sensor noise, extracts the regions of interest exactly as ``roi_series`` does, and asks how much of each region's activity arrives in each extracted series. Entry ``[i, j]`` is the response of series ``i`` to the activity of region ``j``, relative to the response of series ``i`` to its own region (so the diagonal is 1 and a value above 1 means that a neighbour is heard louder than the region itself). It is estimated from random probe data, so it changes a little with the seed. .. GENERATED FROM PYTHON SOURCE LINES 141-147 .. code-block:: Python leak = crosstalk(head, list(spec.network.names), seed=SEED + 2) leak_table = pd.DataFrame(leak.matrix, index=leak.rois, columns=leak.rois) print("rows: series that receives; columns: region that leaks in") print(leak_table.round(2)) print(f"X leaks into the series of Y with {leak.matrix[2, 1]:.2f} times Y's own response") .. rst-class:: sphx-glr-script-out .. code-block:: none rows: series that receives; columns: region that leaks in transversetemporal-rh cuneus-lh pericalcarine-lh transversetemporal-rh 1.00 0.14 -0.19 cuneus-lh -0.15 1.00 0.77 pericalcarine-lh -0.05 2.94 1.00 X leaks into the series of Y with 2.94 times Y's own response .. GENERATED FROM PYTHON SOURCE LINES 148-152 The series that was estimated for Y contains the activity of X, in this simulation more strongly than Y's own activity. That explains the influences into Y: Z drives X, and X is in Y's series. The oracle series, which have no such mixing, are the control: with them the influences into Y are absent. .. GENERATED FROM PYTHON SOURCE LINES 154-167 Limitations ----------- * The influences into Y that appear in the sensor-based analysis are **leakage**, not connections: nothing drives Y in the simulation, and the same estimator finds none in the regions' own series. * This is one simulated recording of one pair of close regions on one head model, with one inverse method and EEG only. How much leakage there is for other pairs, other methods and MEG is not shown here. The benchmark report (``docs/benchmark_results.md``) measures leakage across many pairs under stated conditions. * dirconn does not correct for leakage. The crosstalk matrix is a way to see where it is likely to be a problem, and an estimate of its size, not a correction. * 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 167-170 .. 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 15 coefficients per equation are estimated from 5995 observations (ratio 0.0025; 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 507.1 over lags 1 to 15 (df 90, p = 2.12e-59); largest absolute residual autocorrelation 0.0812 (warning when p < 0.05 and it exceeds 0.1). .. GENERATED FROM PYTHON SOURCE LINES 171-174 * Not tested here: whether a different inverse method or a different head model changes the picture, and what happens with real recordings, where neither the regions nor their number are known. .. GENERATED FROM PYTHON SOURCE LINES 174-175 .. code-block:: Python plt.close("all") .. _sphx_glr_download_auto_tutorials_plot_07_sensors_to_regions.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_07_sensors_to_regions.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_07_sensors_to_regions.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_07_sensors_to_regions.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_