"""
Robustness of input and output configurations
=============================================

A configuration is robust if the system stays structurally controllable (observable)
when a state variable fails. :func:`nocad.node_removal_robustness` removes every state
in turn, with its edges and its input or output, and tests Lin's conditions on what is
left; the states whose loss destroys controllability are the *critical nodes*. Minimal
designs are fragile; additional drivers buy robustness.
"""

# %%
# The NOCAD example
# -----------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import load_nocad_example, make_hen_case_study
from nocad.plotting import default_layout
from nocad.viz import plot_robustness_map

adj = load_nocad_example().adj
pos = default_layout(adj)
# [snippet:robust]
for drivers in ([7], [3, 7]):
    r = nocad.node_removal_robustness(adj, drivers=drivers)
    print(f"drivers {np.add(drivers, 1)}: robustness {r.control_robustness:.3f}, critical {r.control_critical + 1}")
# [/snippet:robust]
fig, axes = plt.subplots(1, 2, figsize=(10.0, 3.8))
for ax, drivers in zip(axes, ([7], [3, 7]), strict=True):
    r = nocad.node_removal_robustness(adj, drivers=drivers)
    plot_robustness_map(adj, r, pos=pos, ax=ax, drivers=drivers, legend=ax is axes[1],
                        title=f"drivers {', '.join(f'x{d + 1}' for d in drivers)}: "
                              f"{r.control_robustness:.0%} of the removals tolerated")
fig.tight_layout()

# %%
# Parameter study: more drivers, more robustness
# ----------------------------------------------
# Drivers added to the heat exchanger network by GDFCMSA reduce the relative order;
# the share of tolerated node removals grows with them.
hen = make_hen_case_study()
ks = range(0, 9)
rob, order = [], []
for k in ks:
    if k == 0:
        nodes = nocad.driver_nodes(hen.adj)
    else:
        nodes = nocad.placement.Placement(kind="drivers", method="gdfcmsa", n_add=k, n_iter=250, n_runs=3,
                                          random_state=0).fit(hen.adj).nodes_
    rob.append(nocad.node_removal_robustness(hen.adj, drivers=nodes).control_robustness)
    order.append(nocad.control_depth(hen.adj, nodes).max())
fig, ax = plt.subplots(figsize=(5.2, 3.4))
ax.plot(list(ks), rob, marker="o", color=nocad.plotting.PALETTE[2], label="robustness")
ax.set_xlabel("additional drivers $K^+$")
ax.set_ylabel("tolerated node removals", color=nocad.plotting.PALETTE[2])
ax2 = ax.twinx()
ax2.plot(list(ks), order, marker="s", color=nocad.plotting.PALETTE[0], label="max control depth")
ax2.set_ylabel("maximal control depth", color=nocad.plotting.PALETTE[0])
ax.set_title("heat exchanger network: robustness and depth", fontsize=10)
ax.grid(True, color="0.9")
fig.tight_layout()

# %%
# **Take-away.** A minimal design depends on every link of its stems; extra drivers
# placed for a small relative order also make the configuration tolerate failures.
