"""
From a state-space model to the network of its state variables
===============================================================

A linear system :math:`\\dot{\\mathbf{x}}=\\mathbf{A}\\mathbf{x}+\\mathbf{B}\\mathbf{u}` is
turned into a network by drawing an edge :math:`x_j\\to x_i` for every non-zero
:math:`a_{ij}`: the adjacency matrix is :math:`\\mathbf{A}^{\\mathsf T}`. Three water tanks,
the first feeding the other two, show why the *physical* topology (the pipes) is not
the network of the state variables: if the outflow of a tank depends on its level, every
state has a self-loop; if the tanks are connected vessels, the flow depends on both
levels and every pipe gives a pair of edges. The driver and sensor nodes, computed by
maximum matching, change accordingly.
"""

# %%
# Three ways to read the same pipes
# ---------------------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import make_water_tanks
from nocad.plotting import draw_network

# [snippet:tanks]
variants = {
    "physical (pipes only)": make_water_tanks(3, "branch", "physical"),
    "free outflow (self-loops)": make_water_tanks(3, "branch", "free_outflow"),
    "connected vessels (loops + pairs)": make_water_tanks(3, "branch", "connected"),
}
for name, tanks in variants.items():
    A = nocad.adjacency_to_state_matrix(tanks.adj).toarray().astype(int)  # A = W^T
    design = nocad.InputOutputDesign().fit(tanks.adj)
    print(f"{name:34s} drivers={design.driver_nodes_ + 1} sensors={design.sensor_nodes_ + 1}")
# [/snippet:tanks]

pos = np.array([[0.0, 0.55], [-0.6, -0.45], [0.6, -0.45]])
fig, axes = plt.subplots(1, 3, figsize=(9.6, 3.3))
for ax, (name, tanks) in zip(axes, variants.items(), strict=True):
    design = nocad.InputOutputDesign().fit(tanks.adj)
    draw_network(tanks.adj, pos, ax=ax, labels=tanks.labels, drivers=design.driver_nodes_,
                 sensors=design.sensor_nodes_, node_size=420, font_size=9, draw_loops="arc")
    ax.set_title(f"{name}\n$N_D$ = {design.n_drivers_}, $N_S$ = {design.n_sensors_}", fontsize=9)
fig.tight_layout()

# %%
# The state matrix and its network
# --------------------------------
# For the connected vessels the state matrix has the pattern below; the network is
# its transpose, which is what the code stores as ``adj``.
A = nocad.adjacency_to_state_matrix(variants["connected vessels (loops + pairs)"].adj)
print(A.toarray().astype(int))

# %%
# Parameter study: more tanks
# ---------------------------
# With a branching topology every extra tank is a new sink of the physical network, so
# the numbers of driver and sensor nodes grow with the number of tanks. Self-loops
# remove every dilation (a state can be "matched" by its own loop), so one input
# controls any number of tanks, but every tank is still a sink and needs its own
# sensor. With connected vessels the network is strongly connected and a single input
# and a single output suffice.
sizes = np.arange(2, 11)
fig, ax = plt.subplots(figsize=(5.4, 3.5))
for k, connection in enumerate(["physical", "free_outflow", "connected"]):
    nets = [make_water_tanks(n, "branch", connection).adj for n in sizes]
    nd = [nocad.n_driver_nodes(a) for a in nets]
    ns = [nocad.sensor_nodes(a).size for a in nets]
    col = nocad.plotting.PALETTE[k]
    ax.plot(sizes, nd, marker="osD"[k], ms=4, lw=1.5, color=col, label=f"{connection}: $N_D$")
    ax.plot(sizes + 0.08 * (k - 1), ns, marker="osD"[k], ms=4, lw=1.2, ls="--", color=col, mfc="white",
            label=f"{connection}: $N_S$")
ax.set_xlabel("number of tanks")
ax.set_ylabel("driver / sensor nodes")
ax.set_title("branching tanks: inputs and outputs by connection type", fontsize=10)
ax.grid(True, color="0.9")
ax.legend(frameon=False, fontsize=7, ncol=1)
fig.tight_layout()

# %%
# **Take-away.** The network of a dynamical system has to be built from its state
# equations, not from its piping diagram: self-influence removes the dilations that
# force an input at every branch, and interactions make the network strongly
# connected, so that one input and one output make the system controllable and
# observable.
