"""
The bipartite view: matchings, dilations and edge classes
=========================================================

In the bipartite representation every node appears twice, as an out-copy
:math:`x_j^+` and an in-copy :math:`x_i^-`. :func:`nocad.viz.plot_bipartite_matching`
puts the in-copy of every matched node level with the out-copy of its partner, so the
matched edges are horizontal and the unmatched in-copies, the driver nodes, are the
ones left without a partner. Coloring the edges by class shows what all maximum
matchings share: *critical* edges are in all of them (removing one adds a driver),
*redundant* edges in none, *ordinary* edges in some.
"""

# %%
# The NOCAD example
# -----------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import load_nocad_example, make_random_network
from nocad.viz import plot_bipartite_matching, plot_edge_classes

adj = load_nocad_example().adj
# [snippet:classes]
classes = nocad.edge_classes(adj)
for kind in ("critical", "ordinary", "redundant"):
    edges = [f"x{j + 1}->x{i + 1}" for (j, i), c in classes.items() if c == kind]
    print(f"{kind:9s}", ", ".join(edges))
# [/snippet:classes]
fig, axes = plt.subplots(1, 2, figsize=(8.2, 4.4), gridspec_kw={"width_ratios": [1, 1.25]})
plot_bipartite_matching(adj, ax=axes[0], title="bipartite view")
plot_edge_classes(adj, ax=axes[1], title="edge classes on the network")
fig.tight_layout()

# %%
# A dilation in the bipartite view
# --------------------------------
# A star :math:`x_1\to\{x_2,x_3,x_4\}`: one out-copy, three in-copies. The out-copy
# :math:`x_1^+` can match only one leaf, so every maximum matching leaves two leaves
# unmatched (a dilation); any of the three may be the matched one, so all three edges
# are *ordinary*.
star = np.zeros((4, 4))
star[0, 1:] = 1
fig, ax = plt.subplots(figsize=(3.6, 2.9))
plot_bipartite_matching(star, ax=ax, title="a star: one out-copy, three in-copies")

# %%
# Parameter study: edge classes and density
# -----------------------------------------
# Critical edges are frequent only in very sparse networks; their share falls quickly
# with the density. Dense networks consist almost entirely of ordinary,
# interchangeable edges, and redundant edges are most frequent at intermediate
# densities.
degrees = np.linspace(0.6, 6, 10)
share = {k: [] for k in ("critical", "ordinary", "redundant")}
for k in degrees:
    counts = {c: 0 for c in share}
    total = 0
    for s in range(4):
        cl = nocad.edge_classes(make_random_network(150, k, random_state=s).adj)
        for c in cl.values():
            counts[c] += 1
        total += len(cl)
    for c in share:
        share[c].append(counts[c] / max(total, 1))
fig, ax = plt.subplots(figsize=(5.2, 3.4))
cols = [nocad.plotting.ROLE_COLORS["matched"], nocad.plotting.ROLE_COLORS["attach"], "#9AA5B1"]
ax.stackplot(degrees, *share.values(), labels=list(share), colors=cols, alpha=0.85)
ax.set_xlabel(r"mean degree $\langle k\rangle$")
ax.set_ylabel("share of edges")
ax.set_title("edge classes of random networks (N = 150)", fontsize=10)
ax.legend(frameon=False, fontsize=8, loc="upper right")
ax.set_xlim(degrees[0], degrees[-1])
ax.set_ylim(0, 1)
fig.tight_layout()

# %%
# **Take-away.** The bipartite view turns the matching into straight lines and makes
# the dilations visible; the edge classes separate the backbone that every
# controllability certificate needs from the edges that are interchangeable.
