"""
Six-sigma visibility graphs
===========================

A visibility graph turns a series into a network: two samples are linked
if the straight line between them passes above all samples in between
(Lacasa et al., 2008); in the horizontal version the line must be
horizontal (Luque et al., 2009). Labelling the nodes with the zones of a
Shewhart control chart -- C within one sigma, B within two, A within three
-- and the Western Electric rule violations gives a network view of process
capability: the zone-transition statistics of the edges change when the
process drifts.
"""

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

from mvtsa import representation as rp
from mvtsa import viz

rng = np.random.default_rng(1)
in_control = rng.normal(0, 1, 120)
drifting = rng.normal(0, 1, 120) + np.linspace(0, 2.5, 120)

# %%
# The graph of an in-control and a drifting process
# -------------------------------------------------
G_ok = rp.six_sigma_visibility_graph(in_control, center=0, sigma=1)
G_drift = rp.six_sigma_visibility_graph(drifting, center=0, sigma=1)
rows = []
for name, G in [("in control", G_ok), ("drifting", G_drift)]:
    f = rp.graph_features(G)
    rules = {
        k: sum(G.nodes[i][k] for i in G.nodes)
        for k in ("rule1", "rule2", "rule3", "rule4")
    }
    rows.append(
        {
            "process": name,
            **{
                k: f[k]
                for k in ("mean_degree", "degree_entropy", "clustering")
            },
            **rules,
        }
    )
print(pd.DataFrame(rows).round(3).to_string(index=False))
# %%
# The global graph features hardly change -- the mean degree of a horizontal
# visibility graph of an uncorrelated series is close to four whatever the
# distribution (Luque et al., 2009) -- but the zone labels and the rule
# flags reveal the drift at once.
fig, axes = plt.subplots(2, 1, figsize=(7, 5), sharex=True)
viz.plot_visibility_graph(in_control, G_ok, ax=axes[0])
viz.plot_visibility_graph(drifting, G_drift, ax=axes[1])
axes[0].set_title("in control", fontsize=9, loc="left")
axes[1].set_title("drifting", fontsize=9, loc="left")

# %%
# Zone transitions
# ----------------
for name, G in [("in control", G_ok), ("drifting", G_drift)]:
    zs = (
        pd.Series([G.edges[e]["zones"] for e in G.edges])
        .value_counts(normalize=True)
        .round(3)
    )
    print(name, dict(zs.head(5)))
plt.show()
