r"""
Autocorrelation-based fuzzy clustering of time series
=====================================================

Some time series belong together not because their values agree but
because they are generated by the same *mechanism*: two realizations of
one stationary process have nothing in common point by point (their
noise is independent), yet they share their dependence structure. D'Urso
and Maharaj proposed representing every series by its estimated
autocorrelation function up to lag :math:`L`,
:math:`(\hat\rho_k(1),\dots,\hat\rho_k(L))`, and clustering these vectors
with fuzzy c-means (A-FCM) or fuzzy c-medoids (A-FCMd) under the
(optionally lag-weighted) squared Euclidean distance. The representation
is independent of level, scale and phase and has the same length for
series of any length; the fuzzy memberships express that a process can lie
between two typical dependence patterns. The squared autocorrelation
distance is Euclidean, so relational fuzzy c-means on it is exactly A-FCM.
"""

# %%
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import linear_sum_assignment
from sklearn.metrics import adjusted_rand_score

from fuzzyclust import FCM
from fuzzyclust.plotting import PALETTE
from fuzzyclust.relational import (
    FuzzyCMedoids,
    RelationalFCM,
    autocorrelation_distance_matrix,
    autocorrelation_features,
    pairwise_dissimilarity,
)


def arma11(n_series, length, phi=0.0, theta=0.0, rng=None, burn_in=50):
    """Gaussian ARMA(1,1) series x_t = phi x_{t-1} + e_t + theta e_{t-1}."""
    e = rng.randn(n_series, length + burn_in + 1)
    x = np.zeros_like(e)
    for t in range(1, e.shape[1]):
        x[:, t] = phi * x[:, t - 1] + e[:, t] + theta * e[:, t - 1]
    return x[:, burn_in + 1 :]


def make_processes(length=200, n_per_class=25, random_state=0):
    """Three classes: AR(1) with phi=0.5, MA(1) with theta=0.9, AR(1) with phi=-0.6."""
    rng = np.random.RandomState(random_state)
    X = np.vstack([
        arma11(n_per_class, length, phi=0.5, rng=rng),
        arma11(n_per_class, length, theta=0.9, rng=rng),
        arma11(n_per_class, length, phi=-0.6, rng=rng),
    ])
    return X, np.repeat(np.arange(3), n_per_class)


X, y = make_processes(length=200, random_state=0)
names = (r"AR(1), $\phi=0.5$", r"MA(1), $\theta=0.9$", r"AR(1), $\phi=-0.6$")

# %%
# Three processes, indistinguishable by their values
# --------------------------------------------------
# A persistent autoregressive process, a moving-average process and an
# alternating autoregressive process, 25 series of length 200 each. The
# first two have practically the same lag-1 autocorrelation (0.50 and
# 0.497); they differ only from lag 2 on, where the AR(1) correlation decays
# geometrically and the MA(1) correlation is exactly zero. The bottom row
# shows the estimated autocorrelation functions of all series of a class
# with the theoretical one: the estimates scatter with a standard error of
# about :math:`1/\sqrt{T}`, so the clusters will overlap. In the figures
# below, each cluster carries the number of the process it matches.
lags = np.arange(1, 11)
theory = (0.5**lags, np.where(lags == 1, 0.9 / (1 + 0.9**2), 0.0), (-0.6) ** lags)
A10 = autocorrelation_features(X, n_lags=10)
fig, axes = plt.subplots(2, 3, figsize=(13, 5.6), sharey="row")
for i in range(3):
    for k in np.flatnonzero(y == i)[:2]:
        axes[0, i].plot(X[k, :80], color=PALETTE[i], lw=1.0, alpha=0.9)
    axes[0, i].set_title(f"class {i + 1}: {names[i]} (2 series)")
    axes[0, i].set_xlabel("time index")
    for k in np.flatnonzero(y == i):
        axes[1, i].plot(lags, A10[k], color=PALETTE[i], alpha=0.25, lw=0.8)
    axes[1, i].plot(lags, theory[i], "k--o", ms=3, lw=1.4, label="theoretical")
    axes[1, i].axhline(0, color="0.6", lw=0.6)
    axes[1, i].set_xlabel("lag $l$")
    axes[1, i].set_title(f"estimated autocorrelations, class {i + 1}")
    axes[1, i].legend(frameon=False, fontsize=8)
axes[1, 0].set_ylabel(r"$\hat\rho_k(l)$")
plt.tight_layout()

# %%
# A-FCM and A-FCMd
# ----------------
# The series are mapped to their autocorrelations up to lag :math:`L=5`
# and clustered. A-FCM is fuzzy c-means on these vectors; A-FCMd is fuzzy
# c-medoids on the matrix of squared autocorrelation distances, so its
# prototypes are three actual series; relational FCM on the same matrix
# reproduces A-FCM. For comparison, fuzzy c-medoids on the Euclidean
# distances of the raw values finds nothing: independent realizations
# of one process are as far apart as realizations of different processes.

# [snippet:fit]
A = autocorrelation_features(X, n_lags=5)                    # (75, 5) feature vectors
D2 = autocorrelation_distance_matrix(X, n_lags=5) ** 2        # squared ACF distances
afcm = FCM(n_clusters=3, n_init=5, random_state=0).fit(A)                              # A-FCM
afcmd = FuzzyCMedoids(n_clusters=3, metric="precomputed", n_init=5, random_state=0).fit(D2)  # A-FCMd
rfcm = RelationalFCM(n_clusters=3, metric="precomputed", init=afcm.membership_).fit(D2)
raw = FuzzyCMedoids(n_clusters=3, metric="precomputed", n_init=5, random_state=0).fit(pairwise_dissimilarity(X))
for name, model in (("A-FCM", afcm), ("A-FCMd", afcmd), ("RFCM on ACF", rfcm), ("raw values", raw)):
    print(f"{name:12s}: ARI = {adjusted_rand_score(y, model.labels_):.2f}")
print(f"max |U_RFCM - U_A-FCM| = {np.abs(rfcm.membership_ - afcm.membership_).max():.1e}")
print("medoid series of A-FCMd:", afcmd.medoid_indices_.tolist())
# [/snippet:fit]

# number each cluster after the process whose theoretical autocorrelations it matches
rho_theory = np.array([t[:5] for t in theory])
perm = linear_sum_assignment(((rho_theory[:, None, :] - afcm.cluster_centers_[None]) ** 2).sum(axis=2))[1]
U = afcm.membership_[:, perm]
labels, centers = U.argmax(axis=1), afcm.cluster_centers_[perm]

fig, axes = plt.subplots(1, 2, figsize=(12, 4.2), gridspec_kw={"width_ratios": [1, 1.3]})
for i in range(3):
    members = labels == i
    axes[0].scatter(A[members, 0], A[members, 1], s=18 + 40 * U[members, i] ** 2, color=PALETTE[i],
                    alpha=0.75, label=f"cluster {i + 1}")
axes[0].scatter(centers[:, 0], centers[:, 1], marker="X", s=140, color="black",
                label="A-FCM centers")
axes[0].scatter(A[afcmd.medoid_indices_, 0], A[afcmd.medoid_indices_, 1], marker="s", s=90, facecolor="none",
                edgecolor="black", lw=1.5, label="A-FCMd medoids")
axes[0].scatter([0.5, 0.9 / 1.81, -0.6], [0.25, 0.0, 0.36], marker="*", s=160, color="gold", edgecolor="black",
                zorder=5, label="theoretical")
axes[0].set_xlabel(r"$\hat\rho(1)$")
axes[0].set_ylabel(r"$\hat\rho(2)$")
axes[0].set_title("First two autocorrelations (size: membership)")
axes[0].legend(frameon=False, fontsize=7, loc="center")
bottom = np.zeros(len(y))
for i in range(3):
    axes[1].bar(np.arange(len(y)), U[:, i], bottom=bottom, color=PALETTE[i], width=1.0,
                label=f"cluster {i + 1}")
    bottom += U[:, i]
for b_ in (25, 50):
    axes[1].axvline(b_ - 0.5, color="white", lw=1.5)
axes[1].set_xlim(-0.5, len(y) - 0.5)
axes[1].set_ylim(0, 1)
axes[1].set_xlabel("series (ordered by true class)")
axes[1].set_ylabel(r"$\mu_{ik}$")
axes[1].set_title("A-FCM memberships ($L=5$; colors as on the left)")
plt.tight_layout()

# %%
# Graded memberships for processes in between
# -------------------------------------------
# The fuzziness is not only noise. New AR(1) series with a coefficient
# :math:`\phi` swept from :math:`-0.9` to :math:`0.9` are assigned to the
# fitted clusters with ``predict_proba`` (40 series per value, averaged).
# The membership moves smoothly from the alternating cluster (3) through
# the region of white noise, where the three clusters share the
# membership, to the persistent cluster (1); the MA(1) cluster (2) takes
# its largest share around :math:`\phi\approx0.2`--:math:`0.3`, between
# white noise and the AR(1) prototype, since no AR(1) process reproduces
# its lag-1 correlation of one half together with a zero at lag 2.
phis = np.linspace(-0.9, 0.9, 19)
rng = np.random.RandomState(1)
U_new = np.array([afcm.predict_proba(autocorrelation_features(arma11(40, 200, phi=p, rng=rng), 5))[:, perm].mean(axis=0)
                  for p in phis])
fig, ax = plt.subplots(figsize=(7, 3.6))
for i in range(3):
    ax.plot(phis, U_new[:, i], "o-", color=PALETTE[i], ms=4, label=f"cluster {i + 1}")
for p in (0.5, -0.6):
    ax.axvline(p, color="0.6", ls=":")
ax.set_xlabel(r"AR(1) coefficient $\phi$ of the new series")
ax.set_ylabel("mean membership")
ax.set_ylim(0, 1)
ax.set_title("Memberships of new AR(1) series in the fitted clusters")
ax.legend(frameon=False, fontsize=8)
ax.grid(True, color="0.9")
plt.tight_layout()

# %%
# Parameter study I: number of lags and length of the series
# ----------------------------------------------------------
# The number of lags decides what the clustering can see. With
# :math:`L=1` the AR(1) and the MA(1) classes coincide and are merged; from
# :math:`L=2` on they are separated. Many lags do not help: beyond the
# few lags at which the processes differ, every additional coordinate adds
# estimation noise of the same size :math:`1/\sqrt{T}` for all series, and
# the memberships flatten. Longer series shrink this noise; short series
# (:math:`T=50`) leave the classes overlapping for any :math:`L`.

# [snippet:lags]
rows = []
for T in (50, 100, 200, 400):
    XT, yT = make_processes(length=T, random_state=0)
    for L in (1, 2, 3, 5, 10, 20):
        model = FCM(n_clusters=3, n_init=5, random_state=0).fit(autocorrelation_features(XT, n_lags=L))
        rows.append((T, L, adjusted_rand_score(yT, model.labels_), model.membership_.max(axis=1).mean()))
# [/snippet:lags]
rows = np.asarray(rows)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
for p, T in enumerate((50, 100, 200, 400)):
    sel = rows[:, 0] == T
    axes[0].plot(rows[sel, 1], rows[sel, 2], "o-", color=PALETTE[p], label=f"$T={T}$")
    axes[1].plot(rows[sel, 1], rows[sel, 3], "s-", color=PALETTE[p], label=f"$T={T}$")
for ax, lab, title in ((axes[0], "ARI", "Agreement with the processes"),
                       (axes[1], "mean max. membership", "Sharpness of the partition")):
    ax.set_xscale("log")
    ax.set_xticks([1, 2, 3, 5, 10, 20])
    ax.set_xticklabels(["1", "2", "3", "5", "10", "20"])
    ax.set_xlabel("number of lags $L$")
    ax.set_ylabel(lab)
    ax.set_ylim(0, 1.05)
    ax.set_title(title)
    ax.grid(True, color="0.9")
axes[0].legend(frameon=False, fontsize=8, loc="lower right")
plt.tight_layout()

# %%
# Parameter study II: lag weights and the fuzziness exponent
# ----------------------------------------------------------
# When :math:`L` has to be large because it is not known at which lags
# the processes differ, decaying lag weights :math:`w_l=q^{\,l-1}` keep
# the noisy high lags from dominating: with :math:`L=20`, uniform weights
# lose part of the structure, and weights with :math:`q\le0.8` restore the
# result of a short lag window. The exponent :math:`m` softens the
# partition as usual; the hard labels are stable.
print("L = 20, lag weights q^(l-1), A-FCMd:")
for q in (1.0, 0.9, 0.8, 0.6):
    Dq = autocorrelation_distance_matrix(X, n_lags=20, weights=q ** np.arange(20)) ** 2
    model = FuzzyCMedoids(n_clusters=3, metric="precomputed", n_init=5, random_state=0).fit(Dq)
    print(f"  q = {q:.1f}: ARI = {adjusted_rand_score(y, model.labels_):.2f}")
print("L = 5, fuzziness exponent, A-FCM:")
for m in (1.5, 2.0, 3.0):
    model = FCM(n_clusters=3, m=m, n_init=5, random_state=0).fit(A)
    print(f"  m = {m:.1f}: ARI = {adjusted_rand_score(y, model.labels_):.2f}, "
          f"mean max membership = {model.membership_.max(axis=1).mean():.2f}")

# %%
# **Take-away.** When series are realizations of processes, the right
# question is not whether their values agree but whether their dependence
# structure does; the estimated autocorrelation function answers it with a
# fixed-length vector that is blind to level, scale and phase. A-FCM and
# A-FCMd cluster these vectors (relational FCM on the squared distances is
# the same as A-FCM), and the memberships grade processes that lie between
# the typical patterns. The number of lags must cover the lags at which the
# processes differ but not much more, because every extra lag adds
# estimation noise of order :math:`1/\sqrt{T}`; decaying lag weights make a
# generous :math:`L` safe, and longer series sharpen everything.
