"""
State matrices of real dynamical systems
========================================

Set III of the NOCAD study contains the zero patterns of the state matrices of
engineering models from the benchmark collection of Chahlaoui and Van Dooren (beams,
buildings, CD player, heat equation, circuits). Their diagonals are full and most of
their edges symmetric, so applying the connection types changes nothing: the network
of a real dynamical system already contains its self-influence and interactions. One
input and one output per connected component usually suffice.
"""

# %%
# Driver and sensor counts
# ------------------------
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

import nocad
from nocad.datasets import list_networks, load_network
from nocad.measures import percent_loop_sym

rows = []
# [snippet:setiii]
for name in list_networks("III"):
    net = load_network(name)
    if net.n_states > 1100:
        continue
    loops, sym = percent_loop_sym(net.adj)
    comps = nocad.condensation(net.adj)
    rows.append({"network": name, "N": net.n_states, "edges": net.n_edges, "loops %": round(loops),
                 "symmetric %": round(sym), "SCCs": comps.n_components,
                 "drivers": nocad.n_driver_nodes(net.adj, "minimum"),
                 "drivers (g)": nocad.n_driver_nodes(nocad.apply_connection_type(net.adj, "g"), "minimum"),
                 "sensors": nocad.sensor_nodes(net.adj, "minimum").size})
table = pd.DataFrame(rows)
# [/snippet:setiii]
pd.set_option("display.width", 140)
print(table.to_string(index=False))

fig, ax = plt.subplots(figsize=(6.4, 3.4))
x = np.arange(len(table))
ax.bar(x - 0.2, table["drivers"] / table["N"], width=0.4, color=nocad.plotting.PALETTE[0], label="original")
ax.bar(x + 0.2, table["drivers (g)"] / table["N"], width=0.4, color=nocad.plotting.PALETTE[2],
       label="with connection type g")
ax.set_yscale("log")
ax.set_xticks(x)
ax.set_xticklabels(table.network, rotation=60, fontsize=7)
ax.set_ylabel("share of driver nodes")
ax.set_title("Set III: driver nodes do not change with the connection types", fontsize=10)
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# **Take-away.** Where a network really is the state matrix of a physical system,
# its structure already encodes the balance equations, and the network-based design
# needs very few inputs and outputs.
