"""
The operability plane
=====================

Placing every state at the point :math:`(\\rho^C_i,\\rho^O_i)`, its control and its
observation depth, gives a compact picture of a whole input--output configuration. The
sum :math:`\\rho^C_i+\\rho^O_i` is the length of the shortest input-to-output path through
the state (dotted level lines); the largest coordinates are the relative orders of the
input and output configurations; states in the upper right corner are slow both to
steer and to see. Marginal bars count the states at every depth.
"""

# %%
# Heat exchanger network: minimal configuration
# ---------------------------------------------

import nocad
from nocad.datasets import make_hen_case_study
from nocad.placement import Placement
from nocad.viz import plot_operability_plane

hen = make_hen_case_study()
design = nocad.InputOutputDesign().fit(hen.adj)
# [snippet:plane]
axes = plot_operability_plane(hen.adj, design.driver_nodes_, design.sensor_nodes_, labels=hen.labels)
# [/snippet:plane]
axes["top"].set_title(f"minimal design: {design.n_drivers_} driver, {design.n_sensors_} sensor nodes", fontsize=10)

# %%
# Parameter study: improved configurations
# ----------------------------------------
# Adding drivers and sensors with GDFCMSA until the relative order is at most 2 moves
# the cloud toward the origin; the dashed lines mark the bound.
drv = Placement(kind="drivers", method="gdfcmsa", r_max=2, n_iter=300, n_runs=4, random_state=0).fit(hen.adj)
sen = Placement(kind="sensors", method="gdfcmsa", r_max=2, n_iter=300, n_runs=4, random_state=0).fit(hen.adj)
print("drivers:", [hen.labels[v] for v in drv.nodes_])
print("sensors:", [hen.labels[v] for v in sen.nodes_])
axes = plot_operability_plane(hen.adj, drv.nodes_, sen.nodes_, labels=hen.labels, r_max=2)
axes["top"].set_title(f"improved: {drv.nodes_.size} drivers, {sen.nodes_.size} sensors (bound 2)", fontsize=10)

# %%
# **Take-away.** The operability plane condenses a configuration into one scatter
# plot: its corners show the worst states, its marginals the distribution of the
# relative orders, and moving nodes between configurations shows the trade-off between
# the number of inputs and outputs and how fast the system can be steered and seen.
