"""
PCA models: T², Q and similarity factors
========================================

A PCA model fitted on normal operation describes the correlation of the
variables; the Hotelling :math:`T^2` statistic measures the variation inside
the model, the :math:`Q` statistic the distance from it. When the
correlation structure changes, :math:`Q` exceeds its control limit -- the
principle behind PCA-based segmentation and monitoring.
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import viz
from mvtsa.datasets import make_correlation_switching
from mvtsa.representation import (
    PCAModel,
    chordal_distance,
    krzanowski_similarity,
)

X, cps, _ = make_correlation_switching(
    n_segments=2, length=300, random_state=3
)

# %%
# Monitoring statistics of a reference model
# ------------------------------------------
model = PCAModel(n_components=1).fit(X[:300])  # first regime as reference
t2_lim, q_lim = model.control_limits(alpha=0.01)
q = model.q_statistic(X)
print(
    f"Q limit {q_lim:.3f}; exceedance before/after the change: "
    f"{np.mean(q[:300] > q_lim):.2f} / {np.mean(q[300:] > q_lim):.2f}"
)
viz.plot_pca_statistics(X, model)

# %%
# Comparing PCA models: Krzanowski similarity
# -------------------------------------------
m1, m2 = PCAModel(1).fit(X[:300]), PCAModel(1).fit(X[300:])
print(
    "s_PCA(regime 1, regime 1 half) =",
    round(m1.similarity(PCAModel(1).fit(X[:150])), 3),
)
print("s_PCA(regime 1, regime 2)      =", round(m1.similarity(m2), 3))
print(
    "chordal distance               =",
    round(chordal_distance(m1.components_, m2.components_), 3),
)
# %%
# Parameter study: window length and similarity
# ---------------------------------------------
# The similarity of short windows to the reference fluctuates; longer
# windows estimate the subspace better.
fig, ax = plt.subplots(figsize=(6, 3))
for w in (20, 50, 100):
    s = [
        krzanowski_similarity(
            m1.components_, PCAModel(1).fit(X[a : a + w]).components_
        )
        for a in range(0, len(X) - w, 5)
    ]
    ax.plot(np.arange(0, len(X) - w, 5) + w, s, label=f"window {w}")
ax.axvline(300, color="gray", ls=":")
ax.set_xlabel("window end")
ax.set_ylabel("Krzanowski similarity")
ax.legend(frameon=False)
plt.show()
