"""
Fuzzy segmentation with the modified Gath--Geva algorithm
=========================================================

Abonyi, Feil, Nemeth and Arva (2005) treat segmentation as clustering in
which every cluster has a Gaussian membership in *time* and a probabilistic
PCA model of the variables. The memberships are fuzzy, so gradual
transitions show up as overlapping segments; compatible clusters are merged
and a monotone crisp labelling is read off at the end.
"""

import matplotlib.pyplot as plt

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import evaluate_segmentation

X, cps, _ = mv.datasets.make_correlation_switching(
    n_segments=4, length=150, random_state=0
)

# %%
# Memberships and crisp segments
# ------------------------------
gg = sg.GGSegmenter(
    n_segments=6, n_components=1
)  # start with more clusters than needed
seg = gg.segment(X)
print(
    "clusters after merging:",
    seg.n_segments,
    "| change points:",
    seg.change_points,
    "| true:",
    cps,
)
print(evaluate_segmentation(cps, seg, len(X), margin=10)["f1"])
mv.viz.plot_fuzzy_segmentation(X, seg)

# %%
# Parameter study: the initial number of clusters
# -----------------------------------------------
# The merging step removes the surplus clusters as long as the start is
# generous.
for c in (4, 6, 8, 10):
    s = sg.GGSegmenter(n_segments=c, n_components=1).segment(X)
    print(
        f"start {c:2d} -> {s.n_segments} segments, F1 {evaluate_segmentation(cps, s, len(X), 10)['f1']:.2f}"
    )
plt.show()
