"""
PCA segmentation with the T² and Q statistics
=============================================

Abonyi et al. (2005) segment a multivariate series so that the PCA model of
every segment describes its samples well: the cost of a segment is the sum
of the reconstruction errors (:math:`Q`) or of the Hotelling :math:`T^2`
values of its samples. Bankó (2015, Eq. 3.1) uses the same costs with
bottom-up search for correlation-based warping. :math:`Q` reacts to changes
of the correlation structure, :math:`T^2` to changes of the variation within
the model; their sum is the full squared reconstruction distance.
"""

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

X, cps, _ = mv.datasets.make_correlation_switching(
    n_segments=5, length=120, n_variables=4, random_state=2
)

# %%
# Q, T² and their sum
# -------------------
rows = []
for stat in ("Q", "T2", "both"):
    seg = sg.PCASegmenter(
        n_segments=5, n_components=1, statistic=stat
    ).segment(X)
    rows.append(
        {
            "statistic": stat,
            **evaluate_segmentation(cps, seg, len(X), margin=6),
        }
    )
print(pd.DataFrame(rows)[["statistic", "f1", "covering", "hausdorff"]])
# %%
# The variances of the variables are the same in every segment, so the
# :math:`T^2` statistic -- the variation *inside* the model -- has nothing to
# react to; the changes live entirely in the residual space.

# %%
# The loadings of the segment models
# ----------------------------------
# The first principal direction of every segment: the correlation structure
# that defines the segments.
seg = sg.PCASegmenter(n_segments=5, n_components=1).segment(X)
mv.viz.plot_segmentation(X, seg, truth=cps)
mv.viz.plot_segment_loadings(X, seg)

# %%
# Parameter study: the number of principal components
# ---------------------------------------------------
# One latent variable generates the data. With more components the
# :math:`Q` statistic sees less and less of the structure.
for q in (1, 2, 3):
    s = sg.PCASegmenter(n_segments=5, n_components=q).segment(X)
    print(
        f"{q} components: covering {evaluate_segmentation(cps, s, len(X))['covering']:.3f}"
    )
plt.show()
