"""
Dynamic PCA segmentation
========================

When the segments differ in their *dynamics* -- here a second-order
system whose parameters change while the static gain is kept -- a static
PCA model sees nothing. Dynamic PCA (Ku et al., 1995) augments every sample
with its lagged values, so that the principal subspace of the lag matrix
encodes the input--output dynamics; segmenting with it (Dobos and Abonyi,
2012; Bankó, 2015) recovers the changes. The number of lags can be chosen
from the eigenvalues of the covariance of the lag matrix: a lag that
completes a dynamic relation makes the smallest eigenvalue drop by orders
of magnitude.
"""

import matplotlib.pyplot as plt
import numpy as np

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import evaluate_segmentation
from mvtsa.representation import select_dpca_lag

Y, cps, _ = mv.datasets.make_dynamic_switching(
    order=2, n_segments=3, length=300, random_state=1
)

# %%
# Static versus dynamic PCA
# -------------------------
static = sg.PCASegmenter(n_segments=3, n_components=1).segment(Y)
dynamic = sg.DPCASegmenter(n_segments=3, lags=2, n_components=5).segment(Y)
for name, s in [("PCA", static), ("DPCA", dynamic)]:
    print(
        f"{name:5s}",
        s.change_points,
        evaluate_segmentation(cps, s, len(Y), margin=15)["f1"],
    )
mv.viz.plot_segmentation(
    Y, dynamic, truth=cps, names=["u", "y"], title="Dynamic PCA, two lags"
)

# %%
# Choosing the number of lags
# ---------------------------
Y1, _, _ = mv.datasets.make_dynamic_switching(
    order=1, n_segments=3, length=300, random_state=0
)
print("selected lag, first-order system: ", select_dpca_lag(Y1))
print("selected lag, second-order system:", select_dpca_lag(Y))
print(
    "Ku et al. (1995) count of relations:",
    select_dpca_lag(Y1, method="ku"),
    select_dpca_lag(Y, method="ku"),
)
# %%
# The pH neutralization process
# -----------------------------
# The titration curve makes the process gain change by orders of magnitude,
# so the local linear dynamics differ between operating ranges.
P = mv.datasets.simulate_ph_cstr(T=720, random_state=0)
seg_ph = sg.DPCASegmenter(n_segments=6, lags=2, n_components=0.99).segment(P)
print(
    "pH change points:", seg_ph.change_points, "| input steps every 60 samples"
)
mv.viz.plot_segmentation(P, seg_ph, names=["base flow", "pH"])

# %%
# Parameter study: lags
# ---------------------
f1 = [
    evaluate_segmentation(
        cps,
        sg.DPCASegmenter(3, lags=L, n_components=0.99).segment(Y),
        len(Y),
        15,
    )["f1"]
    for L in range(0, 5)
]
fig, ax = plt.subplots(figsize=(4.5, 2.8))
ax.bar(np.arange(5), f1, color="#285780")
ax.set_xlabel("number of lags")
ax.set_ylabel("F1 (margin 15)")
plt.show()
