"""
Segmentation of a data stream
=============================

Three ways to segment data that arrive sample by sample: a multivariate
CUSUM chart, recursive PCA (see the latent-variable examples) and a batch
segmenter applied to a sliding buffer, which reports a change point once
it is far enough from the end of the buffer to be stable.
"""

import matplotlib.pyplot as plt

import mvtsa as mv
from mvtsa import segmentation as sg

X, cps, _ = mv.datasets.make_piecewise_stationary(
    n_segments=6, length=200, n_variables=3, random_state=2
)

# %%
# Windowed batch segmentation
# ---------------------------
stream = sg.StreamSegmenter(
    sg.PELT("l2", jump=5), window=300, step=25, guard=20
)
reported = []
for t, x in enumerate(X):
    for c in stream.partial_fit(x):
        reported.append((t, c))
for t, c in reported:
    print(f"at sample {t:5d}: change point {c} (delay {t - c})")
# %%
# Multivariate CUSUM
# ------------------
cusum = sg.CUSUMDetector(k=0.5, h=25, warmup=50)
seg = cusum.segment(X)
print("CUSUM:", seg.change_points, "| true:", cps)
fig, axes = plt.subplots(2, 1, figsize=(7, 4.5), sharex=True)
mv.viz.plot_segmentation(X, seg, truth=cps, ax=axes[0])
mv.viz.plot_profile(
    cusum.statistic_,
    seg.change_points,
    ax=axes[1],
    label="CUSUM",
    threshold=cusum.h,
)
plt.show()
