"""
Experiment tracking and model cards
===================================

Comparing settings is an experiment, and experiments should leave a trace.
The :class:`~mvtsa.mlops.ExperimentTracker` logs parameters, metrics,
figures and models of every run to a local folder (and to MLflow when it
is installed and requested). A model card documents what a model is for,
how it was evaluated and where its limits are (Mitchell et al., 2019).
"""

import tempfile
from pathlib import Path

import matplotlib.pyplot as plt

import mvtsa as mv
from mvtsa import mlops
from mvtsa import segmentation as sg
from mvtsa.evaluation import evaluate_segmentation

X, cps, _ = mv.datasets.make_correlation_switching(
    n_segments=5, length=150, n_variables=4, random_state=7
)
workdir = Path(tempfile.mkdtemp())

# %%
# Tracked runs
# ------------
tracker = mlops.ExperimentTracker(
    workdir / "runs", experiment="pca-segmentation", use_mlflow=False
)
for q in (1, 2, 3):
    with tracker.start_run(f"q={q}") as run:
        model = sg.PCASegmenter(n_segments=5, n_components=q)
        seg = model.segment(X)
        run.log_params(mlops.to_config(model)["params"])
        run.log_metrics(
            {
                k: v
                for k, v in evaluate_segmentation(
                    cps, seg, len(X), margin=8
                ).items()
                if k in ("f1", "covering", "hausdorff")
            }
        )
        fig = mv.viz.plot_segmentation(X, seg, truth=cps).figure
        run.log_figure(fig, "segmentation.png")
        plt.close(fig)
runs = tracker.runs()
print(runs[["name", "param.n_components", "metric.f1", "metric.covering"]])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.bar(runs["name"], runs["metric.covering"], color="#285780")
ax.set_ylabel("covering")
ax.set_ylim(0, 1.05)
ax.set_title("tracked runs", fontsize=9, loc="left")

# %%
# A model card
# ------------
card = mlops.model_card(
    sg.PCASegmenter(n_segments=5, n_components=1),
    name="PCA segmentation of unit 7",
    purpose="Detect changes of the correlation structure of four process variables.",
    data_description="Synthetic data with four correlation switches.",
    metrics={"f1": 1.0, "covering": 1.0},
    limitations="Blind to pure mean shifts; assumes one latent variable.",
    path=workdir / "MODEL_CARD.md",
)
print(card)
plt.show()
