"""
Measuring segmentation quality
==============================

No single number describes how good a segmentation is. The F1 score of the
change points within a margin counts detections; the covering (Arbelaez et
al., 2011) measures how well the segments overlap; the Hausdorff distance
gives the worst boundary error; the annotation error compares the numbers
of change points. The example shows how the metrics react to typical
mistakes.
"""

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from mvtsa.evaluation import evaluate_segmentation

T = 1000
truth = np.array([200, 400, 600, 800])
cases = {
    "perfect": truth,
    "shifted by 15": truth + 15,
    "one missed": truth[[0, 1, 3]],
    "one extra": np.sort(np.r_[truth, 500]),
    "many extra": np.arange(50, 1000, 50),
    "nothing": np.array([], int),
}

# %%
# Metrics for typical mistakes
# ----------------------------
rows = [
    {"case": k, **evaluate_segmentation(truth, v, T, margin=10)}
    for k, v in cases.items()
]
table = pd.DataFrame(rows)[
    [
        "case",
        "precision",
        "recall",
        "f1",
        "covering",
        "hausdorff",
        "annotation_error",
    ]
]
print(table.round(3).to_string(index=False))
# %%
# Parameter study: the margin of the F1 score
# -------------------------------------------
fig, ax = plt.subplots(figsize=(5, 3))
margins = np.arange(0, 41, 2)
ax.plot(
    margins,
    [
        evaluate_segmentation(truth, truth + 15, T, margin=m)["f1"]
        for m in margins
    ],
    "o-",
    color="#285780",
    ms=3,
)
ax.set_xlabel("margin (samples)")
ax.set_ylabel("F1, change points shifted by 15")
plt.show()
