"""
Relative degree in the network
==============================

The relative degree :math:`r_{kl}` of output :math:`y_k` with respect to input
:math:`u_l` counts the integrations between them: the smallest :math:`r` with
:math:`\\mathbf{c}_k\\mathbf{A}^{r-1}\\mathbf{b}_l\\neq0`. In the network it is (generically)
the shortest path from the driver node to the sensor node plus one. With disturbances
acting on every state, the *relative order* of a configuration is the largest network
distance of a state from its nearest driver (to its nearest sensor). The cost of the
NOCAD papers weighs this worst case against the mean:
:math:`\\beta\\max_i\\rho_i+(1-\\beta)\\frac1N\\sum_i\\rho_i`.
"""

# %%
# Relative degrees of the NOCAD example
# -------------------------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import load_nocad_example
from nocad.placement import configuration_cost

adj = load_nocad_example().adj
design = nocad.InputOutputDesign().fit(adj)
# [snippet:reldeg]
R = nocad.relative_degree_matrix(adj, design.driver_nodes_, design.sensor_nodes_)
print("classical relative degrees (rows: sensors, columns: drivers):\n", R)
print("relative order of the configuration:", nocad.relative_degree(adj, design.driver_nodes_, design.sensor_nodes_))
for drivers in ([7], [3, 7]):
    cost, mx, mean = configuration_cost(adj, drivers, kind="drivers", beta=0.5)
    print(f"drivers {np.add(drivers, 1)}: cost {cost:.4f}, max {mx:.0f}, mean {mean:.4f}")
# [/snippet:reldeg]

# %%
# Numerical check: the first non-zero Markov parameter
# ----------------------------------------------------
# For a random realization of the pattern the relative degree is the first :math:`r`
# for which :math:`\\mathbf{c}\\mathbf{A}^{r-1}\\mathbf{b}` is non-zero; it matches the
# network distance plus one.
from nocad.structural import random_realization

A = random_realization(nocad.adjacency_to_state_matrix(adj), 0).toarray()
b = np.zeros(9)
b[7] = 1
dist = nocad.geodesic_distances(adj)[7]
r_num = []
for s in range(9):
    c = np.zeros(9)
    c[s] = 1
    r = next((k for k in range(1, 12) if abs(c @ np.linalg.matrix_power(A, k - 1) @ b) > 1e-12), np.inf)
    r_num.append(r)
fig, ax = plt.subplots(figsize=(5.0, 3.2))
ax.bar(np.arange(9) - 0.18, dist + 1, width=0.36, color=nocad.plotting.PALETTE[0], label="network distance + 1")
ax.bar(np.arange(9) + 0.18, r_num, width=0.36, color=nocad.plotting.PALETTE[2], label=r"first $r$ with $cA^{r-1}b\neq0$")
ax.set_xticks(range(9))
ax.set_xticklabels([f"x{i + 1}" for i in range(9)])
ax.set_ylabel("relative degree")
ax.set_title("input at $x_8$, output at each state", fontsize=10)
ax.legend(frameon=False, fontsize=8)
ax.grid(True, axis="y", color="0.9")
fig.tight_layout()

# %%
# Parameter study: the weight beta
# --------------------------------
# All configurations of two drivers that contain :math:`x_8` (needed for
# controllability), ranked by the cost for three values of :math:`\\beta`: the worst case
# dominates for :math:`\\beta=1`, the mean for :math:`\\beta=0`.
cands = [k for k in range(9) if k != 7]
fig, ax = plt.subplots(figsize=(5.4, 3.3))
for j, beta in enumerate((0.0, 0.5, 1.0)):
    costs = [configuration_cost(adj, [7, k], "drivers", beta)[0] for k in cands]
    ax.plot(range(len(cands)), costs, marker="osD"[j], ms=4, color=nocad.plotting.PALETTE[j], label=f"beta = {beta}")
ax.set_xticks(range(len(cands)))
ax.set_xticklabels([f"x{k + 1}" for k in cands])
ax.set_xlabel("second driver node (first: $x_8$)")
ax.set_ylabel("cost")
ax.set_title("cost of two-driver configurations", fontsize=10)
ax.legend(frameon=False, fontsize=8)
ax.grid(True, color="0.9")
fig.tight_layout()

# %%
# **Take-away.** The network distance is the relative degree in disguise; a cost that
# mixes its worst case and its mean ranks the candidate configurations; for the
# NOCAD example a second driver at :math:`x_4` or :math:`x_5` is best whatever the weight.
