"""
Bayesian on-line change point detection
=======================================

Adams and MacKay (2007) maintain the posterior distribution of the *run
length* -- the time since the last change -- and update it with every new
sample using the predictive distribution of a conjugate model. Here a
Normal--inverse-Wishart model detects changes of the mean and the
covariance of a three-variable series.
"""

import matplotlib.pyplot as plt

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

X, cps, _ = mv.datasets.make_piecewise_stationary(
    n_segments=6,
    length=120,
    n_variables=3,
    change="all",
    vary=0.3,
    random_state=8,
)

# %%
# Run-length posterior and change probability
# -------------------------------------------
bo = sg.BOCPD(hazard=150, model="full")
seg = bo.segment(X)
print("detected:", seg.change_points, "\ntrue:    ", cps)
print(evaluate_segmentation(cps, seg, len(X), margin=10)["f1"])
fig, axes = plt.subplots(3, 1, figsize=(7, 6), sharex=True)
mv.viz.plot_segmentation(X, seg, truth=cps, ax=axes[0])
mv.viz.plot_run_length(bo, ax=axes[1])
mv.viz.plot_profile(
    bo.change_probability_,
    seg.change_points,
    ax=axes[2],
    label="P(change)",
    threshold=bo.threshold,
)

# %%
# Parameter study: the hazard
# ---------------------------
# The hazard is the prior expected segment length. The detector is robust
# to it over an order of magnitude.
for h in (30, 100, 300, 1000):
    s = sg.BOCPD(hazard=h).segment(X)
    print(
        f"hazard {h:5d}: {len(s.change_points)} change points, "
        f"F1 {evaluate_segmentation(cps, s, len(X), 10)['f1']:.2f}"
    )
plt.show()
