"""
Set covering and centrality-based placement
===========================================

Three structural heuristics add driver or sensor nodes until every state is within a
required distance :math:`r_{\\max}`: *grassroot* set covering covers the network with
the :math:`r_{\\max}`-step reach of the selected nodes, *retrofit* set covering keeps the
nodes of the matching-based design and covers the rest, and the *centrality-based
retrofit* adds, in every region that violates the bound, the node with the largest
product of betweenness and closeness. Grassroot set covering may lose
controllability, because it ignores the matching.
"""

# %%
# Three heuristics on the heat exchanger network
# ----------------------------------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import make_hen_case_study
from nocad.placement import Placement
from nocad.plotting import default_layout
from nocad.viz import plot_depth_map

hen = make_hen_case_study()
pos = default_layout(hen.adj)
# [snippet:heuristics]
results = {}
for method in ("set_cover", "retrofit", "centrality"):
    p = Placement(kind="sensors", method=method, r_max=2).fit(hen.adj)
    results[method] = p
    print(f"{method:10s} sensors={len(p.nodes_):2d} added={p.n_added_:2d} max={p.max_order_:.0f} "
          f"mean={p.mean_order_:.2f} cost={p.cost_:.3f}")
# [/snippet:heuristics]
fig, axes = plt.subplots(1, 3, figsize=(13.0, 3.9))
for ax, (name, p) in zip(axes, results.items(), strict=True):
    plot_depth_map(hen.adj, p.nodes_, "observation", pos=pos, ax=ax, labels=hen.labels, node_size=210,
                   title=f"{name.replace('_', ' ')}: {len(p.nodes_)} sensors")
fig.tight_layout()

# %%
# Parameter study: the bound r_max
# --------------------------------
# The number of sensors each heuristic needs for bounds from 0 (every state measured)
# to 6; a hollow marker would show a configuration that is not observable. On this
# network every configuration stays observable.
bounds = range(0, 7)
fig, ax = plt.subplots(figsize=(5.2, 3.4))
for k, method in enumerate(("set_cover", "retrofit", "centrality")):
    counts, ok = [], []
    for r in bounds:
        p = Placement(kind="sensors", method=method, r_max=r).fit(hen.adj)
        counts.append(len(p.nodes_))
        C = np.zeros((len(p.nodes_), 22))
        C[range(len(p.nodes_)), p.nodes_] = 1
        ok.append(nocad.is_observable(nocad.adjacency_to_state_matrix(hen.adj), C))
    col = nocad.plotting.PALETTE[k]
    ax.plot(list(bounds), counts, color=col, lw=1.4, label=method.replace("_", " "))
    for r, c, o in zip(bounds, counts, ok, strict=True):
        ax.scatter(r, c, s=26, color=col if o else "white", edgecolors=col, zorder=3)
ax.set_xlabel(r"required relative order $r_{\max}$")
ax.set_ylabel("number of sensors")
ax.set_title("sensors needed by the heuristics (HEN)", fontsize=10)
ax.grid(True, color="0.9")
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Grassroot set covering ignores the matching
# -------------------------------------------
# A star :math:`x_1\to\{x_2,x_3,x_4\}` shows what can go wrong: one driver at
# :math:`x_1` reaches every state in one step, but two of the leaves stay unmatched,
# so set covering returns an uncontrollable configuration, retrofit a controllable one.
star = np.zeros((4, 4))
star[0, 1:] = 1
for method in ("set_cover", "retrofit"):
    p = Placement(kind="drivers", method=method, r_max=1).fit(star)
    B = np.zeros((4, len(p.nodes_)))
    B[p.nodes_, range(len(p.nodes_))] = 1
    print(f"{method:10s} drivers {[f'x{v + 1}' for v in p.nodes_]} controllable: {nocad.is_controllable(star.T, B)}")

# %%
# **Take-away.** Set covering is the natural formulation of the bound on the relative
# order; keeping the matching-based nodes (retrofit) guarantees observability at the
# price of a few more sensors.
