.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_14_three_methods_same_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_14_three_methods_same_regions.py: ============================================================ Three methods on the same regions: what the data decide ============================================================ Tutorial 8 read sources and sinks from Granger causality, once with the regions' own time series and once with regions estimated from the EEG sensors. Is what it found specific to that method? This tutorial analyses the same simulation with three methods: Granger causality (time domain, one model of all regions), transfer entropy (time domain, model-free, one pair at a time; tutorial 12) and the adaptive DTF (frequency domain; tutorial 6). Each result is compared with the known truth in three ways: do the true influences score above the other pairs, what happens to pairs that are linked only through a third region, and is the delay of an influence found. It is a demonstration with one simulation, not an evaluation of the methods. It needs the MNE ``sample`` dataset (about 1.5 GB), which dirconn never downloads without being asked. The full version runs for about ten minutes, most of it for transfer entropy. .. GENERATED FROM PYTHON SOURCE LINES 18-21 .. code-block:: Python NEEDS_SAMPLE = True .. GENERATED FROM PYTHON SOURCE LINES 22-24 Setup ----- .. GENERATED FROM PYTHON SOURCE LINES 24-47 .. code-block:: Python import os import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd from dirconn.datasets import require_sample import dirconn 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 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()) # the neighbour searches of transfer entropy use every core; the values do not depend on it WORKERS = -1 .. 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 48-56 The simulation of tutorial 8 ---------------------------- The shipped scenario ``random_10``: ten regions and fifteen influences between them, with delays of 10 to 30 ms and oscillations between 8 and 30 Hz, projected to the EEG sensors of the MNE ``sample`` head model with ten background sources. Besides the true influences we mark the pairs that are linked only through a third region (A drives B, B drives C, but A does not drive C): a method that sees the whole network should leave them low, a method that looks at one pair at a time may not. .. GENERATED FROM PYTHON SOURCE LINES 56-81 .. code-block:: Python spec = load_scenario("random_10") names = list(spec.network.names) n = len(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]).astype(bool) off = ~np.eye(n, dtype=bool) indirect = ((truth.astype(int) @ truth.astype(int)) > 0) & ~truth & off other = off & ~truth & ~indirect true_delay = np.zeros((n, n), dtype=int) for edge in spec.network.edges: true_delay[names.index(edge.source), names.index(edge.target)] = round( edge.delay_ms * spec.sfreq / 1000.0 ) print(f"{truth.sum()} true influences, {indirect.sum()} indirect pairs, {other.sum()} other pairs") .. rst-class:: sphx-glr-script-out .. code-block:: none 15 true influences, 10 indirect pairs, 65 other pairs .. GENERATED FROM PYTHON SOURCE LINES 82-83 The regions' own series and the regions estimated from the sensors, as in tutorials 7 and 8: .. GENERATED FROM PYTHON SOURCE LINES 83-88 .. code-block:: Python series = { "own series": sim.roi_observations(snr_db=spec.snr_db, seed=SEED + 1), "from sensors": roi_series(sim.data, head, names), } .. GENERATED FROM PYTHON SOURCE LINES 89-98 Three methods ------------- Granger causality and the adaptive DTF are both computed from a vector autoregressive model of all ten regions, the first in the time domain, the second in the frequency domain; transfer entropy is computed for one pair at a time (its default) and scans the delay of the influence. The network of this simulation does not change over time, so the adaptive DTF is averaged over the whole recording, and over the band of the oscillators. Its library warning matters: the recursion has a short memory (tutorial 6), so a single time point would be unreliable; the average over the recording is what we use here. .. GENERATED FROM PYTHON SOURCE LINES 98-122 .. code-block:: Python ORDER = 4 if QUICK else 5 BAND = (8.0, 30.0) MAX_DELAY = 5 # samples; the simulated delays are 1 to 3 def fit_all(data): """Fit the three methods to one set of region series.""" gc = dirconn.gc(data, order=ORDER, check_order_stability=False) te = dirconn.te(data, mode="pairwise", max_delay=MAX_DELAY, workers=WORKERS) with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") adtf = dirconn.adtf(data, order=ORDER, fmax=40.0, n_freqs=41, time_step=0.5) for item in caught: print(" ADTF warning:", str(item.message)) span = (float(adtf.times[0]), float(adtf.times[-1])) return {"GC": gc, "TE": te, "ADTF": adtf.reduce_freq(BAND).reduce_time(span)} results = {} for label, data in series.items(): print(label) results[label] = fit_all(data) methods = list(results["own series"]) .. rst-class:: sphx-glr-script-out .. code-block:: none own series /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) ADTF warning: 50 coefficients per equation are estimated from 5 observations (ratio 10; the rule of thumb is at most 0.1). Estimates will be unreliable; use more data, a lower order, fewer channels or a ridge penalty. from sensors /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) ADTF warning: 50 coefficients per equation are estimated from 6 observations (ratio 8.33; the rule of thumb is at most 0.1). Estimates will be unreliable; use more data, a lower order, fewer channels or a ridge penalty. .. GENERATED FROM PYTHON SOURCE LINES 123-130 The matrices ------------ One figure per method, the regions' own series on the left and the regions from the sensors on the right, on one colour scale per method. Granger causality is never negative and is drawn in red from zero; the adaptive DTF is a share between 0 and 1, so its scale is fixed to that range. Raw transfer entropy is biased and can be slightly negative (tutorial 12), so its scale is centred on zero: red above, blue below. The fifteen true influences, by source: .. GENERATED FROM PYTHON SOURCE LINES 130-142 .. code-block:: Python for i, source in enumerate(names): if truth[i].any(): print(f" {source} -> {', '.join(names[j] for j in np.flatnonzero(truth[i]))}") for method in methods: pair = [res[method] for res in results.values()] # the averaged adaptive DTF keeps one frequency and one time point; the colour bar names them where = {"freq": pair[0].freqs[0]} if pair[0].is_frequency_resolved else {} where |= {"time": pair[0].times[0]} if pair[0].is_time_resolved else {} # a larger figure than the default: room for the ten region names connectivity_grids(pair, names=list(results), figsize=(12.0, 6.0), **where) .. rst-class:: sphx-glr-horizontal * .. image-sg:: /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_001.png :alt: own series, from sensors :srcset: /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_001.png, /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_001_2_00x.png 2.00x :class: sphx-glr-multi-img * .. image-sg:: /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_002.png :alt: own series, from sensors :srcset: /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_002.png, /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_002_2_00x.png 2.00x :class: sphx-glr-multi-img * .. image-sg:: /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_003.png :alt: own series, from sensors :srcset: /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_003.png, /auto_tutorials/images/sphx_glr_plot_14_three_methods_same_regions_003_2_00x.png 2.00x :class: sphx-glr-multi-img .. rst-class:: sphx-glr-script-out .. code-block:: none caudalmiddlefrontal-lh -> transversetemporal-rh paracentral-lh -> transversetemporal-rh, rostralanteriorcingulate-rh, parstriangularis-lh, bankssts-rh transversetemporal-rh -> rostralanteriorcingulate-rh, parstriangularis-lh, bankssts-rh superiorfrontal-rh -> transversetemporal-rh, temporalpole-rh, bankssts-rh rostralanteriorcingulate-rh -> caudalmiddlefrontal-lh, cuneus-lh parstriangularis-lh -> cuneus-lh temporalpole-rh -> bankssts-rh .. GENERATED FROM PYTHON SOURCE LINES 143-145 How many true influences are among the largest values? For each result, the fifteen pairs with the largest values (as many as there are true influences), counted by kind: .. GENERATED FROM PYTHON SOURCE LINES 145-155 .. code-block:: Python n_true = int(truth.sum()) for label, res in results.items(): for method, conn in res.items(): matrix = np.where(off, conn.values[:, :, 0, 0], -np.inf) top = np.unravel_index(np.argsort(matrix, axis=None)[::-1][:n_true], matrix.shape) print( f"{label:13s} {method:5s} {truth[top].sum():2d} true, {indirect[top].sum():2d} indirect, " f"{other[top].sum():2d} other" ) .. rst-class:: sphx-glr-script-out .. code-block:: none own series GC 15 true, 0 indirect, 0 other own series TE 9 true, 3 indirect, 3 other own series ADTF 13 true, 2 indirect, 0 other from sensors GC 5 true, 4 indirect, 6 other from sensors TE 5 true, 3 indirect, 7 other from sensors ADTF 5 true, 2 indirect, 8 other .. GENERATED FROM PYTHON SOURCE LINES 156-165 With the regions' own series, the true influences stand out for all three methods (for the adaptive DTF, whose shares are small on its scale from 0 to 1, more faintly): among the fifteen largest values, Granger causality has all fifteen true influences, the adaptive DTF twelve or thirteen and transfer entropy nine (quick and full version). Granger causality, which conditions every pair on the other regions, keeps the other cells close to zero. The other two light up some of them: the adaptive DTF a few of the pairs linked through a third region, transfer entropy a few pairs of both kinds. From the sensors only four or five true influences remain among the fifteen largest values of each method, and the adaptive DTF shows a whole bright row, temporalpole-rh: a region that looks like a strong source although it sends only one influence. .. GENERATED FROM PYTHON SOURCE LINES 167-173 How well do the true influences score? -------------------------------------- One number per result: the chance that a true influence scores above a pair without one (the area under the ROC curve; 1 means every true influence is above every other pair, 0.5 is guessing). It uses only the ranks of the values, so it can be compared across methods whose values have different units. The mean percentile ranks show where the three kinds of pairs fall. .. GENERATED FROM PYTHON SOURCE LINES 173-207 .. code-block:: Python def auc(values, labels): """Chance that a value with label True is above one with label False (ties count half).""" pos, neg = values[labels], values[~labels] above = (pos[:, None] > neg[None, :]).sum() + 0.5 * (pos[:, None] == neg[None, :]).sum() return float(above / (pos.size * neg.size)) def percentile_ranks(matrix): ranks = np.full(matrix.shape, np.nan) order = np.argsort(np.argsort(matrix[off])) ranks[off] = 100.0 * (order + 0.5) / off.sum() return ranks rows = [] for label, res in results.items(): for method, conn in res.items(): matrix = conn.values[:, :, 0, 0] ranks = percentile_ranks(matrix) rows.append( { "series": label, "method": method, "AUC": auc(matrix[off], truth[off]), "rank: true": np.nanmean(ranks[truth]), "rank: indirect": np.nanmean(ranks[indirect]), "rank: other": np.nanmean(ranks[other]), } ) scores = pd.DataFrame(rows).set_index(["series", "method"]) print(scores.round(2).to_string()) .. rst-class:: sphx-glr-script-out .. code-block:: none AUC rank: true rank: indirect rank: other series method own series GC 1.00 91.67 59.56 38.91 TE 0.94 86.33 56.78 40.57 ADTF 0.98 89.67 74.56 37.07 from sensors GC 0.71 67.30 65.11 43.68 TE 0.74 69.81 65.44 43.05 ADTF 0.69 65.74 53.00 45.91 .. GENERATED FROM PYTHON SOURCE LINES 208-215 With the regions' own series all three methods put the true influences near the top. From the sensors, all three fall, and they fall much more than they differ from each other: here, the data the regions come from decide more than the choice between time and frequency domain. The one clear difference between the methods is in the indirect pairs, which the adaptive DTF ranks well above the other pairs: the DTF counts the flow through other regions by definition. With one simulation and fifteen true influences, differences of a few hundredths between the methods mean nothing. .. GENERATED FROM PYTHON SOURCE LINES 217-222 What the time domain adds: the delay ------------------------------------ Transfer entropy keeps, for every pair, the delay (in samples) that gave the largest value; the chosen delays are in its provenance. On the true influences we compare them with the simulated delays. Guessing one of the ``MAX_DELAY`` delays would be right for one influence in five. .. GENERATED FROM PYTHON SOURCE LINES 222-231 .. code-block:: Python for label, res in results.items(): chosen = np.array(res["TE"].provenance.details["delay"], dtype=float) exact = int((chosen[truth] == true_delay[truth]).sum()) close = int((np.abs(chosen[truth] - true_delay[truth]) <= 1).sum()) print( f"{label:13s} exact delay on {exact} of {truth.sum()} true influences, within one sample " f"on {close}; guessing: about {truth.sum() / MAX_DELAY:.0f}" ) .. rst-class:: sphx-glr-script-out .. code-block:: none own series exact delay on 11 of 15 true influences, within one sample on 15; guessing: about 3 from sensors exact delay on 4 of 15 true influences, within one sample on 11; guessing: about 3 .. GENERATED FROM PYTHON SOURCE LINES 232-236 With the regions' own series the exact delay is found for most influences; from the sensors, where every region mixes in its neighbours, it is found about as often as by guessing, although the chosen delay is often off by only one sample. The adaptive DTF, averaged over a band, gives no delay at all. .. GENERATED FROM PYTHON SOURCE LINES 238-251 Limitations ----------- * Every value here is about **prediction**: the past of one region helps to predict another. None of the three methods shows that a region drives another, and the regions estimated from sensors were not corrected for leakage (tutorial 7). * The comparison is one simulation of one network, on one head model with one inverse method. It shows that the step from the regions' own series to regions estimated from sensors can matter more than the method; it does not show how much in general, nor which method is better. * Transfer entropy was computed pair by pair and its values are raw and untested; the surrogate test of tutorial 12 is needed before reading any single value. The adaptive DTF was averaged over a network that does not change; its time resolution, the reason to use it, is not used. * 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 251-256 .. code-block:: Python for method, conn in results["from sensors"].items(): print(method) for check in conn.provenance.assumptions.checks: print(f" {check.name:24s} {check.status:12s} {check.detail}") .. rst-class:: sphx-glr-script-out .. code-block:: none GC 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). TE stationarity not_checked linearity not_checked sampling_adequacy not_checked instantaneous_coupling not_checked causal_sufficiency not_checked filtering not_checked ADTF stationarity pass 0 of 100 time points (0%) have a companion spectral radius of 1 or more. linearity not_checked sampling_adequacy warn 50 coefficients per equation are estimated from 6 observations (ratio 8.33; the rule of thumb is at most 0.1). instantaneous_coupling not_checked causal_sufficiency not_checked filtering not_checked filter_health pass no update was skipped and no state was reset. order_source not_checked order 5 was fixed by the caller, not selected. .. GENERATED FROM PYTHON SOURCE LINES 257-259 * Not tested here: other networks, other head models and inverse methods, more seeds, and anything about real recordings. .. GENERATED FROM PYTHON SOURCE LINES 259-260 .. code-block:: Python plt.close("all") .. rst-class:: sphx-glr-timing **Total running time of the script:** (3 minutes 30.746 seconds) .. _sphx_glr_download_auto_tutorials_plot_14_three_methods_same_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_14_three_methods_same_regions.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_14_three_methods_same_regions.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_14_three_methods_same_regions.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_