"""
Recurring operating states
==========================

Segments of a process often return to a few recurring states. Three ways
to find them: a sticky Gaussian hidden Markov model, segmentation followed
by clustering of the segments (with the 2-Wasserstein distance of their
Gaussian descriptions), and a TICC-style model that assigns windows to
sparse Gaussian graphical models with a switching penalty (Hallac et al.,
2017).
"""

import matplotlib.pyplot as plt
import pandas as pd

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

R, cps, states = mv.datasets.make_regime_process(
    n_regimes=3, n_segments=8, length=150, random_state=1
)

# %%
# Three state detectors
# ---------------------
models = {
    "sticky HMM": sg.GaussianHMMSegmenter(
        n_states=3, sticky=10, min_duration=10
    ),
    "segment + cluster": sg.StateSegmenter(n_states=3),
    "sparse Gaussian": sg.SparseGaussianStateSegmenter(
        n_states=3, window=2, beta=40
    ),
}
rows = []
for name, m in models.items():
    s = m.segment(R)
    rows.append(
        {
            "method": name,
            **evaluate_segmentation(
                cps, s, len(R), margin=10, true_states=states
            ),
        }
    )
print(pd.DataFrame(rows)[["method", "f1", "covering", "state_ari"]].round(3))
seg = models["segment + cluster"].segmentation_
fig, axes = plt.subplots(
    2, 1, figsize=(7, 4.2), sharex=True, gridspec_kw={"height_ratios": [3, 1]}
)
mv.viz.plot_segmentation(R, seg, truth=cps, ax=axes[0])
mv.viz.plot_states(seg, ax=axes[1])

# %%
# How many states? BIC of the HMM
# -------------------------------
h = sg.GaussianHMMSegmenter(n_states="bic", max_states=6, sticky=10).fit(R)
print(
    "BIC:", {k: round(v) for k, v in h.bic_.items()}, "-> states:", h.n_states_
)
small = min(range(h.n_states_), key=lambda k: (h.states_ == k).sum())
print(
    "samples of the smallest state:", (h.states_ == small).sum(), "around", cps
)
# %%
# BIC asks for a fourth state: it collects the few samples of the smooth
# transitions between the regimes, which none of the three Gaussian regime
# models explains. Information criteria count such systematic deviations as
# structure; with ``min_duration`` the short visits are absorbed again.
plt.show()
