Source code for nocad.viz.structure

# SPDX-License-Identifier: MIT
# Copyright (c) 2026 János Abonyi, Dániel Leitold, Ágnes Vathy-Fogarassy
r"""Structure views: SCC hierarchy, bipartite matching, control cacti and the system matrix."""

from __future__ import annotations

import numpy as np
import scipy.sparse as sp
from matplotlib.lines import Line2D
from matplotlib.patches import Circle, FancyArrowPatch, FancyBboxPatch, Rectangle

from .._graph import as_adjacency, edge_list, resolve_labels
from ..components import condensation
from ..design import InputOutputDesign, control_matching
from ..matching import Matching, edge_classes, maximum_matching
from ..plotting import ROLE_COLORS, _ax, _clean, draw_network, legend_handles
from .layouts import bipartite_layout, cactus_layout, control_cacti, hierarchy_layout

__all__ = ["plot_scc_hierarchy", "plot_bipartite_matching", "plot_control_cacti", "plot_structure_matrix"]


def _tex(label: str, sup: str) -> str:
    """``x12`` -> ``$x_{12}^{+}$``; other labels get the superscript appended."""
    import re

    m = re.fullmatch(r"([A-Za-z]+)(\d+)", label)
    if m:
        return f"${m.group(1)}_{{{m.group(2)}}}^{{{sup}}}$"
    return f"{label}$^{{{sup}}}$"


_TINT = {
    "source": ROLE_COLORS["driver"],
    "sink": ROLE_COLORS["sensor"],
    "both": ROLE_COLORS["both"],
    "inner": "#8A96A3",
}


[docs] def plot_scc_hierarchy( adj, drivers=None, sensors=None, direction: str = "control", matching=None, ax=None, labels=None, node_size=230, title=None, legend=True, level_labels=True, ): r"""Draw the network level by level on its condensation (see :func:`hierarchy_layout`). Strongly connected components are shaded: source components (they need a driver node) blue, sink components (they need a sensor node) vermilion, components that are both (isolated parts) purple. Driver and sensor nodes are computed with path finding when not given; ``drivers=()`` draws none. Returns ------- ax : matplotlib Axes """ A = as_adjacency(adj) labels = resolve_labels(adj, labels) if drivers is None or sensors is None: d = InputOutputDesign().fit(A) drivers = d.driver_nodes_ if drivers is None else drivers sensors = d.sensor_nodes_ if sensors is None else sensors lay = hierarchy_layout(A, direction=direction) cond = lay.condensation ax = _ax(ax, figsize=(6.2, 4.6)) is_src = np.isin(np.arange(cond.n_components), cond.sources) is_snk = np.isin(np.arange(cond.n_components), cond.sinks) for c in range(cond.n_components): kind = ( "both" if is_src[c] and is_snk[c] else "source" if is_src[c] else "sink" if is_snk[c] else "inner" ) col = _TINT[kind] r = lay.halo[c] if cond.sizes[c] > 1 or kind != "inner": ax.add_patch( Circle( lay.center[c], r, fc=col, ec=col, alpha=0.10 if kind != "inner" else 0.07, lw=0, zorder=0.5, ) ) ax.add_patch( Circle( lay.center[c], r, fill=False, ec=col, lw=0.9, alpha=0.55, ls="-" if cond.nontrivial[c] else ":", zorder=0.6, ) ) hl = {} if matching is not None: for a, b in matching.edges: hl[(int(a), int(b))] = {"color": ROLE_COLORS["matched"], "lw": 2.2, "alpha": 1.0} lab = cond.labels for a, b in edge_list(A): if lab[a] != lab[b] and (int(a), int(b)) not in hl: hl[(int(a), int(b))] = {"color": "#5D6B79", "lw": 1.0} n_inner = sum(1 for a, b in edge_list(A) if lab[a] == lab[b] and a != b) inner_alpha = float(min(0.9, max(0.12, 40.0 / max(n_inner, 1)))) draw_network( A, lay.pos, ax=ax, drivers=drivers, sensors=sensors, highlight=hl, labels=labels, node_size=node_size, edge_color="#B7C0C9", edge_alpha=inner_alpha, ) pad = 0.6 ax.set_xlim(lay.pos[:, 0].min() - pad - (0.9 if level_labels else 0), lay.pos[:, 0].max() + pad) ax.set_ylim(lay.pos[:, 1].min() - pad, lay.pos[:, 1].max() + pad) if level_labels and lay.levels: x0 = lay.pos[:, 0].min() - pad - 0.5 for lv in range(len(lay.levels)): ax.text(x0, lay.level_y[lv], f"level {lv}", fontsize=7, color="0.45", ha="center", va="center") if title: ax.set_title(title, fontsize=10) if legend: handles = [ Line2D( [0], [0], marker="o", ls="", ms=11, mfc=_TINT["source"], alpha=0.25, mec=_TINT["source"], label="source SCC", ), Line2D( [0], [0], marker="o", ls="", ms=11, mfc=_TINT["sink"], alpha=0.25, mec=_TINT["sink"], label="sink SCC", ), ] handles += legend_handles( ["driver", "sensor", "state"] + (["matched"] if matching is not None else []) ) ax.legend(handles=handles, frameon=False, fontsize=7, loc="upper left", bbox_to_anchor=(1.0, 1.0)) return ax
[docs] def plot_bipartite_matching( adj, matching: Matching | None = None, classes: bool = True, ax=None, labels=None, title=None, legend=True ): r"""Bipartite representation with a maximum matching and the edge classes. Out-copies :math:`x_j^+` on the left, in-copies :math:`x_i^-` on the right (see :func:`bipartite_layout`). Matched edges are thick; with ``classes`` the color tells whether an edge is in every maximum matching (critical, green), in some (ordinary, orange) or in none (redundant, light gray, dotted). Unmatched in-copies receive an input arrow: they are the driver nodes of this matching. """ A = as_adjacency(adj) labels = resolve_labels(adj, labels) n = A.shape[0] m = matching if matching is not None else maximum_matching(A) lay = bipartite_layout(A, m) cls = edge_classes(A, m) if classes else {} ax = _ax(ax, figsize=(3.6, 0.42 * n + 1.0)) _clean(ax) ax.set_aspect("auto") colors = {"critical": ROLE_COLORS["matched"], "ordinary": ROLE_COLORS["attach"], "redundant": "#C3CAD2"} for a, b in edge_list(A): a, b = int(a), int(b) matched = m.matched_by[b] == a c = colors[cls[(a, b)]] if classes else (ROLE_COLORS["matched"] if matched else "#9AA5B1") ls = ":" if classes and cls[(a, b)] == "redundant" else "-" ax.add_line( Line2D( [lay.out_pos[a, 0], lay.in_pos[b, 0]], [lay.out_pos[a, 1], lay.in_pos[b, 1]], color=c, lw=2.6 if matched else 1.0, ls=ls, zorder=1 if not matched else 2, solid_capstyle="round", ) ) unmatched = set(int(i) for i in m.unmatched) for i in range(n): ax.scatter(*lay.out_pos[i], s=150, c="#5D6B79", edgecolors="white", zorder=3) col = ROLE_COLORS["driver"] if i in unmatched else "#5D6B79" ax.scatter(*lay.in_pos[i], s=150, c=col, edgecolors="white", zorder=3) ax.text( lay.out_pos[i, 0] - 0.12, lay.out_pos[i, 1], _tex(labels[i], "+"), ha="right", va="center", fontsize=8, ) ax.text( lay.in_pos[i, 0] + 0.12, lay.in_pos[i, 1], _tex(labels[i], "-"), ha="left", va="center", fontsize=8, color=col if i in unmatched else "black", ) if i in unmatched: ax.add_patch( FancyArrowPatch( lay.in_pos[i] + np.array([0.18, -0.62]), lay.in_pos[i], arrowstyle="-|>", mutation_scale=9, shrinkB=7, color=ROLE_COLORS["driver"], lw=1.4, ) ) ax.text(0, 0.8, "out-copies", ha="center", fontsize=8, color="0.35") ax.text(1, 0.8, "in-copies", ha="center", fontsize=8, color="0.35") ax.set_xlim(-0.75, 1.95) ax.set_ylim(-n + 0.4, 1.2) if title: ax.set_title(title, fontsize=10) if legend and classes: h = [ Line2D([0], [0], color=colors["critical"], lw=2.2, label="critical"), Line2D([0], [0], color=colors["ordinary"], lw=2.2, label="ordinary"), Line2D([0], [0], color=colors["redundant"], lw=1.2, ls=":", label="redundant"), Line2D([0], [0], color="0.3", lw=2.6, label="matched (thick)"), ] ax.legend(handles=h, frameon=False, fontsize=7, loc="upper center", bbox_to_anchor=(0.5, 0.0), ncol=2) return ax
[docs] def plot_control_cacti( adj, method: str = "path_finding", kind: str = "control", ax=None, labels=None, show_other_edges: bool = True, node_size=230, title=None, legend=True, cacti=None, ): r"""Draw the control (observation) cacti of a design (see :func:`control_cacti`). Every input :math:`u_l` starts a lane with its stem; buds hang from the node whose edge (orange, dashed) attaches them; edges outside the cacti are faint. For ``kind="observation"`` the cacti of the reversed network are drawn mirrored, so the stems run into the outputs :math:`y_k` on the right and all arrows keep their original direction. """ A = as_adjacency(adj) labels = resolve_labels(adj, labels) n = A.shape[0] G = A if kind == "control" else sp.csr_array(A.T) if cacti is None: m, shared = control_matching(G, method) cacti = control_cacti(G, matching=m, shared=shared) lay = cactus_layout(cacti, n) pos = lay.pos.copy() inputs = lay.inputs.copy() sign = 1.0 if kind == "control" else -1.0 pos[:, 0] *= sign inputs[:, 0] *= sign ax = _ax(ax, figsize=(6.0, 3.6)) flip = (lambda a, b: (a, b)) if kind == "control" else (lambda a, b: (b, a)) hl = {} for stem in cacti.stems: for a, b in zip(stem[:-1], stem[1:], strict=True): hl[flip(a, b)] = { "color": ROLE_COLORS["driver"] if kind == "control" else ROLE_COLORS["sensor"], "lw": 2.4, "alpha": 1.0, } for cyc in cacti.buds: for a, b in zip(cyc, cyc[1:] + cyc[:1], strict=True): hl[flip(a, b)] = {"color": ROLE_COLORS["matched"], "lw": 2.2, "alpha": 1.0} for u, v in cacti.attach: if u >= 0: hl[flip(u, v)] = {"color": ROLE_COLORS["attach"], "lw": 1.8, "ls": "--", "alpha": 1.0} keep = A.copy() if not show_other_edges: M = sp.lil_array(A.shape, dtype=bool) for a, b in hl: M[a, b] = True keep = sp.csr_array(M) unattached_nodes = [v for b in cacti.unattached for v in cacti.buds[b]] colors = [ROLE_COLORS["state"]] * n for stem in cacti.stems: colors[stem[0]] = ROLE_COLORS["driver"] if kind == "control" else ROLE_COLORS["sensor"] for v in cacti.shared: colors[v] = ROLE_COLORS["driver"] if kind == "control" else ROLE_COLORS["sensor"] for v in unattached_nodes: colors[v] = "#F2C8B6" draw_network( keep, pos, ax=ax, node_color=colors, highlight=hl, labels=labels, node_size=node_size, edge_color="#D3D9DF", edge_alpha=0.9, io_stubs=False, curved_symmetric=True, ) io_col = ROLE_COLORS["driver"] if kind == "control" else ROLE_COLORS["sensor"] sym = "u" if kind == "control" else "y" r_node = np.sqrt(node_size) / 2 for k, (stem, p) in enumerate(zip(cacti.stems, inputs, strict=True)): ax.add_patch( FancyBboxPatch( p - 0.13, 0.26, 0.26, boxstyle="round,pad=0.02", fc="white", ec=io_col, lw=1.4, zorder=3 ) ) ax.text(*p, f"${sym}_{{{k + 1}}}$", ha="center", va="center", fontsize=8, color=io_col, zorder=4) a, b = (p, pos[stem[0]]) if kind == "control" else (pos[stem[0]], p) ax.add_patch( FancyArrowPatch( a, b, arrowstyle="-|>", mutation_scale=9, color=io_col, lw=1.6, shrinkA=9 if kind == "control" else r_node + 1, shrinkB=r_node + 1.5 if kind == "control" else 9, zorder=2.5, ) ) for v in cacti.shared: p = inputs[0] a, b = (p, pos[v]) if kind == "control" else (pos[v], p) ax.add_patch( FancyArrowPatch( a, b, arrowstyle="-|>", mutation_scale=9, color=io_col, lw=1.2, ls=":", shrinkA=9, shrinkB=r_node + 1.5, connectionstyle="arc3,rad=-0.2", zorder=2.5, ) ) for b in cacti.unattached: ax.add_patch( Circle( lay.bud_center[b] * np.array([sign, 1]), lay.bud_radius[b] + 0.25, fill=False, ec=ROLE_COLORS["critical"], ls="--", lw=1.2, ) ) allp = np.vstack([pos, inputs]) if inputs.size else pos ax.set_xlim(np.nanmin(allp[:, 0]) - 0.5, np.nanmax(allp[:, 0]) + 0.5) ax.set_ylim(np.nanmin(allp[:, 1]) - 0.5, np.nanmax(allp[:, 1]) + 0.5) if title: ax.set_title(title, fontsize=10) if legend: word = "stem" if kind == "control" else "stem (to output)" h = [ Line2D([0], [0], color=io_col, lw=2.4, label=word), Line2D([0], [0], color=ROLE_COLORS["matched"], lw=2.2, label="bud (cycle)"), Line2D([0], [0], color=ROLE_COLORS["attach"], lw=1.8, ls="--", label="attaching edge"), Line2D([0], [0], color="#D3D9DF", lw=1.2, label="other edge"), ] ax.legend(handles=h, frameon=False, fontsize=7, loc="upper left", bbox_to_anchor=(1.0, 1.0)) return ax
[docs] def plot_structure_matrix( adj, B=None, C=None, matching: Matching | None = None, order: str = "scc", ax=None, labels=None, title=None, design: str = "path_finding", ): r"""Zero pattern of the system matrix :math:`\left[\begin{smallmatrix}\mathbf{A}&\mathbf{B}\\ \mathbf{C}&\mathbf{0}\end{smallmatrix}\right]` in block-triangular order. Rows are the equations :math:`\dot x_i`, columns the states :math:`x_j`. With ``order="scc"`` states are sorted by a topological order of the strongly connected components (source components first), so :math:`\mathbf{A}` becomes block lower triangular and the diagonal blocks are the components; the entries of the control matching (green rings) form a transversal that, completed by the entries of :math:`\mathbf{B}`, covers every row: the generic-rank condition of Lin's theorem. Source blocks are outlined blue (they need a non-zero in :math:`\mathbf{B}`), sink blocks vermilion (they need a non-zero in :math:`\mathbf{C}`). Parameters ---------- B, C : array-like, optional Input and output matrices; designed by ``design`` when omitted. order : {"scc", "natural"} """ A = as_adjacency(adj) labels = resolve_labels(adj, labels) n = A.shape[0] if B is None or C is None: d = InputOutputDesign(design).fit(A) B = d.B_ if B is None else B C = d.C_ if C is None else C matching = d.control_matching_ if matching is None else matching if matching is None: matching = control_matching(A, design)[0] B = sp.csr_array(B) if sp.issparse(B) else sp.csr_array(np.atleast_2d(np.asarray(B, dtype=float))) C = sp.csr_array(C) if sp.issparse(C) else sp.csr_array(np.atleast_2d(np.asarray(C, dtype=float))) cond = condensation(A) perm = np.lexsort((np.arange(n), cond.labels)) if order == "scc" else np.arange(n) inv = np.empty(n, dtype=int) inv[perm] = np.arange(n) M, K = B.shape[1], C.shape[0] ax = _ax(ax, figsize=(0.32 * (n + M) + 1.6, 0.32 * (n + K) + 1.4)) _clean(ax) gap = 0.6 matched = {(int(j), int(i)) for j, i in matching.edges} def cell(r, c, fc, ec="none", ring=False): ax.add_patch(Rectangle((c + 0.12, -r - 0.88), 0.76, 0.76, fc=fc, ec=ec, lw=0.8, zorder=2)) if ring: ax.add_patch( Circle((c + 0.5, -r - 0.5), 0.5, fill=False, ec=ROLE_COLORS["matched"], lw=1.6, zorder=3) ) # diagonal blocks for comp in range(cond.n_components): rows = np.sort(inv[cond.members[comp]]) lo, hi = rows.min(), rows.max() + 1 src, snk = comp in set(cond.sources), comp in set(cond.sinks) ec = ( ROLE_COLORS["both"] if src and snk else ROLE_COLORS["driver"] if src else ROLE_COLORS["sensor"] if snk else "#9AA5B1" ) ax.add_patch( Rectangle( (lo, -hi), hi - lo, hi - lo, fc="#EEF1F4" if cond.nontrivial[comp] else "none", ec=ec, lw=1.3 if (src or snk) else 0.6, zorder=1, ) ) for j, i in edge_list(A): # a_ij != 0 : row i, column j cell(inv[i], inv[j], "#5D6B79", ring=(int(j), int(i)) in matched) Bc = sp.coo_array(B) for i, l in zip(Bc.row, Bc.col, strict=True): cell(inv[i], n + gap + l, ROLE_COLORS["driver"]) Cc = sp.coo_array(C) for k, j in zip(Cc.row, Cc.col, strict=True): cell(n + gap + k, inv[j], ROLE_COLORS["sensor"]) # frame and labels ax.add_patch(Rectangle((0, -n), n, n, fill=False, ec="0.3", lw=0.8)) if M: ax.add_patch(Rectangle((n + gap, -n), M, n, fill=False, ec=ROLE_COLORS["driver"], lw=0.8)) if K: ax.add_patch(Rectangle((0, -n - gap - K), n, K, fill=False, ec=ROLE_COLORS["sensor"], lw=0.8)) for r in range(n): lab = labels[perm[r]] ax.text(-0.25, -r - 0.5, lab, ha="right", va="center", fontsize=6.5) ax.text(r + 0.5, 0.25, lab, ha="center", va="bottom", fontsize=6.5, rotation=90) for l in range(M): ax.text( n + gap + l + 0.5, 0.25, f"$u_{{{l + 1}}}$", ha="center", va="bottom", fontsize=7, color=ROLE_COLORS["driver"], ) for k in range(K): ax.text( -0.25, -n - gap - k - 0.5, f"$y_{{{k + 1}}}$", ha="right", va="center", fontsize=7, color=ROLE_COLORS["sensor"], ) ax.set_xlim(-1.4, n + gap + M + 0.3) ax.set_ylim(-n - gap - K - 0.3, 1.6) if title: ax.set_title(title, fontsize=10, pad=18) return ax