"""
The SCC hierarchy: where inputs and outputs must go
===================================================

Lin's accessibility condition says that every state must be reachable from an input;
in network terms, every *source* strongly connected component (one without incoming
edges) needs a driver node, and, dually, every *sink* component needs a sensor node.
:func:`nocad.viz.hierarchy_layout` draws the condensation level by level: source
components on top, every other component one level below its deepest predecessor, the
nodes of a component on a circle in the order of a cycle through it. The nine-state
example of the NOCAD manual and a random network with many components show the view;
the observation direction counts the levels upward from the sinks.
"""

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

import nocad
from nocad.datasets import load_nocad_example, make_random_network
from nocad.viz import hierarchy_layout, plot_scc_hierarchy

# [snippet:hierarchy]
adj = load_nocad_example().adj
design = nocad.InputOutputDesign().fit(adj)
layout = hierarchy_layout(adj, direction="control")
print("components per level:", [[(layout.condensation.members[c] + 1).tolist() for c in lv] for lv in layout.levels])
ax = plot_scc_hierarchy(adj, design.driver_nodes_, design.sensor_nodes_, matching=design.control_matching_)
# [/snippet:hierarchy]
ax.set_title("control view: source components on top", fontsize=10)

fig, ax = plt.subplots(figsize=(5.6, 4.6))
plot_scc_hierarchy(adj, design.driver_nodes_, design.sensor_nodes_, direction="observation", ax=ax)
ax.set_title("observation view: sink components at the bottom", fontsize=10)

# %%
# A network with many components
# ------------------------------
# A sparse random network has many trivial components (single nodes): every source node
# is a source component and needs its own input, every sink node needs a sensor.
net = make_random_network(30, 1.4, random_state=4).adj
d = nocad.InputOutputDesign().fit(net)
fig, ax = plt.subplots(figsize=(7.0, 5.0))
plot_scc_hierarchy(net, d.driver_nodes_, d.sensor_nodes_, ax=ax, node_size=170)
ax.set_title(f"random network: {d.n_drivers_} driver and {d.n_sensors_} sensor nodes", fontsize=10)

# %%
# Parameter study: density and depth of the hierarchy
# ---------------------------------------------------
# As the mean degree grows, a giant component swallows most nodes: the number of
# components and of source components falls, and with it the number of required
# inputs, while the hierarchy gets shallower.
import numpy as np

degrees = np.linspace(0.6, 4.0, 12)
stats = {"components": [], "source components": [], "levels": []}
for k in degrees:
    vals = {key: [] for key in stats}
    for s in range(5):
        a = make_random_network(100, k, random_state=s).adj
        c = nocad.condensation(a)
        lay = hierarchy_layout(a)
        vals["components"].append(c.n_components / 100)
        vals["source components"].append(c.sources.size / 100)
        vals["levels"].append(len(lay.levels) / 100)
    for key in stats:
        stats[key].append(np.mean(vals[key]))
fig, ax = plt.subplots(figsize=(5.2, 3.4))
for j, (name, y) in enumerate(stats.items()):
    ax.plot(degrees, y, marker="osD"[j], ms=4, color=nocad.plotting.PALETTE[j], label=name)
ax.set_xlabel(r"mean degree $\langle k\rangle$")
ax.set_ylabel("count / N")
ax.set_title("condensation of random networks (N = 100)", fontsize=10)
ax.grid(True, color="0.9")
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# **Take-away.** The hierarchy of strongly connected components shows at a glance
# which parts of a network must receive an input (top level) or an output (bottom
# level), and how deep the influence of an input has to travel.
