r"""
Fuzzy segmentation of a multivariate time series
================================================

A multivariate time series is segmented into internally homogeneous
pieces. The segments are found by a modified Gath–Geva clustering whose
prototype has two parts: a Gaussian membership function in *time*, which
makes the clusters contiguous, and a local probabilistic PCA model of the
observations, which measures the homogeneity of a segment. Because a PCA
hyperplane reacts to changes in the mean, in the variance, *and* in the
correlation structure, all three kinds of regime change are detected,
including those that are invisible in any single variable.

The synthetic data reproduce the benchmark of Abonyi, Feil, Németh, and Árva
(Fuzzy Sets and Systems, 2005): two hidden variables generate six observed
ones through a mixing matrix. At the first change point the mixing matrix
(the correlation structure) changes, at the second the mean of the hidden
variables jumps, and at the third both change.
"""

# %%
import matplotlib.pyplot as plt
import numpy as np

from fuzzyclust.plotting import PALETTE
from fuzzyclust.timeseries import FuzzySegmentation, make_piecewise_timeseries, plot_segmentation

# %%
# The data: hidden regime changes behind six observed variables
# -------------------------------------------------------------
# [snippet:data]
X, true_segments = make_piecewise_timeseries(
    n_samples=2000,
    n_features=6,
    n_latent=2,
    change_points=(500, 1000, 1500),
    change_kinds=("correlation", "mean", "both"),
    noise=0.15,
    random_state=0,
)
t = np.arange(X.shape[0])
# [/snippet:data]

fig, axes = plt.subplots(6, 1, figsize=(9, 7), sharex=True)
for j, ax in enumerate(axes):
    ax.plot(t, X[:, j], color="0.3", lw=0.6)
    for cp in (500, 1000, 1500):
        ax.axvline(cp, color=PALETTE[1], ls="--", lw=1)
    ax.set_ylabel(f"$x_{j + 1}$")
axes[0].set_title("Six observed variables; dashed lines: true change points (correlation, mean, both)")
axes[-1].set_xlabel("time")
plt.tight_layout()

# %%
# The first change (at 500) only alters the correlation among the variables
# and leaves every mean in place, so a univariate segmentation would miss it.
#
# Number of principal components from the scree plot of the initial segments
# --------------------------------------------------------------------------
# The algorithm starts from a uniform partition into ``n_segments`` pieces.
# The eigenvalues of the covariance matrices of these pieces show how many
# components the local models need. Two eigenvalues stand out, and the other
# four lie at the noise level, so :math:`q=2` (the number of hidden
# variables). The two components explain about 85 % of the variance inside a
# regime, the rest being noise, so a required accuracy of 95 % would select
# more components. ``n_components`` accepts this integer or a required
# accuracy (fraction of explained variance), which selects :math:`q`
# automatically.
pieces = np.array_split(np.arange(X.shape[0]), 10)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4))
for seg in pieces:
    lam = np.sort(np.linalg.eigvalsh(np.cov(X[seg], rowvar=False)))[::-1]
    axes[0].plot(np.arange(1, 7), lam, "o-", color="0.3", lw=1, ms=4, alpha=0.7)
    axes[1].plot(np.arange(1, 7), np.cumsum(lam) / lam.sum(), "o-", color="0.3", lw=1, ms=4, alpha=0.7)
axes[0].set_title("Scree plot of the ten initial segments")
axes[0].set_xlabel("eigenvalue index")
axes[0].set_ylabel("eigenvalue")
axes[0].set_yscale("log")
axes[1].set_title("Cumulative fraction of variance")
axes[1].set_xlabel("number of components")
axes[1].axhline(0.95, color=PALETTE[1], ls="--", lw=1)
axes[1].set_ylim(0.5, 1.02)
plt.tight_layout()

# %%
# Segmentation into four fuzzy segments
# -------------------------------------
# With the right number of segments and two principal components, the
# borders are found within a few samples. ``boundaries_`` holds the crisp
# change points (where the dominant Gaussian in time changes),
# ``time_membership_`` the fuzzy segments :math:`\beta_i(t_k)`, and
# ``membership_`` the posterior probabilities :math:`p(\eta_i|\mathbf{z}_k)`,
# which also take the observations into account.

# [snippet:fit]
fs = FuzzySegmentation(n_segments=4, n_components=2).fit(X)
print("segment borders:", fs.boundaries_)
print("time centers   :", np.round(fs.segment_centers_))
print("time std       :", np.round(np.sqrt(fs.segment_variances_), 1))
# [/snippet:fit]

axes = plot_segmentation(fs, X, features=[0, 1], feature_names=[f"$x_{j + 1}$" for j in range(6)])
axes[0].set_title("Fuzzy segmentation with four segments: borders, fuzzy segments in time and posteriors")
plt.gcf().set_size_inches(9, 6.2)
plt.tight_layout()

# %%
# The Gaussian membership functions overlap only around the borders, and the
# posteriors are almost crisp inside the segments, because the local PCA
# models of neighboring segments explain each other's data poorly. The PCA
# similarity of the adjacent models shows which change was a change of
# structure:
O, S_pca, D_centers = fs.compatibility_matrix()
for i in range(3):
    print(f"segments {i + 1}-{i + 2}: S_PCA = {S_pca[i, i + 1]:.3f}, center distance = {D_centers[i, i + 1]:.2f}")

# %%
# Parameter study I: number of segments and number of components
# --------------------------------------------------------------
# With fewer segments than regimes, one border has to be sacrificed; with
# more segments, a regime is split (the extra borders fall inside a regime,
# and the surplus segments are highly compatible; see the merging below).
# The number of principal components matters less for the PPCA distance.
# With :math:`q=1` the models cannot represent the two-dimensional hidden
# structure and one border drifts; from :math:`q=2` on, the result is stable.

# [snippet:scan]
def borders_for(**kwargs):
    return FuzzySegmentation(n_components=2, **kwargs).fit(X).boundaries_


fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), sharey=False)
for c in (2, 3, 4, 5, 6, 8):
    b = borders_for(n_segments=c)
    axes[0].plot(b, np.full(b.size, c), "|", color=PALETTE[0], ms=14, mew=2)
for q in (1, 2, 3, 5):
    b = FuzzySegmentation(n_segments=4, n_components=q).fit(X).boundaries_
    axes[1].plot(b, np.full(b.size, q), "|", color=PALETTE[2], ms=14, mew=2)
# [/snippet:scan]
for ax, ylabel, title in zip(
    axes,
    ("number of segments $c$", "number of components $q$"),
    ("Borders versus the number of segments ($q=2$)", "Borders versus the number of components ($c=4$)"),
    strict=True,
):
    for cp in (500, 1000, 1500):
        ax.axvline(cp, color=PALETTE[1], ls="--", lw=1)
    ax.set_xlabel("time")
    ax.set_ylabel(ylabel)
    ax.set_title(title)
    ax.set_xlim(0, 2000)
axes[0].set_yticks([2, 3, 4, 5, 6, 8])
axes[1].set_yticks([1, 2, 3, 5])
plt.tight_layout()

# %%
# Parameter study II: the three distance measures
# -----------------------------------------------
# The conference version of the method restricted the Gaussian of the
# observations to the residual subspace (reconstruction error :math:`Q`)
# or to the principal subspace (Hotelling :math:`T^2`). Both are sensitive
# to :math:`q`. :math:`Q` works with the true latent dimension but becomes
# meaningless when :math:`q` approaches :math:`n`; :math:`T^2` needs a high
# accuracy so that all segments keep a comparable model complexity. The
# PPCA distance of the journal version combines the two subspaces and is
# far less sensitive to :math:`q`.
rows = []
for distance, q in (("ppca", 2), ("ppca", 5), ("q", 2), ("q", 5), ("t2", 2), ("t2", 0.99)):
    model = FuzzySegmentation(n_segments=4, n_components=q, distance=distance).fit(X)
    rows.append((distance, q, model.n_components_, model.boundaries_.tolist()))
print(f"{'distance':>9} {'n_components':>13} {'q used':>7}  borders")
for distance, q, q_used, borders in rows:
    print(f"{distance:>9} {q!s:>13} {q_used:>7}  {borders}")

# %%
# Finding the number of segments by compatible cluster merging
# ------------------------------------------------------------
# Starting from ten segments, the most compatible adjacent pair is merged
# whenever its compatibility :math:`O_{i,i+1}` (an aggregate of the
# parallelism of the PCA models and the closeness of the centers) exceeds
# the threshold :math:`\gamma`, and the clustering continues. Two surplus
# segments inside one regime have nearly identical models and close
# centers, so they are merged first; segments of different regimes are
# kept apart.

# [snippet:merge]
fs10 = FuzzySegmentation(n_segments=10, n_components=2, merge=True, merge_threshold=0.75).fit(X)
print("segments after merging:", fs10.n_segments_, "borders:", fs10.boundaries_)
# [/snippet:merge]
O10, _, _ = FuzzySegmentation(n_segments=10, n_components=2).fit(X).compatibility_matrix()

fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), gridspec_kw={"width_ratios": [1, 1.6]})
im = axes[0].imshow(O10, cmap="Blues", vmin=0, vmax=1)
axes[0].set_title("Compatibility $O_{ij}$ of the ten initial segments")
axes[0].set_xlabel("segment $j$")
axes[0].set_ylabel("segment $i$")
axes[0].set_xticks(range(10))
axes[0].set_xticklabels(range(1, 11))
axes[0].set_yticks(range(10))
axes[0].set_yticklabels(range(1, 11))
plt.colorbar(im, ax=axes[0], fraction=0.046)
for i in range(fs10.n_segments_):
    axes[1].plot(t, fs10.time_membership_[:, i], color=PALETTE[i % len(PALETTE)], lw=1.6)
for cp in (500, 1000, 1500):
    axes[1].axvline(cp, color="k", ls="--", lw=0.8)
axes[1].set_title(f"Fuzzy segments after merging from 10 to {fs10.n_segments_} segments ($\\gamma=0.75$)")
axes[1].set_xlabel("time")
axes[1].set_ylabel(r"$\beta_i(t_k)$")
plt.tight_layout()

# %%
# The threshold determines how different two neighbors must be to survive
# as separate segments:
for gamma in (0.5, 0.65, 0.75, 0.85):
    model = fs10 if gamma == 0.75 else FuzzySegmentation(
        n_segments=10, n_components=2, merge=True, merge_threshold=gamma
    ).fit(X)
    print(f"gamma = {gamma:.2f}: {model.n_segments_} segments, borders {model.boundaries_.tolist()}")

# %%
# **Take-away.** Time-series segmentation is clustering with a prototype
# that knows about time. The Gaussian in time keeps the segments contiguous
# and the local PCA model measures their homogeneity, so mean shifts and
# changes in the correlation structure are detected together, which no
# univariate method can do. The number of components is read off the
# scree plot of the initial segments (or set by a required accuracy), and
# the number of segments is found by merging compatible neighbors, starting
# from a deliberately large initial number. The merging threshold
# :math:`\gamma` (between 0.3 and 0.75 in the paper, higher when small mean
# shifts must be preserved) is the one parameter that encodes how different
# two regimes have to be.
