"""
Control and observation depth maps
==================================

How many integrations separate a state from the nearest input? The *control depth*
:math:`\\rho^C_i` is the network distance of state :math:`x_i` from the nearest driver
node, the *observation depth* :math:`\\rho^O_i` its distance to the nearest sensor node.
:func:`nocad.viz.plot_depth_map` colors the network by depth and outlines the regions
of the drivers (sensors): the states that share their nearest configured node, the
network Voronoi cells. The largest depth is the relative order that the placement
methods of NOCAD reduce.
"""

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

import nocad
from nocad.datasets import load_nocad_example, make_hen_case_study
from nocad.plotting import default_layout
from nocad.viz import plot_depth_map, plot_distance_matrix

adj = load_nocad_example().adj
design = nocad.InputOutputDesign().fit(adj)
pos = default_layout(adj)
# [snippet:depth]
rho_c = nocad.control_depth(adj, design.driver_nodes_)
rho_o = nocad.observation_depth(adj, design.sensor_nodes_)
print("control depth    ", rho_c.astype(int))
print("observation depth", rho_o.astype(int))
print("regions of the sensors", nocad.observation_regions(adj, design.sensor_nodes_) + 1)
# [/snippet:depth]
fig, axes = plt.subplots(1, 2, figsize=(10.0, 4.0))
plot_depth_map(adj, design.driver_nodes_, "control", pos=pos, ax=axes[0], title="control depth: one driver ($x_8$)")
plot_depth_map(adj, design.sensor_nodes_, "observation", pos=pos, ax=axes[1],
               title="observation depth: two sensors ($x_1$, $x_9$)")
fig.tight_layout()

# %%
# The distance matrix
# -------------------
# The same information as a matrix: rows are states sorted by region and depth, columns
# the configured nodes, cells the number of derivations :math:`\\ell+1` after which the
# input appears in the state (the MATLAB ``controlling`` matrix).
fig, axes = plt.subplots(1, 2, figsize=(7.6, 3.8))
plot_distance_matrix(adj, design.driver_nodes_, ax=axes[0], title="one driver")
plot_distance_matrix(adj, [3, 7], ax=axes[1], title="drivers $x_4$, $x_8$")
fig.tight_layout()

# %%
# Parameter study: adding drivers
# -------------------------------
# On the heat exchanger network one driver controls all 22 states, but some only after
# seven integrations. Adding drivers by the placement methods of Chapter 8 shrinks the
# regions and the depth.
hen = make_hen_case_study()
hpos = default_layout(hen.adj)
fig, axes = plt.subplots(1, 3, figsize=(13.0, 3.9))
for ax, k in zip(axes, (0, 2, 4), strict=True):
    if k == 0:
        nodes = nocad.driver_nodes(hen.adj)
    else:
        p = nocad.placement.Placement(kind="drivers", method="gdfcmsa", n_add=k, n_iter=300, n_runs=4,
                                      random_state=0).fit(hen.adj)
        nodes = p.nodes_
    depth = nocad.control_depth(hen.adj, nodes)
    plot_depth_map(hen.adj, nodes, pos=hpos, ax=ax, labels=hen.labels, node_size=210,
                   title=f"{len(nodes)} driver(s): max depth {int(depth.max())}, mean {depth.mean():.2f}")
fig.tight_layout()

# %%
# **Take-away.** Depth maps show where the effect of the inputs arrives late and where
# the outputs see the states only through long chains; the regions show which driver
# or sensor is responsible for which part of the network.
