"""
System characterisation: network and node measures
==================================================

The second module of NOCAD computes about fifty measures of a system from its
state-space matrices: network-level values (size, density, diameter, degree
centralization, assortativity, relative degree, the share of self-loops and of
symmetric edges), node centralities (degrees, closeness, betweenness, PageRank, control
and observe centrality) and the clustering and similarity measures of the drivers,
sensors and edges. :func:`nocad.measures.measures_tables` returns them as pandas tables.
For the nine-state example of the NOCAD manual the density, diameter, degree variance,
Freeman centralization and share of symmetric edges agree with the values printed in
the manual.
"""

# %%
# The measures 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 measures_tables

adj = load_nocad_example().adj
# [snippet:tables]
A, B, C, D = nocad.generate_matrices(adj)
tables = measures_tables(A, B, C, D)
print(tables.system)
print(tables.nodes[["degree", "closeness", "betweenness", "pagerank", "control", "observe"]].round(3))
# [/snippet:tables]

# %%
# Node centralities side by side
# ------------------------------
cols = ["degree_scott", "closeness", "betweenness", "pagerank"]
vals = tables.nodes[cols].to_numpy(float)
vals = vals / np.where(vals.max(axis=0) > 0, vals.max(axis=0), 1)
fig, ax = plt.subplots(figsize=(6.4, 3.3))
x = np.arange(len(tables.nodes))
for k, c in enumerate(cols):
    ax.bar(x + (k - 1.5) * 0.2, vals[:, k], width=0.2, color=nocad.plotting.PALETTE[k], label=c.replace("_", " "))
ax.set_xticks(x)
ax.set_xticklabels(tables.nodes.index)
ax.set_ylabel("value / maximum")
ax.set_title("node centralities of the NOCAD example (normalized)", fontsize=10)
ax.legend(frameon=False, fontsize=7, ncol=4, loc="upper center", bbox_to_anchor=(0.5, -0.12))
ax.grid(True, axis="y", color="0.9")
fig.tight_layout()

# %%
# Parameter study: measures of growing random networks
# ----------------------------------------------------
# Density, diameter and degree centralization of Erdős--Rényi networks with N = 100
# against the mean degree: the diameter peaks where the giant component forms.
from nocad.datasets import make_random_network
from nocad.distances import diameter
from nocad.measures import degree_freeman, density

degrees = np.linspace(0.5, 6, 12)
rows = {"density x 10": [], "diameter / 10": [], "Freeman centralization": []}
for k in degrees:
    v = {key: [] for key in rows}
    for s in range(3):
        a = make_random_network(100, k, random_state=s).adj
        v["density x 10"].append(10 * density(a))
        v["diameter / 10"].append(diameter(a) / 10)
        v["Freeman centralization"].append(degree_freeman(a))
    for key in rows:
        rows[key].append(np.mean(v[key]))
fig, ax = plt.subplots(figsize=(5.2, 3.4))
for k, (name, y) in enumerate(rows.items()):
    ax.plot(degrees, y, marker="osD"[k], ms=4, color=nocad.plotting.PALETTE[k], label=name)
ax.set_xlabel(r"mean degree $\langle k\rangle$")
ax.set_title("network measures of random networks (N = 100)", fontsize=10)
ax.grid(True, color="0.9")
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# **Take-away.** One call gives the measures that the NOCAD papers use to relate the
# structure of a network to the effort of controlling and observing it, in tables that
# are easy to compare across systems.
