r"""
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.
"""

# %%
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

# %%
# 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).

# [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()

# %%
# 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.

# [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()

# %%
# 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:
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}")

# %%
# 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.

# [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()

# %%
# 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.
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()

# %%
# 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.

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

# %%
# 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`).
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}")

# %%
# **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.
