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 (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.

Setup#

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.

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")
dirconn 0.2.0, numpy 2.5.5

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:

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}")
plot 12 transfer entropy
quadratic coupling, X -> Y: GC 0.0004
quadratic coupling, X -> Y: TE 0.1030

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:

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}"
)
linear coupling, X -> Y: GC 0.1868, GC / 2 0.0934, TE 0.0990

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:

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")
transfer entropy at every delay
delay found: 2 samples

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:

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}"
)
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

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.

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:

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}"
)
X -> Y pairwise 0.1030, conditional 0.1019

The default of 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.

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:

for check in te_quadratic.provenance.assumptions.checks:
    print(f"{check.name:24s} {check.status:12s} {check.detail}")
stationarity             not_checked
linearity                not_checked
sampling_adequacy        not_checked
instantaneous_coupling   not_checked
causal_sufficiency       not_checked
filtering                not_checked
  • Not shown here: effective transfer entropy (the bias subtracted, deferred), longer embeddings, more signals, and mixing between the signals (tutorial 9).

plt.close("all")

Total running time of the script: (0 minutes 49.610 seconds)

Gallery generated by Sphinx-Gallery