"""
Operating ranges of an energy indicator
=======================================

Abonyi, Kulcsár, Balaton and Nagy (2013) segment energy monitoring
data so that within every segment the key energy indicator depends linearly
on the operating variables. The cost of a segment is the residual of a
regression of the target column on the others (:class:`~mvtsa.segmentation.CostRegression`);
a change of the coefficients -- a different operating regime -- is a
change point even when every variable moves smoothly.
"""

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

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

X, cps, _ = mv.datasets.make_energy_process(
    n_segments=4, length=250, random_state=0
)

# %%
# Regression cost versus a mean/covariance cost
# ---------------------------------------------
reg = sg.BottomUp(
    sg.CostRegression(targets=[0]), n_segments=4, initial_size=20
).segment(X)
gauss = sg.BottomUp("normal", n_segments=4, initial_size=20).segment(X)
print(
    pd.DataFrame(
        [
            {"cost": n, **evaluate_segmentation(cps, s, len(X), margin=25)}
            for n, s in [("regression", reg), ("Gaussian", gauss)]
        ]
    )[["cost", "f1", "covering"]]
)
mv.viz.plot_segmentation(
    X, reg, truth=cps, names=["energy indicator", "load", "feed temperature"]
)

# %%
# The local models
# ----------------
for a, b in reg.segments:
    A = np.c_[np.ones(b - a), X[a:b, 1:]]
    coef = np.linalg.lstsq(A, X[a:b, 0], rcond=None)[0]
    print(
        f"[{a:4d},{b:4d})  KEI = {coef[0]:6.2f} {coef[1]:+.3f}*load {coef[2]:+.3f}*feed"
    )
plt.show()
