.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_05_misleading_scenarios.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_05_misleading_scenarios.py: ============================================== When the picture misleads: indirect and hidden ============================================== A directed connectivity estimate can show an influence that is not there. This tutorial builds three situations in which that happens, each with a known truth, and for each one runs a control that shows *why*: the same data analysed in a way that removes the false influence. It also shows the one situation where no analysis of the recorded data can remove it, and why a significant p-value does not help. The tutorial is about a way of reading results, so all values come from short simulations of three or four regions. They show that these effects exist, not how large they are in general. .. GENERATED FROM PYTHON SOURCE LINES 17-29 Setup ----- Three shipped scenarios are used: ``chain`` (A drives B, B drives C), ``common_driver`` (A drives B and C) and ``hidden_common_input`` (a region H, which will not be recorded, drives A and B; A also drives C). We compare two Granger causality estimators: * the **conditional** one (the default, ``conditional=True``) asks whether the past of the source helps to predict the target *beyond what the past of all other recorded regions does*; * the **pairwise** one (``conditional=False``) looks at two regions at a time and ignores the rest. Each figure draws the two estimates side by side on one colour scale, so their values can be compared directly. The rows and columns are the regions A, B, C (and D) in that order. .. GENERATED FROM PYTHON SOURCE LINES 29-83 .. code-block:: Python import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import dirconn from dirconn import GC 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 FIGSIZE = (12.0, 6.0) # inches print(f"dirconn {dirconn.__version__}, numpy {np.__version__}") def run_scenario(name): """Simulate a shipped scenario; return the simulation and the region data of every node.""" spec = load_scenario(name) sim = dirconn.simulate( spec.network, sfreq=spec.sfreq, n_times=int((30.0 if QUICK else spec.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 estimate(data, *, conditional): return GC(order="bic", conditional=conditional, check_order_stability=False).fit(data) def show(estimates): """One panel per estimate, named by its label, on one shared colour scale.""" # larger than the default figure: the region names are long, and the cells hold numbers connectivity_grids(list(estimates.values()), names=list(estimates), figsize=FIGSIZE) 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 .. rst-class:: sphx-glr-script-out .. code-block:: none dirconn 0.2.0, numpy 2.5.5 .. GENERATED FROM PYTHON SOURCE LINES 84-89 An indirect path ---------------- In the chain A drives B and B drives C; A does not drive C. The pairwise estimator sees only A and C, and A's signal does help to predict C, because it passes through B. The true connections are A to B and B to C. .. GENERATED FROM PYTHON SOURCE LINES 89-102 .. code-block:: Python spec, sim, data = run_scenario("chain") A, B, C = spec.network.names estimates = { "conditional (default)": estimate(data, conditional=True), "pairwise": estimate(data, conditional=False), } 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_05_misleading_scenarios_001.png :alt: conditional (default), pairwise :srcset: /auto_tutorials/images/sphx_glr_plot_05_misleading_scenarios_001.png, /auto_tutorials/images/sphx_glr_plot_05_misleading_scenarios_001_2_00x.png 2.00x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none conditional (default) pairwise A -> C (no such influence) 0.004 0.136 A -> B (real) 0.377 0.392 .. GENERATED FROM PYTHON SOURCE LINES 103-108 Both estimators show the two true connections strongly. The conditional one shows nothing else: its other cells stay below 0.01. The pairwise estimator reports a clear influence from A to C as well, about a third of the value of A to B. The conditional one, which has the past of B at its disposal, does not. That is the control: the same data, with the missing piece supplied, and the false influence is gone, so it came from the path through B. .. GENERATED FROM PYTHON SOURCE LINES 110-115 A shared driver --------------- In ``common_driver`` region A drives B and C, which are not connected to each other. B and C get the same signal from A, 10 ms and 20 ms late, so the past of B helps to predict C. A fourth region, D, is connected to nothing. The true connections are A to B and A to C. .. GENERATED FROM PYTHON SOURCE LINES 115-128 .. code-block:: Python spec, sim, data = run_scenario("common_driver") A, B, C, D = spec.network.names estimates = { "conditional (default)": estimate(data, conditional=True), "pairwise": estimate(data, conditional=False), } 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_05_misleading_scenarios_002.png :alt: conditional (default), pairwise :srcset: /auto_tutorials/images/sphx_glr_plot_05_misleading_scenarios_002.png, /auto_tutorials/images/sphx_glr_plot_05_misleading_scenarios_002_2_00x.png 2.00x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none conditional (default) pairwise B -> C (no such influence) 0.002 0.165 A -> C (real) 0.215 0.378 .. GENERATED FROM PYTHON SOURCE LINES 129-133 Both estimators show the two true connections strongly, and the cells of D stay near 0 in both. Again the pairwise estimator reports an influence between the two regions that share a driver, from B to C and, weaker, from C to B, and the conditional one, which has the driver in the model, does not: its other cells stay below 0.01. .. GENERATED FROM PYTHON SOURCE LINES 135-140 A driver you did not record --------------------------- Now the driver is *missing*. In ``hidden_common_input`` an unrecorded region H drives A and B, and A drives C. We analyse only A, B and C, as one would with a real recording in which H was not measured. Among these three the one true connection is A to C. .. GENERATED FROM PYTHON SOURCE LINES 140-156 .. code-block:: Python spec, sim, all_regions = run_scenario("hidden_common_input") A, B, C = spec.analysed (H,) = spec.hidden seen = all_regions.pick(list(spec.analysed)) print("analysed:", seen.names) estimates = { "conditional (default)": estimate(seen, conditional=True), "pairwise": estimate(seen, conditional=False), } show(estimates) print( values_table(estimates, {"A -> B (no such influence)": (A, B), "A -> C (real)": (A, C)}).round( 3 ) ) .. image-sg:: /auto_tutorials/images/sphx_glr_plot_05_misleading_scenarios_003.png :alt: conditional (default), pairwise :srcset: /auto_tutorials/images/sphx_glr_plot_05_misleading_scenarios_003.png, /auto_tutorials/images/sphx_glr_plot_05_misleading_scenarios_003_2_00x.png 2.00x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none analysed: ('transversetemporal-rh', 'cuneus-rh', 'transversetemporal-lh') conditional (default) pairwise A -> B (no such influence) 0.079 0.089 A -> C (real) 0.351 0.519 .. GENERATED FROM PYTHON SOURCE LINES 157-166 Both estimators show the true connection, A to C, as the largest value. Both also link A and B, which have no connection and share a hidden driver, in both directions: A to B and B to A. Both are smaller than A to C but clearly above zero. The pairwise estimator also shows B to C, which is no connection either. Conditioning cannot help, because H is not among the recorded regions. The control that shows where it comes from needs the one thing a real recording does not have: the hidden region. Here we have it, because we simulated it. With H in the data, the conditional estimator removes the influence between A and B, in both directions: .. GENERATED FROM PYTHON SOURCE LINES 166-178 .. code-block:: Python with_hidden = {"conditional, H recorded": estimate(all_regions, conditional=True)} print( values_table( with_hidden, { "A -> B (no such influence)": (A, B), "B -> A (no such influence)": (B, A), "H -> A (real)": (H, A), }, ).round(3) ) .. rst-class:: sphx-glr-script-out .. code-block:: none conditional, H recorded A -> B (no such influence) 0.001 B -> A (no such influence) 0.002 H -> A (real) 0.324 .. GENERATED FROM PYTHON SOURCE LINES 179-183 **Significance does not help.** Tutorial 4 showed a test that asks whether a value is more than noise. Applied to the recorded data, it marks the false influence like the real ones, because the false influence is not noise: there *is* a relation between A and B, it just does not run from one to the other. .. GENERATED FROM PYTHON SOURCE LINES 183-196 .. code-block:: Python surrogate = dirconn.significance_test( GC(order=5, check_order_stability=False), seen, test="surrogate", surrogate="phase_randomize", n_surrogates=199, seed=SEED + 2, ) significant = surrogate.significant()[:, :, 0, 0] print( "A -> B significant:", bool(significant[0, 1]), " A -> C significant:", bool(significant[0, 2]) ) .. rst-class:: sphx-glr-script-out .. code-block:: none A -> B significant: True A -> C significant: True .. GENERATED FROM PYTHON SOURCE LINES 197-200 The library cannot tell either. Every result carries a check named ``causal_sufficiency``, the assumption that no unrecorded region drives two of the recorded ones, and the library marks it as not checked. .. GENERATED FROM PYTHON SOURCE LINES 200-203 .. code-block:: Python check = estimates["conditional (default)"].provenance.assumptions.get("causal_sufficiency") print(f"{check.name}: {check.status}") .. rst-class:: sphx-glr-script-out .. code-block:: none causal_sufficiency: not_checked .. GENERATED FROM PYTHON SOURCE LINES 204-218 Limitations ----------- * Each false influence above was removed by a control that supplied what the estimate lacked: the middle region of the chain, the shared driver, the hidden region. That is the evidence that these influences come from a missing piece and not from noise. In a real recording the missing piece may be one you do not know about, and then no control of this kind exists. * What **conditioning** does and does not do: it handles third regions that are recorded; it cannot handle one that is not. Whether conditioning is the better choice in other settings (many regions, little data) is not shown here; with many regions the conditional model has more coefficients to estimate from the same data. * Every estimate is **predictive**. A value from A to C says that the past of A helps to predict C given what was included; it does not say that A acts on C. * 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 218-221 .. code-block:: Python for check in estimates["conditional (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 pass 21 coefficients per equation are estimated from 11993 observations (ratio 0.00175; 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 162.8 over lags 1 to 17 (df 90, p = 4.13e-06); largest absolute residual autocorrelation 0.0339 (warning when p < 0.05 and it exceeds 0.1). order_selection pass the bic criterion chose order 7 of 10 candidates. .. GENERATED FROM PYTHON SOURCE LINES 222-225 * Not shown here: other ways to be misled, such as leakage between neighbouring regions when region signals are estimated from the sensors (tutorial 7), influences that switch on and off (tutorial 6), or coupling at zero delay. .. GENERATED FROM PYTHON SOURCE LINES 225-226 .. code-block:: Python plt.close("all") .. _sphx_glr_download_auto_tutorials_plot_05_misleading_scenarios.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_05_misleading_scenarios.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_05_misleading_scenarios.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_05_misleading_scenarios.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_