"""
Costs and search strategies
===========================

Any cost can be combined with any search strategy. Here a piecewise
stationary series with changes of the mean, the variance and the
correlation is segmented with five costs and five strategies.
"""

import matplotlib.pyplot as plt
import pandas as pd

from mvtsa import segmentation as sg
from mvtsa import viz
from mvtsa.datasets import make_piecewise_stationary
from mvtsa.evaluation import evaluate_segmentation

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

# %%
# Five costs, bottom-up search
# ----------------------------
rows = []
for cost in ("l2", "normal", "linear", "kernel", "pca"):
    seg = sg.BottomUp(cost, n_segments=5, initial_size=10).segment(X)
    rows.append(
        {"cost": cost, **evaluate_segmentation(cps, seg, len(X), margin=10)}
    )
print(pd.DataFrame(rows)[["cost", "f1", "covering", "hausdorff"]])
# %%
# The Gaussian and kernel costs see every kind of change; the L2 and linear
# costs only see the changes of the mean. The PCA cost -- whose
# reconstruction error is computed around the segment mean with the
# segment's own principal subspace -- reacts to the changes of the
# correlation structure, and finds every boundary here because each of them
# changes the correlations as well.

# %%
# Five search strategies, Gaussian cost
# -------------------------------------
searches = {
    "bottom-up": sg.BottomUp("normal", n_segments=5, initial_size=10),
    "top-down": sg.TopDown("normal", n_segments=5, jump=5),
    "optimal": sg.OptimalPartition("normal", n_segments=5, jump=10),
    "PELT": sg.PELT("normal", penalty=250, jump=5, min_size=20),
    "window": sg.WindowDiscrepancy("normal", width=40, n_segments=5),
}
for name, s in searches.items():
    seg = s.segment(X)
    print(
        f"{name:10s}",
        seg.change_points,
        round(evaluate_segmentation(cps, seg, len(X), 10)["covering"], 3),
    )
viz.plot_segmentation(
    X,
    searches["PELT"].segment(X),
    truth=cps,
    title="PELT with the Gaussian cost",
)

# %%
# Parameter study: the PELT penalty
# ---------------------------------
# The BIC default (about 60 here) over-segments this series because the
# variance changes make the Gaussian likelihood very sensitive; the penalty
# path shows how the number of change points settles as the penalty grows.
path = sg.penalty_path(
    X, "normal", penalties=[10, 20, 40, 80, 160, 250, 320, 640, 1280]
)
print(path)
fig, ax = plt.subplots(figsize=(5, 3))
ax.semilogx(list(path), list(path.values()), "o-")
ax.set_xlabel("penalty")
ax.set_ylabel("number of change points")
plt.show()
