"""
Monitoring a deployed model for drift
=====================================

A model learned on reference data is only valid while the process behaves
like the reference. The :class:`~mvtsa.mlops.DriftMonitor` checks every new
batch: the exceedance rates of the :math:`T^2` and :math:`Q` limits of the
reference PCA model, the Krzanowski similarity of the batch model, the
distribution shift of every variable (Kolmogorov--Smirnov, population
stability index) and, optionally, the distribution of segment durations. A
data contract catches schema and range violations before any of this.
"""

import matplotlib.pyplot as plt
import numpy as np

import mvtsa as mv
from mvtsa import mlops

X, cps, _ = mv.datasets.make_correlation_switching(
    n_segments=3, length=400, n_variables=4, random_state=1
)
reference = X[:300]

# %%
# Data contract
# -------------
contract = mlops.DataContract.infer(reference, names=["a", "b", "c", "d"])
bad = X[300:350].copy()
bad[5, 2] = np.nan
print(contract.check(bad, names=["a", "b", "c", "d"]))
# %%
# Batch-wise drift monitoring
# ---------------------------
mon = mlops.DriftMonitor(n_components=1, similarity_threshold=0.8).fit(
    reference
)
for a in range(300, len(X), 100):
    r = mon.update(X[a : a + 100])
    print(
        f"batch {a:4d}-{a + 100:4d}: Q exceed {r['q_exceedance']:.2f}  "
        f"similarity {r['similarity']:.2f}  "
        f"alerts {r['alerts']}"
    )
rep = mon.report()
fig, ax = plt.subplots(figsize=(6, 3))
start = np.arange(300, len(X), 100)
ax.plot(
    start,
    rep["similarity"],
    "o-",
    color="#285780",
    label="Krzanowski similarity",
)
ax.plot(
    start,
    rep["q_exceedance"],
    "s-",
    color="#D55E00",
    label="Q exceedance rate",
)
ax.axhline(0.8, color="#285780", ls=":", lw=1)
for c in cps:
    ax.axvline(c, color="gray", ls="--", lw=0.8)
ax.set_xlabel("batch start")
ax.legend(frameon=False)
plt.show()
