"""
Clustering segments: recurring patterns across series
=====================================================

Instead of clustering whole series, every series is segmented and the
segments of all series are clustered. The result is a vocabulary of
operating patterns: each series becomes a sequence of pattern labels, and
the patterns can be compared across batches, shifts or units.
"""

import matplotlib.pyplot as plt
import numpy as np

import mvtsa as mv
from mvtsa import clustering as cl
from mvtsa import segmentation as sg
from mvtsa import viz
from mvtsa.datasets import make_regime_process
from mvtsa.evaluation import clustering_scores

# Six series (batches) cut from one process with three recurring regimes,
# five regime segments each.
X, cps, states = make_regime_process(
    n_regimes=3, n_segments=30, length=120, random_state=0
)
bounds = np.r_[0, cps[4::5], len(X)]
C, series = [], []
for k in range(6):
    a, b = bounds[k], bounds[k + 1]
    C.append(X[a:b])
    series.append((cps[(cps > a) & (cps < b)] - a, states[5 * k : 5 * k + 5]))

# %%
# Segment and cluster
# -------------------
sc = cl.SegmentClustering(
    segmenter=sg.BottomUp("normal", penalty=60, initial_size=20), n_clusters=3
).fit(C)
for i, seg in enumerate(sc.segmentations_):
    print(
        f"series {i}: {seg.n_segments} segments, patterns {seg.labels.tolist()}"
    )
pred = np.concatenate(
    [seg.to_labels(states=True) for seg in sc.segmentations_]
)
true = np.concatenate(
    [
        mv.Segmentation(c, len(x), labels=st).to_labels(states=True)
        for x, (c, st) in zip(C, series, strict=True)
    ]
)
print(
    "sample-level agreement with the true regimes:",
    clustering_scores(true, pred),
)
seg0 = sc.segmentations_[0]
viz.plot_segmentation(
    C[0],
    seg0,
    truth=series[0][0],
    title="series 0, segments coloured by pattern",
)
plt.show()
