"""
Is the segmentation stable?
===========================

Without ground truth, a segmentation can still be validated: change points
that persist when the data are perturbed -- noise added, a random block
segmented -- are trustworthy; those that come and go are not. The boundary
frequency over the perturbed runs measures the support of every change
point.
"""

import matplotlib.pyplot as plt

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

X, cps, _ = mv.datasets.make_piecewise_stationary(
    n_segments=5,
    length=150,
    n_variables=3,
    change="all",
    vary=0.3,
    random_state=3,
)

# %%
# Stable and unstable settings
# ----------------------------
good = segmentation_stability(
    sg.BottomUp("normal", n_segments=5, initial_size=10),
    X,
    n_runs=20,
    random_state=0,
)
over = segmentation_stability(
    sg.BottomUp("normal", n_segments=9, initial_size=10),
    X,
    n_runs=20,
    random_state=0,
)
print(
    "5 segments: support",
    good["support"].round(2),
    "stability",
    round(good["stability"], 2),
)
print(
    "9 segments: support",
    over["support"].round(2),
    "stability",
    round(over["stability"], 2),
)
print(
    "change points with 9 segments:",
    over["reference"].change_points,
    "| true:",
    cps,
)
fig, axes = plt.subplots(2, 1, figsize=(7, 4.4), sharex=True)
mv.viz.plot_stability(good, ax=axes[0])
mv.viz.plot_stability(over, ax=axes[1])

# %%
# Parameter study: the number of segments
# ---------------------------------------
# With too few segments the boundaries wander between runs; once every true
# change is found, the support saturates. The extra change points of the
# over-segmentation are stable as well, because they sit right next to the
# true ones (one initial segment away), so stability complements the rules
# for the number of segments rather than replacing them.
for k in range(3, 10):
    r = segmentation_stability(
        sg.BottomUp("normal", n_segments=k, initial_size=10),
        X,
        n_runs=15,
        random_state=0,
    )
    print(f"{k} segments: stability {r['stability']:.2f}")
plt.show()
