.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_tutorials/plot_02_model_order.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_02_model_order.py: ============================ How many past samples to use ============================ Granger causality and the spectral measures of the next tutorials all rest on a multivariate autoregressive (MVAR) model: every signal is predicted from the last ``order`` samples of all signals. The order is a choice, and this tutorial shows how the library helps to make it and what happens to the answer when it is chosen badly. It uses the same simulated chain as tutorial 1, so you can compare with the truth. .. GENERATED FROM PYTHON SOURCE LINES 15-17 Setup and data -------------- .. GENERATED FROM PYTHON SOURCE LINES 17-56 .. code-block:: Python import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import dirconn from dirconn import Edge, Network, dk_node from dirconn.simulation import NodeDynamics, simulate 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__}") A, B, C = "cuneus-rh", "precuneus-rh", "insula-rh" network = Network( nodes=[dk_node(A), dk_node(B), dk_node(C)], edges=[Edge(A, B, strength=0.4, delay_ms=10.0), Edge(B, C, strength=0.4, delay_ms=10.0)], name="chain", ) dynamics = { A: NodeDynamics(kind="oscillator", freq_hz=10.0), B: NodeDynamics(kind="oscillator", freq_hz=20.0), C: NodeDynamics(kind="oscillator", freq_hz=15.0), } SFREQ = 100.0 sim = simulate( network, sfreq=SFREQ, n_times=int((30.0 if QUICK else 120.0) * SFREQ), seed=SEED, dynamics=dynamics, snr_db=10.0, n_background=0, node_scale="unit", ) data = sim.roi_observations(snr_db=10.0, seed=SEED + 1) print(data) .. rst-class:: sphx-glr-script-out .. code-block:: none dirconn 0.2.0, numpy 2.5.5 TimeSeries(n_trials=1, n_channels=3, n_times=12000, sfreq=100, segmentation='continuous') .. GENERATED FROM PYTHON SOURCE LINES 57-62 Let the data choose ------------------- ``select_order`` fits MVAR models of order 1, 2, ... up to ``max_order`` and scores each with information criteria: they reward a model for predicting well and punish it for the number of coefficients it needs. Lower is better. AIC, BIC and HQC differ in how hard they punish. .. GENERATED FROM PYTHON SOURCE LINES 62-69 .. code-block:: Python MAX_ORDER = 12 selection = dirconn.select_order(data, MAX_ORDER, criterion="bic") print("chosen by BIC:", selection.order) for criterion in ("aic", "bic", "hqc"): chosen = dirconn.select_order(data, MAX_ORDER, criterion=criterion).order print(f"{criterion.upper()} chooses order {chosen}") .. rst-class:: sphx-glr-script-out .. code-block:: none chosen by BIC: 6 AIC chooses order 8 BIC chooses order 6 HQC chooses order 7 .. GENERATED FROM PYTHON SOURCE LINES 70-78 .. code-block:: Python fig, ax = plt.subplots(layout="constrained") for name, curve in (("AIC", selection.aic), ("BIC", selection.bic), ("HQC", selection.hqc)): ax.plot(selection.orders, curve, marker="o", label=name) ax.axvline(selection.order, color="k", linestyle=":", label=f"BIC choice: {selection.order}") ax.set_xlabel("model order (samples of the past)") ax.set_ylabel("information criterion (lower is better)") ax.legend() .. image-sg:: /auto_tutorials/images/sphx_glr_plot_02_model_order_001.png :alt: plot 02 model order :srcset: /auto_tutorials/images/sphx_glr_plot_02_model_order_001.png, /auto_tutorials/images/sphx_glr_plot_02_model_order_001_2_00x.png 2.00x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 79-82 The curves fall steeply over the first orders and then flatten out: after that, a longer past adds coefficients without predicting noticeably better. At this sampling rate of 100 Hz an order of 5 means that the model looks back 50 ms. .. GENERATED FROM PYTHON SOURCE LINES 84-89 What a bad choice does ---------------------- We now estimate the same Granger causality with different orders and compare the three influences that matter: the two real ones (first to second, second to third) and the one that does not exist (first to third). .. GENERATED FROM PYTHON SOURCE LINES 89-107 .. code-block:: Python orders = [1, 2, 3, selection.order, MAX_ORDER] rows = [] for order in orders: # check_order_stability=False: the result would otherwise refit at much longer orders to test # how stable the direction is, which we do not need to show here result = dirconn.gc(data, order=order, check_order_stability=False) values = result.values[:, :, 0, 0] rows.append( { "order": order, "A -> B (real)": values[0, 1], "B -> C (real)": values[1, 2], "A -> C (absent)": values[0, 2], } ) table = pd.DataFrame(rows).set_index("order") print(table.round(3)) .. rst-class:: sphx-glr-script-out .. code-block:: none /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 5.611e+04 over lags 1 to 11 (df 90, p = 0); largest absolute residual autocorrelation 0.655 (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) /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 6411 over lags 1 to 12 (df 90, p = 0); largest absolute residual autocorrelation 0.344 (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) /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 1285 over lags 1 to 13 (df 90, p = 1.38e-210); largest absolute residual autocorrelation 0.16 (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) A -> B (real) B -> C (real) A -> C (absent) order 1 0.137 0.073 0.001 2 0.380 0.118 0.014 3 0.456 0.229 0.005 6 0.383 0.253 0.007 12 0.348 0.220 0.008 .. GENERATED FROM PYTHON SOURCE LINES 108-115 .. code-block:: Python fig, ax = plt.subplots(layout="constrained") for column in table.columns: ax.plot(table.index, table[column], marker="o", label=column) ax.set_xlabel("model order") ax.set_ylabel("Granger causality (nats)") ax.legend() .. image-sg:: /auto_tutorials/images/sphx_glr_plot_02_model_order_002.png :alt: plot 02 model order :srcset: /auto_tutorials/images/sphx_glr_plot_02_model_order_002.png, /auto_tutorials/images/sphx_glr_plot_02_model_order_002_2_00x.png 2.00x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 116-122 In this recording an order of 1 gives less than half of what the orders from 3 upwards give for the two real influences, and those longer models give values of similar size to each other; the absent influence stays close to zero at every order. A model that is too short cannot see an influence that acts over several samples. The library warns when the criterion picks the largest candidate order, because then a longer one might have been better, and it records a check on the order, shown next. .. GENERATED FROM PYTHON SOURCE LINES 124-128 The order is part of the result ------------------------------- By default ``order="bic"``, and the result keeps the curves it chose from and a check of how stable the direction of every pair is when the order is made longer. .. GENERATED FROM PYTHON SOURCE LINES 128-134 .. code-block:: Python result = dirconn.gc(data, order="bic") print("order used:", result.provenance.model_order) for name in ("order_selection", "order_stability"): check = result.provenance.assumptions.get(name) print(f"{check.name}: {check.status}. {check.detail}") .. rst-class:: sphx-glr-script-out .. code-block:: none order used: 6 order_selection: pass. the bic criterion chose order 6 of 10 candidates. order_stability: pass. the direction of every pair at order 6 agrees with models of order 12, 24, 48. .. GENERATED FROM PYTHON SOURCE LINES 135-143 Limitations ----------- * Information criteria pick the order that predicts well; they do not know the true order, which for real data does not exist. Different criteria can choose different orders. * The comparison above uses one simulated recording of one network: it shows the kind of difference a short model can make, not how large it is in general. * 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 143-146 .. code-block:: Python for check in result.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 18 coefficients per equation are estimated from 11994 observations (ratio 0.0015; 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 135.8 over lags 1 to 16 (df 90, p = 0.00131); largest absolute residual autocorrelation 0.0373 (warning when p < 0.05 and it exceeds 0.1). order_selection pass the bic criterion chose order 6 of 10 candidates. order_stability pass the direction of every pair at order 6 agrees with models of order 12, 24, 48. .. GENERATED FROM PYTHON SOURCE LINES 147-150 * Not tested here: the effect of the order on frequency-resolved measures (tutorial 3), whether the model is stationary, and what happens when the order is chosen on one part of the data and used on another. .. GENERATED FROM PYTHON SOURCE LINES 150-151 .. code-block:: Python plt.close("all") .. _sphx_glr_download_auto_tutorials_plot_02_model_order.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_02_model_order.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_02_model_order.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_02_model_order.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_