"""
Consensus of segmentations
==========================

Different segmenters make different mistakes. The boundary agreement --
the kernel-smoothed fraction of members that place a change point near
every sample -- shows where they agree, and its peaks above one half form
a consensus segmentation.
"""

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=5,
    length=150,
    n_variables=3,
    change="all",
    vary=0.3,
    random_state=21,
)

# %%
# Members and consensus
# ---------------------
members = [
    sg.BottomUp("normal", n_segments=5, initial_size=10),
    sg.PELT("normal", penalty=200, jump=5, min_size=20),
    sg.TopDown("kernel", n_segments=5, jump=5),
    sg.BOCPD(hazard=150),
    sg.WindowDiscrepancy("normal", width=40, n_segments=5),
]
cons = sg.ConsensusSegmenter(members, threshold=0.5)
seg = cons.segment(X)
for m, s in zip(
    ["bottom-up", "PELT", "top-down", "BOCPD", "window"],
    cons.members_,
    strict=True,
):
    print(f"{m:9s} {s.change_points}")
print("consensus", seg.change_points, "| true", cps)
print(evaluate_segmentation(cps, seg, len(X), margin=10)["f1"])
mv.viz.plot_boundary_agreement(
    cons.agreement_,
    members=cons.members_,
    consensus=seg,
    names=["bottom-up", "PELT", "top-down", "BOCPD", "window"],
)
plt.show()
