"""
Maximum matching and the minimum number of driver nodes
=======================================================

A matching is a set of edges without common start or end nodes; a node is matched when
a matching edge ends in it. Liu, Slotine and Barabási proved that the unmatched nodes of
a *maximum* matching form a minimum set of driver nodes (the minimum input theorem). The
four-node network of the NOCAD manual, a three-cycle with a tail, has several maximum
matchings: the number of driver nodes is fixed, their positions are not. On random
networks the share of driver nodes falls with the mean degree, the classical result of
network controllability.
"""

# %%
# One matching, two pictures
# --------------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import load_four_node_example, make_random_network
from nocad.plotting import draw_network
from nocad.viz import plot_bipartite_matching

# [snippet:matching]
adj = load_four_node_example().adj
m = nocad.maximum_matching(adj)
print("size of the matching:", m.size)
print("matched edges (start, end):", (m.edges + 1).tolist())
print("unmatched (driver) nodes:", m.unmatched + 1)
# [/snippet:matching]

pos = np.array([[-0.55, 0.65], [0.55, 0.65], [0.0, -0.25], [0.0, -1.1]])
fig, axes = plt.subplots(1, 2, figsize=(7.2, 3.4), gridspec_kw={"width_ratios": [1.1, 1]})
hl = {(int(a), int(b)): {"color": nocad.plotting.ROLE_COLORS["matched"], "lw": 2.6} for a, b in m.edges}
draw_network(adj, pos, ax=axes[0], highlight=hl, drivers=m.unmatched, node_size=420, font_size=9)
axes[0].set_title("directed network: matched edges green", fontsize=9)
plot_bipartite_matching(adj, m, ax=axes[1], title="bipartite representation")
fig.tight_layout()

# %%
# All maximum matchings
# ---------------------
# The small network has two maximum matchings. Each leaves exactly one node unmatched,
# but a different one: :math:`x_4` when the cycle is matched by itself and the tail is
# left over, :math:`x_1` when the stem runs through the cycle into the tail. Nodes
# :math:`x_1` and :math:`x_4` are therefore *intermittent* driver nodes, :math:`x_2` and
# :math:`x_3` are never driver nodes (*redundant*).
# [snippet:enumerate]
all_m = nocad.all_maximum_matchings(adj)
for k, mm in enumerate(all_m, start=1):
    print(f"matching {k}: edges {(mm.edges + 1).tolist()}  drivers {mm.unmatched + 1}")
print("node roles:", nocad.node_roles(adj))
# [/snippet:enumerate]
fig, axes = plt.subplots(1, len(all_m), figsize=(3.0 * len(all_m), 2.9))
for k, (ax, mm) in enumerate(zip(np.atleast_1d(axes), all_m, strict=True), start=1):
    hl = {(int(a), int(b)): {"color": nocad.plotting.ROLE_COLORS["matched"], "lw": 2.6} for a, b in mm.edges}
    draw_network(adj, pos, ax=ax, highlight=hl, drivers=mm.unmatched, node_size=380, font_size=9)
    ax.set_title(f"maximum matching {k}: driver $x_{{{mm.unmatched[0] + 1}}}$", fontsize=9)
fig.tight_layout()

# %%
# Parameter study: mean degree
# ----------------------------
# The share of driver nodes :math:`n_D=N_D/N` of Erdős--Rényi and scale-free networks with
# :math:`N=300` nodes. Sparse networks need many inputs because of their many sources,
# sinks and dilations; the heterogeneous scale-free networks need more than random ones
# of the same mean degree.
degrees = np.linspace(0.5, 8, 14)
fig, ax = plt.subplots(figsize=(5.2, 3.4))
for k, kind in enumerate(["erdos_renyi", "scale_free"]):
    share = []
    for kd in degrees:
        vals = [nocad.n_driver_nodes(make_random_network(300, kd, kind=kind, random_state=s).adj, "matching") / 300
                for s in range(3)]
        share.append(np.mean(vals))
    ax.plot(degrees, share, marker="os"[k], ms=4, lw=1.5, color=nocad.plotting.PALETTE[k],
            label=kind.replace("_", "-"))
ax.set_xlabel(r"mean degree $\langle k\rangle$")
ax.set_ylabel("share of driver nodes $n_D$")
ax.set_title("driver nodes of random networks (N = 300)", fontsize=10)
ax.grid(True, color="0.9")
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# **Take-away.** Maximum matching fixes how many driver nodes are needed, not which
# ones; denser and more homogeneous networks are controlled by a smaller share of
# their nodes.
