"""
Control centrality
==================

The control centrality of a node (Liu, Slotine and Barabási 2012) is the dimension of
the subspace it can control alone: the generic rank of
:math:`[\\mathbf{b}_i,\\mathbf{A}\\mathbf{b}_i,\\dots,\\mathbf{A}^{N-1}\\mathbf{b}_i]`.
:func:`nocad.control_centrality` computes it from random realizations of the pattern
with an orthogonal Krylov iteration. It is bounded by the number of nodes the node can
reach, and the gap between the two measures the dilations on its way. The MATLAB toolbox
took the structural rank of the numerically formed Kalman matrix, an upper bound
(``method="sprank"``).
"""

# %%
# Control centrality on a tree and on a network
# ---------------------------------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import make_hen_case_study, make_random_network
from nocad.measures import reach_c

tree = np.zeros((7, 7))
for j, i in [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]:
    tree[j, i] = 1
# [snippet:centrality]
A = tree.T
cc = nocad.control_centrality(A)
reach = reach_c(A).sum(axis=1)
print("control centrality:", cc)
print("reachable nodes:   ", reach)
# [/snippet:centrality]

# %%
# Parameter study: centrality against reach and out-degree
# --------------------------------------------------------
# On a random network the control centrality of a node is limited by what it reaches;
# self-loops on every node remove the dilations and the two measures coincide.
net = make_random_network(80, 1.8, random_state=1).adj
fig, axes = plt.subplots(1, 2, figsize=(9.0, 3.4), sharey=True)
for ax, (name, G) in zip(axes, (("plain", net), ("with self-loops", nocad.add_node_dynamics(net))), strict=True):
    A = nocad.adjacency_to_state_matrix(G)
    c = nocad.control_centrality(A)
    r = reach_c(A).sum(axis=1)
    ax.scatter(r, c, s=16, color=nocad.plotting.PALETTE[0], alpha=0.8)
    lim = max(r.max(), 1) + 2
    ax.plot([0, lim], [0, lim], ls="--", color="0.6", lw=0.8)
    ax.set_xlabel("number of reachable nodes")
    ax.set_title(f"random network, {name}", fontsize=10)
    ax.grid(True, color="0.9")
axes[0].set_ylabel("control centrality")
fig.tight_layout()
hen = make_hen_case_study()
print("HEN control centrality of the driver:", nocad.control_centrality(nocad.adjacency_to_state_matrix(hen.adj),
                                                                        nodes=nocad.driver_nodes(hen.adj))[
                                                                            nocad.driver_nodes(hen.adj)])

# %%
# **Take-away.** Control centrality measures what a single input can achieve; when it
# falls short of the reach of the node, the missing dimensions are lost in dilations,
# and self-influence restores them.
