.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/04_timeseries/plot_04_chaotic_reconstruction.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 or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_04_timeseries_plot_04_chaotic_reconstruction.py: State-space reconstruction and prediction of a chaotic time series ================================================================== A deterministic system is observed through one scalar measurement :math:`y_k`. By Takens' theorem, the delay vectors :math:`\mathbf{y}_k=[y_k, y_{k-\tau},\dots,y_{k-\tau(d_e-1)}]^T` reconstruct the state space if the embedding dimension :math:`d_e` is large enough. Abonyi, Feil, Németh, Árva, and Babuška identify the map :math:`\mathbf{y}_{k+1}=\mathbf{f}(\mathbf{y}_k)` in the reconstructed space as an operating-regime model (Gaussian regimes with local linear models) by a modified Gath–Geva clustering of the pairs :math:`(\mathbf{y}_k, \mathbf{y}_{k+1})`. One clustering provides three results: the embedding dimension (the one-step prediction error stops improving when :math:`d_e` is large enough), the *local* dimension of the attractor (the clusters become flat, with a collapsing smallest eigenvalue, once :math:`d_e` exceeds the dimension of the manifold on which the trajectory lies), and a model that predicts the series. The example uses the Rössler system of the paper, observed through :math:`x_1`; the Lorenz and Mackey–Glass series are generated by the same module and compared at the end. .. GENERATED FROM PYTHON SOURCE LINES 26-47 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np from fuzzyclust.plotting import PALETTE from fuzzyclust.timeseries import ( ChaoticPredictor, correlation_dimension, delay_embedding, embedding_scan, false_nearest_neighbors, fnn_model_order, make_lorenz, make_mackey_glass, make_rossler, plot_embedding_scan, plot_phase_space, select_delay, select_embedding_dimension, ) from fuzzyclust.viz import FuzzySammon, pca_projection, plot_projection .. GENERATED FROM PYTHON SOURCE LINES 48-53 The observed series and the lag of the embedding ------------------------------------------------ The lag :math:`\tau` is chosen as the first minimum of the average mutual information between :math:`y_k` and :math:`y_{k-\tau}` (the paper used 20 samples for this system). .. GENERATED FROM PYTHON SOURCE LINES 53-73 .. code-block:: Python # [snippet:data] states = make_rossler(n_samples=2200, dt=0.05) x = states[:, 0] # the only measured variable tau = select_delay(x, max_lag=60, method="mutual_information") n_train = 1500 print("lag from the mutual information:", tau) # [/snippet:data] fig, axes = plt.subplots(1, 2, figsize=(10, 3.4), gridspec_kw={"width_ratios": [2, 1]}) axes[0].plot(x[:600], color=PALETTE[0], lw=0.9) axes[0].set_xlabel("sample $k$") axes[0].set_ylabel("$x_1$") axes[0].set_title("Rössler system observed through $x_1$") axes[1].plot(states[:, 0], states[:, 1], color="0.4", lw=0.4) axes[1].set_xlabel("$x_1$") axes[1].set_ylabel("$x_2$") axes[1].set_title("True attractor ($x_1$, $x_2$)") plt.tight_layout() .. image-sg:: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_001.png :alt: Rössler system observed through $x_1$, True attractor ($x_1$, $x_2$) :srcset: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none lag from the mutual information: 15 .. GENERATED FROM PYTHON SOURCE LINES 74-83 Embedding and local dimension from the clustering ------------------------------------------------- For :math:`d_e=1,\dots,5`, a model with eight regimes is identified on the first 1500 samples and evaluated on the rest. The one-step error stops improving at :math:`d_e=3`, and the prior-weighted smallest eigenvalue :math:`J^{d_e}` of the cluster covariances drops by a factor of three at :math:`d_e=3` and keeps falling. The trajectory therefore lies on a two-dimensional surface inside the three-dimensional reconstructed space, the well-known picture of the Rössler band. .. GENERATED FROM PYTHON SOURCE LINES 83-96 .. code-block:: Python # [snippet:scan] table = embedding_scan(x, dims=(1, 2, 3, 4, 5), delay=tau, n_clusters=8, train_fraction=n_train / x.size, random_state=0) choice = select_embedding_dimension(table, ratio_tol=1.3) print(table.round(5)) print(f"embedding dimension d_e = {choice.embedding_dimension}, local dimension d_l = {choice.local_dimension}") # [/snippet:scan] axes = plot_embedding_scan(table, selected=choice) axes[0].set_title("Embedding dimension from the prediction error, local dimension from the eigenvalues") plt.tight_layout() .. image-sg:: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_002.png :alt: Embedding dimension from the prediction error, local dimension from the eigenvalues :srcset: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none mse_train mse_test mse_ratio local_dimension_index dim 1 0.15621 0.15149 NaN 0.85605 2 0.01354 0.01712 8.84695 1.25991 3 0.00632 0.00963 1.77786 0.40511 4 0.00901 0.01263 0.76266 0.18578 5 0.00517 0.00887 1.42411 0.06111 embedding dimension d_e = 3, local dimension d_l = 2 .. GENERATED FROM PYTHON SOURCE LINES 97-103 Two independent checks agree. The false-nearest-neighbor test with the cluster-based threshold (the model-order method of the previous example, applied to the scalar series with lag :math:`\tau`) also collapses at :math:`d_e=3`, and the correlation dimension of Grassberger and Procaccia, the fractal counterpart of the integer local dimension, is close to two on the reconstructed vectors: .. GENERATED FROM PYTHON SOURCE LINES 103-108 .. code-block:: Python fnn = fnn_model_order(x[:n_train], max_na=5, n_clusters=6, delay=tau, random_state=0) print("false nearest neighbors [%] for d_e = 1..5:", fnn.table.iloc[1:, 0].round(1).tolist()) Y3 = delay_embedding(x, dim=3, delay=tau) print(f"correlation dimension of the reconstructed attractor: {correlation_dimension(Y3, random_state=0).dimension:.2f}") .. rst-class:: sphx-glr-script-out .. code-block:: none false nearest neighbors [%] for d_e = 1..5: [98.7, 14.5, 1.9, 0.7, 0.0] correlation dimension of the reconstructed attractor: 1.92 .. GENERATED FROM PYTHON SOURCE LINES 109-117 The model in the reconstructed space ------------------------------------ With :math:`d_e=3` and twelve Gaussian regimes, the model tiles the reconstructed attractor; every regime carries a local linear model of the next sample. Fed with its own predictions (free run), the model keeps spiraling on a Rössler-like band. Because the series is chaotic, however, the simulated trajectory leaves the measured one after a few cycles and visits the outer part of the band more often than the system does. .. GENERATED FROM PYTHON SOURCE LINES 117-154 .. code-block:: Python # [snippet:fit] model = ChaoticPredictor(dim=3, delay=tau, n_clusters=12, random_state=0).fit(x[:n_train]) print(f"one-step test MSE: {model.one_step_error(x[n_train:]):.4f} (variance of x: {x.var():.2f})") simulated = model.simulate(x[:n_train], n_steps=x.size - n_train) # [/snippet:fit] fig, axes = plt.subplots(1, 2, figsize=(10, 4.2)) plot_phase_space(model.embedding_, model.labels_, centers=model.cluster_centers_, ax=axes[0]) axes[0].set_title("Reconstructed state space ($d_e=3$) with the twelve regimes") Y_true = delay_embedding(x[n_train:], 3, tau) Y_sim = delay_embedding(simulated, 3, tau) axes[1].plot(Y_true[:, 0], Y_true[:, 1], color="0.5", lw=0.7, label="measured") axes[1].plot(Y_sim[:, 0], Y_sim[:, 1], color=PALETTE[1], lw=0.7, ls="--", label="free-run simulation") axes[1].set_xlabel("$y_k$") axes[1].set_ylabel(r"$y_{k-\tau}$") axes[1].set_title("Free-run simulation in the reconstructed space") axes[1].legend(frameon=False, fontsize=8) plt.tight_layout() horizons = (1, 2, 5, 10, 20, 40, 80) err = model.multi_step_error(x[n_train:], horizons=horizons) fig, axes = plt.subplots(1, 2, figsize=(10, 3.4), gridspec_kw={"width_ratios": [2, 1]}) k = np.arange(n_train, x.size) axes[0].plot(k, x[n_train:], color="0.4", lw=1, label="measured") axes[0].plot(k, simulated, color=PALETTE[1], lw=1, ls="--", label="free run from $k=1500$") axes[0].set_xlabel("sample $k$") axes[0].set_ylabel("$x_1$") axes[0].set_title("Free-run prediction of the test part") axes[0].legend(frameon=False, fontsize=8) axes[1].semilogy(err.index, err.to_numpy() / x.var(), "o-", color=PALETTE[0]) axes[1].set_xlabel("prediction horizon [samples]") axes[1].set_ylabel("MSE / var($x_1$)") axes[1].set_title("Error grows with the horizon") axes[1].grid(True, color="0.9", which="both") plt.tight_layout() .. rst-class:: sphx-glr-horizontal * .. image-sg:: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_003.png :alt: Reconstructed state space ($d_e=3$) with the twelve regimes, Free-run simulation in the reconstructed space :srcset: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_003.png :class: sphx-glr-multi-img * .. image-sg:: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_004.png :alt: Free-run prediction of the test part, Error grows with the horizon :srcset: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_004.png :class: sphx-glr-multi-img .. rst-class:: sphx-glr-script-out .. code-block:: none one-step test MSE: 0.0061 (variance of x: 23.51) .. GENERATED FROM PYTHON SOURCE LINES 155-164 Visualizing the regimes with fuzzy Sammon mapping ------------------------------------------------- The clusters live in the three-dimensional reconstructed space with Mahalanobis-type distances. The fuzzy Sammon mapping (see the visualization chapter) projects the data and the regime centers onto the plane so that the *cluster-to-sample* distances of the clustering are preserved. Each regime becomes a compact circular group, and the order in which the trajectory visits the regimes is visible in the ring structure. A PCA projection of the same vectors is shown for comparison. .. GENERATED FROM PYTHON SOURCE LINES 164-174 .. code-block:: Python fuzzsam = FuzzySammon(max_iter=200, random_state=0).fit(model, model.embedding_) Y_pca, Z_pca, _ = pca_projection(model.embedding_, 2, model.cluster_centers_) fig, axes = plt.subplots(1, 2, figsize=(10, 4.4)) plot_projection(Y_pca, Z_pca, labels=model.labels_, U=model.membership_, ax=axes[0], legend=False) axes[0].set_title("PCA projection of the delay vectors and regime centers") plot_projection(fuzzsam.embedding_, fuzzsam.embedded_centers_, labels=model.labels_, U=model.membership_, ax=axes[1], legend=False) axes[1].set_title(f"Fuzzy Sammon mapping (stress {fuzzsam.stress_:.3g})") plt.tight_layout() .. image-sg:: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_005.png :alt: PCA projection of the delay vectors and regime centers, Fuzzy Sammon mapping (stress 86.7) :srcset: /auto_examples/04_timeseries/images/sphx_glr_plot_04_chaotic_reconstruction_005.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 175-185 Parameter study: number of regimes and lag ------------------------------------------ More regimes give a finer piecewise-linear approximation of the map, lower one-step errors and, except at the long lag, lower ten-step errors (until the regimes receive too few samples). A short lag gives small one-step errors because consecutive samples are almost collinear and the prediction is close to an extrapolation, but it stretches the reconstructed attractor along the diagonal. A long lag (30 samples, about a third of the mean revolution of some 90 samples) folds the attractor, and the errors grow. The mutual-information lag is the usual compromise. .. GENERATED FROM PYTHON SOURCE LINES 185-197 .. code-block:: Python # [snippet:params] rows = [] for c in (3, 6, 12): for delay in (5, tau, 30): mdl = ChaoticPredictor(dim=3, delay=delay, n_clusters=c, random_state=0).fit(x[:n_train]) rows.append((c, delay, mdl.one_step_error(x[n_train:]), mdl.multi_step_error(x[n_train:], (10,))[10])) # [/snippet:params] print(f"{'regimes':>7} {'lag':>4} {'1-step MSE':>11} {'10-step MSE':>12}") for c, delay, e1, e10 in rows: print(f"{c:>7} {delay:>4} {e1:>11.4f} {e10:>12.3f}") .. rst-class:: sphx-glr-script-out .. code-block:: none regimes lag 1-step MSE 10-step MSE 3 5 0.0160 6.356 3 15 0.0620 4.128 3 30 0.1038 6.545 6 5 0.0078 2.732 6 15 0.0114 0.800 6 30 0.0662 4.885 12 5 0.0030 0.128 12 15 0.0061 0.344 12 30 0.0547 5.268 .. GENERATED FROM PYTHON SOURCE LINES 198-206 Three chaotic systems at a glance --------------------------------- The classical false-nearest-neighbor test on the scalar series (with the embedding lag) gives a first estimate of the embedding dimension, and the correlation dimension of the reconstructed vectors gives the fractal dimension of the attractor. It is close to 2 for all three systems; the known values are 1.99 (Rössler), 2.06 (Lorenz), and about 2.1 (Mackey–Glass, :math:`\tau_{MG}=17`). .. GENERATED FROM PYTHON SOURCE LINES 206-219 .. code-block:: Python systems = { "Rössler": x, "Lorenz": make_lorenz(n_samples=2200, dt=0.02)[:, 0], "Mackey–Glass": make_mackey_glass(n_samples=2200), } print(f"{'system':>13} {'lag':>4} {'FNN % for d_e = 1..5':>28} {'D_2':>6}") for name, series in systems.items(): lag = select_delay(series, max_lag=60) fnn = false_nearest_neighbors(series, max_na=5, delay=lag) d2 = correlation_dimension(delay_embedding(series, 4, lag), random_state=0).dimension pct = " ".join(f"{v:5.1f}" for v in fnn.iloc[1:, 0]) print(f"{name:>13} {lag:>4} {pct:>28} {d2:>6.2f}") .. rst-class:: sphx-glr-script-out .. code-block:: none system lag FNN % for d_e = 1..5 D_2 Rössler 15 97.3 6.8 0.2 0.0 0.0 1.97 Lorenz 8 98.4 3.9 0.0 0.0 0.0 1.90 Mackey–Glass 12 98.1 12.7 0.5 0.0 0.0 2.00 .. GENERATED FROM PYTHON SOURCE LINES 220-230 **Take-away.** Clustering the delay vectors together with their successors identifies a predictive operating-regime model of a chaotic series and, as a by-product, the two dimensions that characterize the reconstruction: the embedding dimension from the saturation of the one-step error and the local dimension from the collapse of the smallest eigenvalues of the regimes. The free-run simulation reproduces the attractor but, as for any chaotic system, diverges from the measured trajectory as the horizon grows. The fuzzy Sammon mapping shows the regimes and their cyclic order in one picture, which makes the model inspectable. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 5.904 seconds) .. _sphx_glr_download_auto_examples_04_timeseries_plot_04_chaotic_reconstruction.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/fuzzyclust/main?urlpath=lab/tree/notebooks/auto_examples/04_timeseries/plot_04_chaotic_reconstruction.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_04_chaotic_reconstruction.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_04_chaotic_reconstruction.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_04_chaotic_reconstruction.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_