"""
First steps: segment, look, evaluate
====================================

A multivariate series of three variables whose correlation structure
switches three times -- the means and variances stay the same, so no
variable shows the changes on its own. A PCA-based bottom-up segmentation
(Abonyi et al., 2005) finds them, and the result is compared with the truth.
"""

# %%
# Data and segmentation
# ---------------------
import matplotlib.pyplot as plt

import mvtsa as mv
from mvtsa.evaluation import evaluate_segmentation
X, true_cps, states = mv.datasets.make_correlation_switching(
    n_segments=4, length=150, random_state=0
)
seg = mv.segment(
    X, "pca", n_segments=4, n_components=1
)  # Q-statistic cost, bottom-up search
print(seg)
print(evaluate_segmentation(true_cps, seg, len(X), margin=5))
# %%
# The segmented series
# --------------------
# Segments are shaded, detected change points are blue lines, the true ones
# orange marks at the top.
mv.viz.plot_segmentation(X, seg, truth=true_cps, names=["x1", "x2", "x3"])

# %%
# The same series segmented by the means only
# -------------------------------------------
# A piecewise-constant (L2) cost cannot see correlation changes.
seg_l2 = mv.segment(X, "bottomup", cost="l2", n_segments=4)
print(
    "L2 change points:",
    seg_l2.change_points,
    " PCA change points:",
    seg.change_points,
)
mv.viz.plot_segmentation(X, seg_l2, truth=true_cps, names=["x1", "x2", "x3"])
plt.show()
