"""
Node roles across all maximum matchings
=======================================

Because maximum matchings are not unique, the question "is this node a driver node?"
has three answers (Jia et al. 2013): *critical* nodes are driver nodes in every minimum
driver set (they have no incoming edge), *redundant* nodes in none, *intermittent*
nodes in some. :func:`nocad.node_roles` classifies all nodes from one maximum matching
by alternating paths, without enumerating the matchings.
"""

# %%
# Roles on a random network
# -------------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import make_random_network
from nocad.plotting import default_layout
from nocad.viz import plot_node_roles

net = make_random_network(30, 1.8, random_state=3).adj
# [snippet:roles]
roles = nocad.node_roles(net)
print({r: int((roles == r).sum()) for r in ("critical", "intermittent", "redundant")})
print("driver nodes of one maximum matching:", nocad.maximum_matching(net).unmatched + 1)
# [/snippet:roles]
fig, ax = plt.subplots(figsize=(6.0, 4.4))
plot_node_roles(net, pos=default_layout(net), ax=ax, title="node roles of a random network (N = 30)")

# %%
# Parameter study: two control modes
# ----------------------------------
# Jia et al. showed that networks of the same mean degree can be controlled in two
# modes: *centralized*, where most nodes are redundant and the few driver nodes are
# fixed, or *distributed*, where most nodes are intermittent and the driver nodes can be
# chosen almost freely. Every dot below is one Erdős--Rényi network (N = 300): between
# mean degrees of about 3.5 and 6 networks of the same density fall into either mode.
# The densest networks have a perfect matching; one driver node suffices and, by the
# convention of :func:`nocad.node_roles`, every node is intermittent.
degrees = np.linspace(0.5, 8, 16)
fig, ax = plt.subplots(figsize=(5.4, 3.5))
for s in range(8):
    red, crit = [], []
    for k in degrees:
        rl = nocad.node_roles(make_random_network(300, k, random_state=100 * s + int(10 * k)).adj)
        red.append((rl == "redundant").mean())
        crit.append((rl == "critical").mean())
    ax.scatter(degrees, red, s=12, color="#6B7785", alpha=0.7, label="redundant (one network)" if s == 0 else None)
    ax.scatter(degrees, crit, s=12, color=nocad.plotting.ROLE_COLORS["critical"], alpha=0.7,
               label="critical (one network)" if s == 0 else None)
ax.set_xlabel(r"mean degree $\langle k\rangle$")
ax.set_ylabel("share of nodes")
ax.set_title("node roles of Erdős–Rényi networks (N = 300)", fontsize=10)
ax.grid(True, color="0.9")
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# **Take-away.** Node roles separate the nodes that must always receive an input
# from those that never need one; the intermittent ones are where the designer can
# choose, for example by cost, by the relative degree or by robustness.
