"""
The system matrix in block-triangular order
===========================================

Structural controllability is also a statement about the zero pattern of
:math:`[\\mathbf{A},\\mathbf{B}]`: its generic rank must be full and every row must be
connected to a column of :math:`\\mathbf{B}`. Sorting the states by a topological order
of the strongly connected components makes :math:`\\mathbf{A}` block lower triangular;
the diagonal blocks are the components, source blocks need an entry in
:math:`\\mathbf{B}`, sink blocks an entry in :math:`\\mathbf{C}`. The entries of the control
matching (rings) are a transversal: together with the input entries they cover every
row.
"""

# %%
# Natural and block-triangular order
# ----------------------------------
import matplotlib.pyplot as plt

import nocad
from nocad.datasets import load_nocad_example, make_hen_case_study
from nocad.viz import plot_structure_matrix

adj = load_nocad_example().adj
fig, axes = plt.subplots(1, 2, figsize=(9.0, 4.6))
plot_structure_matrix(adj, order="natural", ax=axes[0], title="natural order")
# [snippet:matrix]
plot_structure_matrix(adj, order="scc", ax=axes[1], title="SCC (block-triangular) order")
# [/snippet:matrix]
fig.tight_layout()

# %%
# Parameter study: the design method changes B and C
# --------------------------------------------------
# For the heat exchanger network every unit is a component with a self-loop on the
# diagonal; signal sharing and path finding give different input and output patterns.
hen = make_hen_case_study()
fig, axes = plt.subplots(1, 2, figsize=(11.0, 5.6))
for ax, method in zip(axes, ("path_finding", "signal_sharing"), strict=True):
    d = nocad.InputOutputDesign(method).fit(hen.adj)
    plot_structure_matrix(hen.adj, d.B_, d.C_, d.control_matching_, ax=ax, labels=hen.labels,
                          title=f"{method.replace('_', ' ')}: {d.n_inputs_} input(s), {d.n_outputs_} output(s)")
fig.tight_layout()

# %%
# **Take-away.** The block-triangular view connects the graph conditions with matrix
# language: diagonal blocks are components, the matching is a transversal, and the
# blocks without predecessors (successors) are where B (C) needs its entries.
