"""
Control cacti: a picture of why a system is controllable
========================================================

Lin's theorem states that a structured system is controllable iff its graph is spanned
by *cacti*: a stem (a path starting at an input) with buds (cycles, each entered by one
extra edge) hanging from it. A design found by maximum matching contains such a
certificate: its matched edges form the stems and the cycles, and an edge from an
already attached node anchors every cycle. :func:`nocad.viz.control_cacti` extracts the
decomposition and :func:`nocad.viz.plot_control_cacti` draws every input on its own lane
with the buds hanging free of the stems; the observation cacti are drawn mirrored, the
stems running into the outputs.
"""

# %%
# The NOCAD example
# -----------------
import matplotlib.pyplot as plt

from nocad.datasets import load_nocad_example, make_cycle_example, make_hen_case_study
from nocad.viz import control_cacti, plot_control_cacti

adj = load_nocad_example().adj
# [snippet:cacti]
cacti = control_cacti(adj, method="path_finding")
for k, stem in enumerate(cacti.stems):
    print(f"u{k + 1}: stem", [f"x{v + 1}" for v in stem])
for bud, (u, v), owner in zip(cacti.buds, cacti.attach, cacti.owner, strict=True):
    print("bud", [f"x{w + 1}" for w in bud], f"attached by x{u + 1}->x{v + 1} to the cactus of u{owner + 1}")
# [/snippet:cacti]
fig, ax = plt.subplots(figsize=(6.0, 3.6))
plot_control_cacti(adj, ax=ax, title="control cactus of the NOCAD example")
fig, ax = plt.subplots(figsize=(6.0, 3.6))
plot_control_cacti(adj, kind="observation", ax=ax, title="observation cacti of the NOCAD example")

# %%
# Signal sharing: a bud fed by a shared input
# -------------------------------------------
# With signal sharing the perfectly matched source cycle is not opened; it hangs from
# the shared input itself (dotted arrow).
fig, axes = plt.subplots(1, 2, figsize=(8.4, 2.8))
cyc = make_cycle_example().adj
plot_control_cacti(cyc, method="signal_sharing", ax=axes[0], legend=False, title="signal sharing")
plot_control_cacti(cyc, method="path_finding", ax=axes[1], legend=False, title="path finding")
fig.tight_layout()

# %%
# Parameter study: a heat exchanger network
# -----------------------------------------
# Every heat exchanger cell of the network contributes a two-node cycle (hot and cold
# outlet temperatures) and every unit a self-loop; one input controls the whole network
# through a long stem with many buds. The exact minimum and path finding give the same
# number of stems here.
hen = make_hen_case_study()
for method in ("path_finding", "minimum"):
    c = control_cacti(hen.adj, method=method)
    print(f"{method:13s} stems={len(c.stems)} buds={len(c.buds)} deepest bud={max(c.depth, default=0)}")
fig, ax = plt.subplots(figsize=(9.0, 4.6))
plot_control_cacti(hen.adj, ax=ax, labels=hen.labels, node_size=300, show_other_edges=False,
                   title="control cactus of the heat exchanger network (cactus edges only)")

# %%
# **Take-away.** The cactus view turns a matching into a certificate a reader can check:
# every state lies on a stem or on a cycle that is anchored, directly or through other
# cycles, to a stem.
