"""
Similarity of drivers, sensors and edges
========================================

The NOCAD toolbox introduced three similarity measures built on reachability. Two
driver nodes are similar if they influence the same states after a similar number of
derivations (Jaccard index of the controlled sets, weighted by the agreement of the
distances); the *endpoint similarity* of an edge compares what its two endpoints
control and observe, and is one on cycles; the *edge similarity* of two
edges compares the four sets of their endpoints and reveals parts of the network with
redundancy.
"""

# %%
# Driver similarity and edge similarity of the NOCAD example
# ----------------------------------------------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import load_nocad_example
from nocad.measures import driver_similarity, edge_similarity, endpoint_similarity, sensor_similarity

adj = load_nocad_example().adj
drivers = [3, 5, 7]  # x4, x6, x8: a richer configuration than the minimal one
sensors = [0, 1, 2, 8]
A = nocad.adjacency_to_state_matrix(adj).toarray()
B = np.zeros((9, 3))
B[drivers, range(3)] = 1
C = np.zeros((4, 9))
C[range(4), sensors] = 1
# [snippet:similarity]
ds = driver_similarity(A, B)
ss = sensor_similarity(A, C)
S, edges = edge_similarity(adj)
es = endpoint_similarity(adj)
# [/snippet:similarity]
print("driver similarity:\n", ds[np.ix_(drivers, drivers)].round(2))
print("sensor similarity:\n", ss[np.ix_(sensors, sensors)].round(2))
fig, axes = plt.subplots(1, 2, figsize=(9.6, 4.2), gridspec_kw={"width_ratios": [1, 1.6]})
im = axes[0].imshow(ds[np.ix_(drivers, drivers)], vmin=0, vmax=1, cmap="Blues")
axes[0].set_xticks(range(3))
axes[0].set_xticklabels([f"x{d + 1}" for d in drivers])
axes[0].set_yticks(range(3))
axes[0].set_yticklabels([f"x{d + 1}" for d in drivers])
axes[0].set_title("driver similarity", fontsize=10)
for a in range(3):
    for b in range(3):
        axes[0].text(b, a, f"{ds[drivers[a], drivers[b]]:.2f}", ha="center", va="center", fontsize=8,
                     color="white" if ds[drivers[a], drivers[b]] > 0.6 else "black")
lab = [f"{j + 1}{i + 1}" for j, i in edges]
im = axes[1].imshow(S, vmin=0, vmax=1, cmap="Greens")
axes[1].set_xticks(range(len(lab)))
axes[1].set_xticklabels(lab, fontsize=6.5, rotation=90)
axes[1].set_yticks(range(len(lab)))
axes[1].set_yticklabels(lab, fontsize=6.5)
axes[1].set_title("edge similarity (label: start, end)", fontsize=10)
fig.colorbar(im, ax=axes[1], fraction=0.04)
fig.tight_layout()

# %%
# Parameter study: endpoint similarity on the network
# ---------------------------------------------------
# Edges inside the strongly connected components have endpoint similarity one (their
# endpoints reach and are reached by the same nodes). An edge between components is
# low when its endpoints differ much in what they reach or in what reaches them: the
# edge from the source x8 and the edges into x7 and x2 are the weakest links.
from nocad.plotting import ROLE_COLORS, default_layout, draw_network

pos = default_layout(adj)
hl = {}
cmap = plt.get_cmap("viridis")
for j, i in edges:
    hl[(int(j), int(i))] = {"color": cmap(es[j, i]), "lw": 1.0 + 2.0 * es[j, i]}
fig, ax = plt.subplots(figsize=(5.6, 4.2))
draw_network(adj, pos, ax=ax, highlight=hl, node_color=ROLE_COLORS["state"], label_color="#1F2A36")
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(0, 1))
fig.colorbar(sm, ax=ax, fraction=0.04, label="endpoint similarity")
ax.set_title("endpoint similarity of the edges", fontsize=10)

# %%
# **Take-away.** Similar drivers (sensors) duplicate each other's work; similar edges
# mark redundant parts of the network, dissimilar ones the bridges that carry a
# unique share of the influence.
