"""
Tuning segmenter parameters
===========================

Parameters can be tuned against labelled series by grid search on a
segmentation metric, or without labels by maximizing stability. The
sensitivity analysis of a single parameter shows how robust the method is.
"""

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,
    grid_search_segmenter,
    sensitivity,
)

train = [
    mv.datasets.make_correlation_switching(
        n_segments=4, length=150, n_variables=4, random_state=s
    )[:2]
    for s in range(4)
]

# %%
# Supervised grid search
# ----------------------
best, table = grid_search_segmenter(
    lambda **p: sg.PCASegmenter(n_segments=4, **p),
    {
        "n_components": [1, 2, 3],
        "statistic": ["Q", "T2", "both"],
        "initial_size": [5, 10, 20],
    },
    train,
    criterion="covering",
)
print("best:", best)
print(table.head(6).round(3).to_string(index=False))
# %%
# Sensitivity of BOCPD to the hazard
# ----------------------------------
X, cps = train[0]
res = sensitivity(
    lambda hazard: sg.BOCPD(hazard=hazard, model="full"),
    "hazard",
    [20, 50, 100, 200, 500, 1000],
    X,
    score=lambda s: evaluate_segmentation(cps, s, len(X), margin=10)["f1"],
)
for r in res:
    print(
        f"hazard {r['hazard']:5d}: {r['n_segments']} segments, F1 {r['score']:.2f}"
    )
fig, ax = plt.subplots(figsize=(5, 3))
ax.semilogx(
    [r["hazard"] for r in res],
    [r["score"] for r in res],
    "o-",
    color="#285780",
)
ax.set_xlabel("hazard")
ax.set_ylabel("F1")
ax.set_ylim(0, 1.05)
print("mean time per run (s):", np.mean([r["time"] for r in res]).round(3))
plt.show()
