"""
The merge hierarchy: segmentogram and persistence
=================================================

Bottom-up segmentation produces a whole hierarchy of segmentations in one
run. The *segmentogram* shows every level; change points that survive many
merges are the important ones. The cost curve and its relative reduction
rate (Bankó, 2015) tell where adding segments stops paying off.
"""

import matplotlib.pyplot as plt

from mvtsa import segmentation as sg
from mvtsa import viz
from mvtsa.datasets import make_correlation_switching

X, cps, _ = make_correlation_switching(
    n_segments=5, length=120, random_state=7
)

# %%
# One run, all levels
# -------------------
bu = sg.BottomUp("pca", initial_size=10, cost_params={"n_components": 1})
tree = bu.full_tree(X)
print("levels:", tree.n_levels, "| 5 segments:", tree.cut(5), "| true:", cps)
pers = tree.persistence()
print(
    "most persistent change points:",
    sorted(pers, key=pers.get, reverse=True)[:4],
)
viz.plot_segmentogram(tree, max_segments=12)

# %%
# Cost curve and relative reduction rate
# --------------------------------------
curve = {c: v for c, v in tree.cost_curve().items() if c <= 12}
rr = sg.relative_reduction(curve)
print({c: round(v, 3) for c, v in rr.items()})
viz.plot_cost_curve(curve, selected=5)
plt.show()
