"""
Benchmarking segmenters with statistical tests
==============================================

A fair comparison runs every method on many data sets and tests whether
the differences are significant. The Friedman test checks whether the
average ranks differ at all; the Nemenyi critical difference (Demšar, 2006)
tells which pairs differ. Here ten synthetic series with changes of the
mean, the variance and the correlation are segmented by eight methods.
"""

import matplotlib.pyplot as plt

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import Benchmark, friedman_nemenyi, wilcoxon_holm

datasets = {
    f"series {i}": mv.datasets.make_piecewise_stationary(
        n_segments=5,
        length=120,
        n_variables=3,
        change="all",
        vary=0.3,
        random_state=i,
    )[:2]
    for i in range(10)
}

# %%
# Run the benchmark
# -----------------
methods = {
    "BU-L2": lambda: sg.BottomUp("l2", n_segments=5, initial_size=10),
    "BU-Gauss": lambda: sg.BottomUp("normal", n_segments=5, initial_size=10),
    "BU-kernel": lambda: sg.BottomUp("kernel", n_segments=5, initial_size=10),
    "TD-Gauss": lambda: sg.TopDown("normal", n_segments=5, jump=5),
    "Opt-Gauss": lambda: sg.OptimalPartition("normal", n_segments=5, jump=10),
    "Window": lambda: sg.WindowDiscrepancy("normal", width=30, n_segments=5),
    "BOCPD": lambda: sg.BOCPD(hazard=120),
    "PCA-Q": lambda: sg.PCASegmenter(n_segments=5, n_components=1),
}
bench = Benchmark(methods, datasets)
res = bench.run()
print(
    res.groupby("method")[["f1", "covering", "time"]]
    .mean()
    .sort_values("covering", ascending=False)
    .round(3)
)
# %%
# Friedman test and critical difference diagram
# ---------------------------------------------
stat = friedman_nemenyi(bench.pivot("covering"))
print(
    f"Friedman p = {stat['p_value']:.2g}, CD = {stat['critical_difference']:.2f}"
)
print(
    wilcoxon_holm(bench.pivot("covering"))
    .head(5)
    .round(4)
    .to_string(index=False)
)
mv.viz.plot_critical_difference(
    stat["ranks"], stat["critical_difference"], title="covering, 10 series"
)
plt.show()
