"""
Control profiles of real and model networks
===========================================

Ruths and Ruths (2014) explained the driver nodes by three structures: source nodes,
external dilations (a surplus of sinks over sources) and internal dilations. The
control profile :math:`(\\eta_s,\\eta_e,\\eta_i)` gives their shares and places a network
in a triangle. The bundled networks of the NOCAD study fall into different corners.
The state matrices of the dynamical systems of Set III shown here have a perfect
matching and no source or sink nodes (their diagonals are non-zero); their single driver
node counts as an internal dilation by the convention :math:`N_D=\\max(N-|\\mathcal{M}|,1)`,
so they all sit in the internal-dilation corner.
"""

# %%
# The bundled networks
# --------------------
import matplotlib.pyplot as plt

import nocad
from nocad.datasets import list_networks, load_network, make_random_network
from nocad.viz import plot_control_profiles

# [snippet:profiles]
profiles, groups = {}, {}
for name in list_networks("I") + list_networks("II") + ["build", "cdplayer", "heatcont", "iss", "pde", "tline"]:
    net = load_network(name)
    profiles[name] = nocad.control_profile(net.adj)
    groups[name] = f"Set {net.group}"
# [/snippet:profiles]
for name, p in profiles.items():
    print(f"{name:10s} N_D={p['n_d']:4d}  eta_s={p['eta_s']:.2f} eta_e={p['eta_e']:.2f} eta_i={p['eta_i']:.2f}")
fig, ax = plt.subplots(figsize=(5.6, 4.8))
plot_control_profiles(profiles, groups, ax=ax, title="control profiles of the bundled networks")

# %%
# Parameter study: random models
# ------------------------------
# Erdős--Rényi and scale-free networks of increasing density move from the
# source-dominated corner toward the internal dilations, as the number of nodes
# without incoming or outgoing edges falls.
prof, grp = {}, {}
for kind in ("erdos_renyi", "scale_free"):
    for k in (0.8, 1.5, 3.0, 6.0):
        net = make_random_network(300, k, kind=kind, random_state=1).adj
        key = f"{'ER' if kind == 'erdos_renyi' else 'SF'} {k}"
        prof[key] = nocad.control_profile(net)
        grp[key] = kind.replace("_", "-")
fig, ax = plt.subplots(figsize=(5.6, 4.8))
plot_control_profiles(prof, grp, ax=ax, title="random networks: label = mean degree")

# %%
# **Take-away.** The control profile tells why a network needs its inputs: because
# of nodes nobody influences, because of surplus end points, or because of internal
# bottlenecks; each calls for a different remedy.
