.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_12_transfer_entropy.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_12_transfer_entropy.py: ================================================ Non-linear coupling: transfer entropy next to GC ================================================ Granger causality asks whether the past of one signal improves a *linear* prediction of another. A coupling that is not linear can pass unnoticed. **Transfer entropy** (:class:`~dirconn.TE`) asks the same question in terms of information: how much does the past of the source tell about the present of the target beyond what the target's own past tells? It is estimated without a model, with nearest neighbours (the KSG estimator), so it also sees non-linear dependence. For Gaussian, linear data it is half the Granger causality. This tutorial shows a coupling that Granger causality misses and transfer entropy finds, the linear case where the two agree, and what the raw transfer entropy needs before it can be read: a significance test. .. GENERATED FROM PYTHON SOURCE LINES 19-25 Setup ----- :func:`dirconn.coupled_nonlinear` makes three signals: X drives Y through a function ``g`` at a lag of two samples, Z is independent. With ``coupling="quadratic"``, ``g`` is a centred square of X. A square has zero linear correlation with its input, so the influence of X on Y is invisible to any linear measure. .. GENERATED FROM PYTHON SOURCE LINES 25-42 .. code-block:: Python import os import matplotlib.pyplot as plt import numpy as np import dirconn from dirconn import GC, TE 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__}") SFREQ = 100.0 N_TIMES = 2000 if QUICK else 5000 quadratic, _ = dirconn.coupled_nonlinear(N_TIMES, sfreq=SFREQ, seed=SEED, coupling="quadratic") linear, _ = dirconn.coupled_nonlinear(N_TIMES, sfreq=SFREQ, seed=SEED, coupling="linear") .. rst-class:: sphx-glr-script-out .. code-block:: none dirconn 0.2.0, numpy 2.5.5 .. GENERATED FROM PYTHON SOURCE LINES 43-51 Granger causality and transfer entropy side by side --------------------------------------------------- The only true connection is X -> Y. Both measures are in nats, but dirconn draws different measures with separate colour bars, so each panel has its own scale: compare the numbers in the cells, not the colours. The Granger panel stops below 0.001, so its darkest cell is still next to nothing. Transfer entropy is drawn on a scale centred on zero, because the nearest-neighbour estimate can be negative. On the quadratic coupling Granger causality from X to Y is about zero; transfer entropy shows X -> Y strongly, and none of the five uncoupled pairs comes close: .. GENERATED FROM PYTHON SOURCE LINES 51-59 .. code-block:: Python gc_quadratic = GC(order="bic", check_order_stability=False).fit(quadratic) te_quadratic = TE(mode="pairwise").fit(quadratic) fig, axes = plt.subplots(1, 2, figsize=(10.0, 4.2), layout="constrained") gc_quadratic.plot(ax=axes[0]) te_quadratic.plot(ax=axes[1]) print(f"quadratic coupling, X -> Y: GC {gc_quadratic.values[0, 1, 0, 0]:.4f}") print(f"quadratic coupling, X -> Y: TE {te_quadratic.values[0, 1, 0, 0]:.4f}") .. image-sg:: /auto_tutorials/images/sphx_glr_plot_12_transfer_entropy_001.png :alt: plot 12 transfer entropy :srcset: /auto_tutorials/images/sphx_glr_plot_12_transfer_entropy_001.png, /auto_tutorials/images/sphx_glr_plot_12_transfer_entropy_001_2_00x.png 2.00x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none quadratic coupling, X -> Y: GC 0.0004 quadratic coupling, X -> Y: TE 0.1030 .. GENERATED FROM PYTHON SOURCE LINES 60-62 With a linear coupling of the same strength the two agree, transfer entropy being about half of Granger causality, as it is for Gaussian data: .. GENERATED FROM PYTHON SOURCE LINES 62-68 .. code-block:: Python gc_linear = GC(order="bic", check_order_stability=False).fit(linear).values[0, 1, 0, 0] te_linear = TE(mode="pairwise").fit(linear).values[0, 1, 0, 0] print( f"linear coupling, X -> Y: GC {gc_linear:.4f}, GC / 2 {gc_linear / 2:.4f}, TE {te_linear:.4f}" ) .. rst-class:: sphx-glr-script-out .. code-block:: none linear coupling, X -> Y: GC 0.1868, GC / 2 0.0934, TE 0.0990 .. GENERATED FROM PYTHON SOURCE LINES 69-73 The delay --------- The estimator scans the interaction delay (``max_delay``, here 1 to 5 samples) and keeps the largest value; every delay is evaluated on the same rows. The scan is in the provenance: .. GENERATED FROM PYTHON SOURCE LINES 73-81 .. code-block:: Python scan = np.array(te_quadratic.provenance.details["scan"], dtype=float)[0, 1] fig, ax = plt.subplots(layout="constrained") ax.bar(te_quadratic.provenance.details["delays"], scan) ax.set_xlabel("delay (samples)") ax.set_ylabel("TE X → Y (nats)") ax.set_title("transfer entropy at every delay") print("delay found:", te_quadratic.provenance.details["delay"][0][1], "samples") .. image-sg:: /auto_tutorials/images/sphx_glr_plot_12_transfer_entropy_002.png :alt: transfer entropy at every delay :srcset: /auto_tutorials/images/sphx_glr_plot_12_transfer_entropy_002.png, /auto_tutorials/images/sphx_glr_plot_12_transfer_entropy_002_2_00x.png 2.00x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none delay found: 2 samples .. GENERATED FROM PYTHON SOURCE LINES 82-90 The raw value is biased ----------------------- Look at the pairs without coupling: their transfer entropy is small but not zero. The nearest-neighbour estimate has a bias that depends on the number of samples, the neighbours and the dimensions, and keeping the best of five delays adds to it. A raw value therefore needs a test. Here a phase-randomised surrogate test: it keeps every signal's spectrum and destroys the relations between them (tutorial 4). Phase randomisation also destroys the *non-linear* structure within each signal, which is part of what this null hypothesis tests: .. GENERATED FROM PYTHON SOURCE LINES 90-106 .. code-block:: Python off_diagonal = te_quadratic.values[:, :, 0, 0][~np.eye(3, dtype=bool)] print(f"TE of the five uncoupled pairs: {np.round(np.sort(off_diagonal)[:-1], 4)}") test = dirconn.significance_test( TE(mode="pairwise", max_delay=3), quadratic, test="surrogate", surrogate="phase_randomize", n_surrogates=19 if QUICK else 39, seed=SEED + 1, ) print("p-values (rows: source, columns: target):") print(np.round(test.pvalues[:, :, 0, 0], 3)) print( f"smallest possible p-value with {test.n_surrogates} surrogates: {1 / (test.n_surrogates + 1):.3f}" ) .. rst-class:: sphx-glr-script-out .. code-block:: none TE of the five uncoupled pairs: [0.0051 0.0094 0.0111 0.0116 0.014 ] /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/dirconn/stats/surrogate_test.py:156: DirconnWarning: n_surrogates=39 is below 119: with 6 defined cells and alpha=0.05 the smallest p-value 1/(n_surrogates + 1) cannot reach alpha/6, so a Bonferroni-type correction can never reject. Increase n_surrogates or reduce the number of tested cells with reduce=. return surrogate_tests( p-values (rows: source, columns: target): [[ nan 0.025 0.825] [0.175 nan 0.5 ] [0.25 0.875 nan]] smallest possible p-value with 39 surrogates: 0.025 .. GENERATED FROM PYTHON SOURCE LINES 107-111 X -> Y reaches the smallest p-value that this number of surrogates allows, the uncoupled pairs do not. The warning printed by the test says more: with so few surrogates no correction over the six pairs can reach 0.05. A real analysis needs at least 119 surrogates here, which takes minutes with transfer entropy, so this tutorial stops at an uncorrected reading. .. GENERATED FROM PYTHON SOURCE LINES 113-120 Three modes ----------- This tutorial uses the pairwise mode (``mode="pairwise"``): one pair at a time, the best of the scanned delays. With ``mode="conditional"`` the past of every other signal joins the condition, which removes indirect and shared influence but adds a dimension per signal, and the nearest-neighbour estimate gets worse quickly as the dimension grows. With three signals the difference is small: .. GENERATED FROM PYTHON SOURCE LINES 120-125 .. code-block:: Python te_conditional = TE(mode="conditional").fit(quadratic) print( f"X -> Y pairwise {te_quadratic.values[0, 1, 0, 0]:.4f}, conditional {te_conditional.values[0, 1, 0, 0]:.4f}" ) .. rst-class:: sphx-glr-script-out .. code-block:: none X -> Y pairwise 0.1030, conditional 0.1019 .. GENERATED FROM PYTHON SOURCE LINES 126-131 The default of :class:`~dirconn.TE` is the third mode, ``mode="multivariate"``: it selects the past variables of every signal that inform the target, tests each step by permutation and returns zero for a source that is not selected, so it needs no separate surrogate test. It is much slower; tutorial 15 shows it on a chain and on a common driver, where the pairwise mode reports links that do not exist. .. GENERATED FROM PYTHON SOURCE LINES 133-148 Limitations ----------- * A quadratic coupling that Granger causality did not see was found by transfer entropy, and on a linear coupling transfer entropy was about half of Granger causality. This is one simulated system and one seed (a demonstration, not an evaluation); the validation report (``docs/method_validation.md``) runs it on the reference scenarios. * The raw estimate is biased and its size depends on the settings, so values are compared with a surrogate test, not across data sets or embeddings. * The result depends on the embedding (``target_history``, ``source_history``) and on the scanned delays. The target history defaults to the BIC order of a VAR model; one that is too short leaves the target's own memory in the source's past and can reverse the direction, as the validation report shows for a history of one sample on oscillating signals. * It is predictive information transfer, not causation, and it assumes stationarity and that no unrecorded signal drives the pair. Each result lists its assumptions; ``not_checked`` means the library did not test one, not that it holds: .. GENERATED FROM PYTHON SOURCE LINES 148-151 .. code-block:: Python for check in te_quadratic.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 not_checked instantaneous_coupling not_checked causal_sufficiency not_checked filtering not_checked .. GENERATED FROM PYTHON SOURCE LINES 152-154 * Not shown here: effective transfer entropy (the bias subtracted, deferred), longer embeddings, more signals, and mixing between the signals (tutorial 9). .. GENERATED FROM PYTHON SOURCE LINES 154-155 .. code-block:: Python plt.close("all") .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 49.610 seconds) .. _sphx_glr_download_auto_tutorials_plot_12_transfer_entropy.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_12_transfer_entropy.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_12_transfer_entropy.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_12_transfer_entropy.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_