"""
Comparing the five placement methods
====================================

:func:`nocad.placement.improve_configuration` runs the five methods of the third NOCAD
module for drivers and sensors with the same bound and reports the size, the cost, the
maximal and mean relative order and the structural controllability (observability) of
every configuration; :func:`nocad.robustness_table` adds the share of single-node
failures each one tolerates (MATLAB ``extendData`` and ``robust``).
"""

# %%
# The NOCAD example with bound 2
# ------------------------------
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

import nocad
from nocad.datasets import load_nocad_example, make_hen_case_study
from nocad.placement import improve_configuration

pd.set_option("display.width", 140)
adj = load_nocad_example().adj
# [snippet:compare]
table = improve_configuration(adj, r_max=2, beta=0.5, n_iter=300, n_runs=5, random_state=0)
shown = table.assign(nodes=table.nodes.apply(lambda v: " ".join(f"x{i + 1}" for i in v)))
print(shown[["kind", "method", "nodes", "cost", "max_order", "mean_order", "structural"]].round(4).to_string(index=False))
configs = {m: (table.query("kind == 'drivers' and method == @m").nodes.iloc[0],
               table.query("kind == 'sensors' and method == @m").nodes.iloc[0]) for m in table.method.unique()}
labels = [f"x{i + 1}" for i in range(9)]
print(nocad.robustness_table(adj, configs, labels=labels).round(3).to_string(index=False))
# [/snippet:compare]

# %%
# Parameter study: the heat exchanger network
# -------------------------------------------
hen = make_hen_case_study()
fig, axes = plt.subplots(1, 2, figsize=(9.6, 3.4), sharey=True)
for ax, r in zip(axes, (1, 3), strict=True):
    t = improve_configuration(hen.adj, r_max=r, n_iter=300, n_runs=4, random_state=0)
    for k, kind in enumerate(("drivers", "sensors")):
        sub = t[t.kind == kind]
        x = np.arange(len(sub))
        ax.bar(x + (k - 0.5) * 0.38, sub.n_nodes, width=0.38, color=nocad.plotting.PALETTE[k], label=kind)
        for xi, (n, ok) in enumerate(zip(sub.n_nodes, sub.structural, strict=True)):
            if not ok:
                ax.text(xi + (k - 0.5) * 0.38, n + 0.2, "×", ha="center", fontsize=9, color="0.2")
    ax.set_xticks(np.arange(len(sub)))
    ax.set_xticklabels([m.replace("_", "\n") for m in sub.method], fontsize=8)
    ax.set_title(f"HEN, bound r_max = {r} (× : structure lost)", fontsize=10)
    ax.grid(True, axis="y", color="0.9")
axes[0].set_ylabel("number of nodes")
axes[0].legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# **Take-away.** All five methods meet the bound; the annealing methods reach it with
# the fewest additional nodes while keeping the matching-based nodes, and only grassroot
# set covering can lose controllability or observability.
