"""
How many segments?
==================

Five rules for the number of segments on one series: the knee of the cost
curve, the relative reduction rate, BIC, a permutation test (after Vasko
and Toivonen, 2002) and the persistence of the change points.
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import segmentation as sg
from mvtsa.datasets import make_piecewise_stationary

X, cps, _ = make_piecewise_stationary(
    n_segments=6, length=100, n_variables=2, random_state=11
)

# %%
# The rules
# ---------
for method, kw in [
    ("knee", {}),
    ("rr", {"rr_threshold": 0.05}),
    ("bic", {}),
    ("persistence", {}),
    ("permutation", {"n_permutations": 19, "random_state": 0}),
]:
    n, info = sg.select_n_segments(
        X, "l2", method, max_segments=12, initial_size=5, **kw
    )
    print(f"{method:12s} -> {n} segments")
print("true number of segments:", len(cps) + 1)
# %%
# BIC as a function of the number of segments
# -------------------------------------------
n, info = sg.select_n_segments(X, "l2", "bic", max_segments=12, initial_size=5)
fig, ax = plt.subplots(figsize=(5, 3))
ks = sorted(info["bic"])
ax.plot(ks, [info["bic"][k] for k in ks], "o-")
ax.axvline(n, color="gray", ls=":")
ax.set_xlabel("number of segments")
ax.set_ylabel("BIC")
print(
    "BIC minimum at",
    n,
    "segments; min BIC",
    round(np.min(list(info["bic"].values())), 1),
)
plt.show()
