"""
On-line segmentation with recursive PCA
=======================================

Dobos and Abonyi (2012) segment process data *on line*: a recursive PCA
model is updated at every sample with a variable forgetting factor, and the
Krzanowski similarity between the running model and the model of the
current segment signals a change. Because the recursive model needs some
samples to follow a change, the detection comes with a delay; a
retrospective search over the samples of the closing segment localizes the
change exactly.
"""

import matplotlib.pyplot as plt
import numpy as np

import mvtsa as mv
from mvtsa import segmentation as sg

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

# %%
# Batch use
# ---------
rp = sg.RecursivePCASegmenter(
    threshold=0.7, n_components=1, forgetting=0.97, warmup=60, patience=8
)
seg = rp.segment(X)
print("detected:", seg.change_points, " true:", cps)
fig, axes = plt.subplots(3, 1, figsize=(7, 5.5), sharex=True)
mv.viz.plot_segmentation(X, seg, truth=cps, ax=axes[0])
axes[1].plot(rp.similarity_, color="#285780", lw=1)
axes[1].axhline(rp.threshold, color="#D55E00", ls="--", lw=1)
axes[1].set_ylabel("similarity")
axes[2].plot(rp.forgetting_, color="#009E73", lw=1)
axes[2].set_ylabel("forgetting")
axes[2].set_xlabel("sample")
for ax in axes[1:]:
    for c in cps:
        ax.axvline(c, color="gray", ls=":", lw=0.8)

# %%
# Stream use
# ----------
# :meth:`partial_fit` processes one sample at a time and returns ``True`` when
# a change point has been declared. The scaling must be fixed in advance.
stream = sg.RecursivePCASegmenter(
    threshold=0.7,
    n_components=1,
    forgetting=0.97,
    warmup=60,
    patience=8,
    scale=(X[:200].mean(0), X[:200].std(0)),
)
for t, x in enumerate(X):
    if stream.partial_fit(x):
        print(f"sample {t}: change declared at {stream.change_points_[-1]}")
# %%
# Parameter study: forgetting factor and detection delay
# ------------------------------------------------------
# Without the retrospective localization, the reported change point is the
# moment of detection; a smaller forgetting factor follows changes faster
# but makes the similarity noisier.
for lam in (0.95, 0.97, 0.99):
    s = sg.RecursivePCASegmenter(
        threshold=0.7,
        n_components=1,
        forgetting=lam,
        warmup=60,
        patience=8,
        refine=False,
    ).segment(X)
    d = [
        int(np.min(np.abs(s.change_points - c)))
        if len(s.change_points)
        else -1
        for c in cps
    ]
    print(f"forgetting {lam}: detections {s.change_points}, delays {d}")
plt.show()
