"""
Source components: signal sharing, path finding and the exact minimum
=====================================================================

The unmatched nodes of a maximum matching are not always enough: a strongly connected
component without incoming edges whose nodes are all matched (by cycles of the
matching) receives no input. *Signal sharing* feeds such a component with the signal
of an existing input; *path finding* (Leitold, Vathy-Fogarassy and Abonyi) exchanges one
matched edge so that the stem of a new driver node runs through the component into an
unmatched node outside, and every input drives a single node. Path finding processes the
components greedily; the *minimum* method of nocad computes the smallest number of such
dedicated inputs exactly, by one maximum matching on a graph extended with a slack
vertex per source component.
"""

# %%
# The cycle with a tail
# ---------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import make_competing_cycles, make_cycle_example, make_random_network
from nocad.plotting import PALETTE, ROLE_COLORS, draw_network


def show(adj, pos, method, ax, title):
    d = nocad.InputOutputDesign(method).fit(adj)
    hl = {(int(a), int(b)): {"color": ROLE_COLORS["matched"], "lw": 2.6} for a, b in d.control_matching_.edges}
    draw_network(adj, pos, ax=ax, highlight=hl, drivers=d.dedicated_driver_nodes_, shared=d.shared_driver_nodes_,
                 node_size=380, font_size=9)
    ax.set_title(f"{title}\n{d.n_inputs_} input(s), {d.n_drivers_} driver node(s)", fontsize=9)


# [snippet:methods]
adj = make_cycle_example().adj  # x1 <-> x2 -> x3 -> x4
for method in ("signal_sharing", "path_finding", "minimum"):
    A, B, C, D = nocad.generate_matrices(adj, method)
    print(f"{method:15s} B^T =", B.toarray().astype(int).T.tolist())
# [/snippet:methods]

pos = np.array([[-0.9, 0.45], [-0.9, -0.45], [0.1, -0.45], [1.0, -0.45]])
fig, axes = plt.subplots(1, 3, figsize=(10, 3.0))
for ax, (method, title) in zip(axes, [("signal_sharing", "signal sharing"), ("path_finding", "path finding"),
                                      ("minimum", "exact minimum")], strict=True):
    show(adj, pos, method, ax, title)
fig.tight_layout()

# %%
# Competing source components
# ---------------------------
# Two two-node cycles are source components; the first points to :math:`x_5` and
# :math:`x_6`, the second only to :math:`x_5`. Opened greedily, both cycles may claim
# :math:`x_5`; the exact method lets the first take :math:`x_6`, and two inputs suffice.
# [snippet:competing]
adj = make_competing_cycles().adj
for method in ("signal_sharing", "path_finding", "minimum"):
    d = nocad.InputOutputDesign(method).fit(adj)
    print(f"{method:15s} inputs={d.n_inputs_} drivers={d.driver_nodes_ + 1} controllable={d.is_controllable()}")
# [/snippet:competing]
pos = np.array([[-1.2, 0.5], [-1.2, -0.5], [1.2, 0.5], [1.2, -0.5], [0.0, 0.0], [-0.2, 1.1]])
fig, axes = plt.subplots(1, 3, figsize=(10, 3.2))
for ax, (method, title) in zip(axes, [("signal_sharing", "signal sharing"), ("path_finding", "path finding"),
                                      ("minimum", "exact minimum")], strict=True):
    show(adj, pos, method, ax, title)
fig.tight_layout()

# %%
# Parameter study: self-loops make source components
# ---------------------------------------------------
# Self-loops turn single nodes into strongly connected components; the more of them,
# the more often a source component is matched internally. On sparse random networks
# (N = 200, mean degree 1.5) signal sharing needs the fewest *inputs*, while path
# finding and the exact minimum need the fewest *driver nodes* with dedicated inputs,
# path finding being at most a few nodes above the minimum.
probs = np.linspace(0, 1, 11)
rows = {"signal sharing: inputs": [], "signal sharing: driver nodes": [], "path finding": [], "minimum": []}
for p in probs:
    vals = {k: [] for k in rows}
    for s in range(4):
        a = make_random_network(200, 1.5, self_loops=p, random_state=s).adj
        ss = nocad.InputOutputDesign("signal_sharing").fit(a)
        vals["signal sharing: inputs"].append(ss.n_inputs_)
        vals["signal sharing: driver nodes"].append(ss.n_drivers_)
        vals["path finding"].append(nocad.n_driver_nodes(a, "path_finding"))
        vals["minimum"].append(nocad.n_driver_nodes(a, "minimum"))
    for k in rows:
        rows[k].append(np.mean(vals[k]) / 200)
fig, ax = plt.subplots(figsize=(5.4, 3.5))
for k, (name, y) in enumerate(rows.items()):
    ax.plot(probs, y, marker="osD^"[k], ms=4, lw=1.4, color=PALETTE[k], label=name)
ax.set_xlabel("probability of a self-loop")
ax.set_ylabel("share of the states")
ax.set_title("inputs and driver nodes as self-loops are added", fontsize=10)
ax.grid(True, color="0.9")
ax.legend(frameon=False, fontsize=7)
fig.tight_layout()

# %%
# **Take-away.** Perfectly matched source components are where maximum matching alone
# fails; path finding repairs them without shared signals, and the exact minimum
# shows how close its greedy choices come to the optimum.
