Source code for nocad.viz.maps

# SPDX-License-Identifier: MIT
# Copyright (c) 2026 János Abonyi, Dániel Leitold, Ágnes Vathy-Fogarassy
r"""Maps of the network: control and observation depth, regions, operability plane, roles."""

from __future__ import annotations

import numpy as np
from matplotlib import colors as mcolors
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Circle, Polygon

from .._graph import as_adjacency, resolve_labels, resolve_pos
from ..distances import (
    control_depth,
    control_regions,
    geodesic_distances,
    observation_depth,
    observation_regions,
)
from ..matching import edge_classes, maximum_matching, node_roles
from ..plotting import PALETTE, ROLE_COLORS, _ax, default_layout, draw_network, legend_handles

__all__ = [
    "depth_colormap",
    "plot_depth_map",
    "plot_operability_plane",
    "plot_distance_matrix",
    "plot_node_roles",
    "plot_edge_classes",
    "plot_robustness_map",
    "plot_annotation",
]


[docs] def depth_colormap(max_depth: int, kind: str = "control"): """Discrete sequential colormap for depths 0..max_depth (blues for control, oranges for observation).""" base = plt.get_cmap("Blues_r" if kind == "control" else "Oranges_r") m = max(int(max_depth), 1) cols = [base(0.08 + 0.72 * k / m) for k in range(m + 1)] return mcolors.ListedColormap(cols), mcolors.BoundaryNorm(np.arange(-0.5, m + 1.5), m + 1)
def _hull(points, pad): from scipy.spatial import ConvexHull, QhullError pts = np.asarray(points) if len(pts) >= 3: try: h = ConvexHull(pts) poly = pts[h.vertices] except QhullError: poly = pts else: poly = pts c = poly.mean(axis=0) ang = np.linspace(0, 2 * np.pi, 16, endpoint=False) ring = np.vstack([p + pad * np.column_stack([np.cos(ang), np.sin(ang)]) for p in poly]) try: h = ConvexHull(ring) return ring[h.vertices] except Exception: # noqa: BLE001 return c + pad * np.column_stack([np.cos(ang), np.sin(ang)])
[docs] def plot_depth_map( adj, nodes, kind: str = "control", pos=None, ax=None, regions: bool = True, labels=None, node_size=240, title=None, colorbar: bool = True, drivers=None, sensors=None, ): r"""Network colored by control depth :math:`\rho^C_i` (or observation depth :math:`\rho^O_i`). Every state is colored by its distance from the nearest driver node (to the nearest sensor node); the light hulls are the control (observation) regions, the sets of states that share their nearest driver (sensor). The largest depth is the relative order of the configuration; states that no driver reaches (that reach no sensor) are drawn white with a vermilion rim. Parameters ---------- nodes : array-like of int Driver nodes (``kind="control"``) or sensor nodes (``kind="observation"``). """ A = as_adjacency(adj) labels = resolve_labels(adj, labels) n = A.shape[0] pos = default_layout(A) if pos is None else resolve_pos(adj, pos) nodes = np.asarray(nodes, dtype=int) if kind == "control": depth, reg = control_depth(A, nodes), control_regions(A, nodes) else: depth, reg = observation_depth(A, nodes), observation_regions(A, nodes) finite = depth[np.isfinite(depth)] mx = int(finite.max()) if finite.size else 0 cmap, norm = depth_colormap(mx, kind) cols = [cmap(norm(d)) if np.isfinite(d) else "white" for d in depth] ax = _ax(ax, figsize=(5.6, 4.4)) if regions: for k, s in enumerate(nodes): idx = np.flatnonzero(reg == s) if idx.size == 0: continue col = PALETTE[k % len(PALETTE)] poly = _hull(pos[idx], 0.11) ax.add_patch(Polygon(poly, closed=True, fc=col, ec=col, alpha=0.10, lw=0, zorder=0.3)) ax.add_patch(Polygon(poly, closed=True, fill=False, ec=col, alpha=0.45, lw=0.9, zorder=0.4)) drivers = nodes if (drivers is None and kind == "control") else (drivers if drivers is not None else ()) sensors = nodes if (sensors is None and kind != "control") else (sensors if sensors is not None else ()) lab_col = ["white" if (np.isfinite(d) and d <= 0.55 * max(mx, 1)) else "#1F2A36" for d in depth] draw_network( A, pos, ax=ax, node_color=cols, labels=False, drivers=drivers, sensors=sensors, node_size=node_size, edge_color="#AAB4BE", ) if labels is not False: for i in range(n): fs = 7 if len(labels[i]) <= 3 else 5.8 ax.text( pos[i, 0], pos[i, 1], labels[i], ha="center", va="center", fontsize=fs, color=lab_col[i], fontweight="bold", zorder=3, ) lost = np.flatnonzero(~np.isfinite(depth)) if lost.size: ax.scatter( pos[lost, 0], pos[lost, 1], s=node_size, facecolors="white", edgecolors=ROLE_COLORS["critical"], linewidths=1.6, zorder=2.5, ) if colorbar: sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) cb = ax.figure.colorbar(sm, ax=ax, fraction=0.04, pad=0.02, ticks=range(mx + 1)) cb.set_label( "control depth $\\rho^C$" if kind == "control" else "observation depth $\\rho^O$", fontsize=8 ) cb.ax.tick_params(labelsize=7) cb.outline.set_visible(False) if title: ax.set_title(title, fontsize=10) return ax
def _spread(xs, ys, step=0.13): """Deterministic offsets for points sharing an integer coordinate (sunflower pattern).""" xs, ys = np.asarray(xs, float), np.asarray(ys, float) ox, oy = np.zeros_like(xs), np.zeros_like(ys) keys = {} for k, (a, b) in enumerate(zip(xs, ys, strict=True)): keys.setdefault((a, b), []).append(k) golden = np.pi * (3 - np.sqrt(5)) for idx in keys.values(): m = len(idx) for t, k in enumerate(idx): if m == 1: continue r = min(0.42, step * np.sqrt(m)) * np.sqrt((t + 0.5) / m) ox[k] = r * np.cos(t * golden) oy[k] = r * np.sin(t * golden) return xs + ox, ys + oy
[docs] def plot_operability_plane( adj, drivers, sensors, ax=None, labels=None, annotate: bool = True, r_max=None, title=None, axes=None ): r"""Every state in the plane of its control depth and observation depth. The sum :math:`\rho^C_i+\rho^O_i` is the length of the shortest input--output path through :math:`x_i`; the dotted diagonals are its level lines. States far up and to the right are slow both to steer and to see; the largest coordinates are the relative orders of the input and the output configuration. Marginal bars count the states at every depth. Parameters ---------- axes : dict with ``"main"``, ``"top"``, ``"right"`` axes, optional Draw into existing axes (``ax`` gets the marginal axes appended otherwise). Returns ------- axes : dict with ``"main"``, ``"top"`` and ``"right"`` axes. """ A = as_adjacency(adj) labels = resolve_labels(adj, labels) n = A.shape[0] if axes is not None: main, top, right = axes["main"], axes["top"], axes["right"] elif ax is None: fig = plt.figure(figsize=(5.0, 4.6)) gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4), wspace=0.05, hspace=0.05) main = fig.add_subplot(gs[1, 0]) top = fig.add_subplot(gs[0, 0], sharex=main) right = fig.add_subplot(gs[1, 1], sharey=main) else: from mpl_toolkits.axes_grid1 import make_axes_locatable main = ax div = make_axes_locatable(ax) top = div.append_axes("top", 0.6, pad=0.05, sharex=ax) right = div.append_axes("right", 0.6, pad=0.05, sharey=ax) dc, do = control_depth(A, drivers), observation_depth(A, sensors) both = np.r_[dc, do] big = (np.max(both[np.isfinite(both)]) if np.isfinite(both).any() else 0) + 1 dcp, dop = np.where(np.isfinite(dc), dc, big), np.where(np.isfinite(do), do, big) roles = np.full(n, "state", dtype=object) roles[np.asarray(drivers, int)] = "driver" so = np.asarray(sensors, int) roles[so] = np.where(roles[so] == "driver", "both", "sensor") x, y = _spread(dcp, dop) mx = int(max(dcp.max(), dop.max())) if n else 1 for s in range(0, 2 * mx + 1): main.plot([s + 0.5, -0.5], [-0.5, s + 0.5], ls=":", color="0.85", lw=0.8, zorder=0) names = {"state": "state", "driver": "driver node", "sensor": "sensor node", "both": "driver and sensor"} for role in ("state", "driver", "sensor", "both"): k = roles == role if k.any(): main.scatter( x[k], y[k], s=46, c=ROLE_COLORS[role], edgecolors="white", linewidths=0.7, zorder=3, label=names[role], ) if annotate and n <= 40 and labels is not False: for i in range(n): main.annotate( labels[i], (x[i], y[i]), xytext=(4, 3), textcoords="offset points", fontsize=6.5, color="0.3" ) if r_max is not None: main.axvline(r_max + 0.5, color=ROLE_COLORS["driver"], ls="--", lw=0.9) main.axhline(r_max + 0.5, color=ROLE_COLORS["sensor"], ls="--", lw=0.9) main.set_xlim(-0.6, mx + 0.6) main.set_ylim(-0.6, mx + 0.6) main.set_xticks(range(mx + 1)) main.set_yticks(range(mx + 1)) main.set_xlabel("control depth $\\rho^C_i$ (distance from the nearest driver)", fontsize=8) main.set_ylabel("observation depth $\\rho^O_i$ (distance to the nearest sensor)", fontsize=8) main.grid(True, color="0.93", lw=0.6) main.set_axisbelow(True) main.legend(frameon=True, framealpha=0.85, edgecolor="none", fontsize=7, loc="upper right") hc = np.bincount(dcp.astype(int), minlength=mx + 1) ho = np.bincount(dop.astype(int), minlength=mx + 1) top.bar(range(len(hc)), hc, color=ROLE_COLORS["driver"], alpha=0.75, width=0.7) right.barh(range(len(ho)), ho, color=ROLE_COLORS["sensor"], alpha=0.75, height=0.7) for a in (main, top, right): for s in ("top", "right"): a.spines[s].set_visible(False) a.tick_params(labelsize=6) plt.setp(top.get_xticklabels(), visible=False) plt.setp(right.get_yticklabels(), visible=False) top.set_ylabel("states", fontsize=7) right.set_xlabel("states", fontsize=7) if title: top.set_title(title, fontsize=10) return {"main": main, "top": top, "right": right}
[docs] def plot_distance_matrix(adj, nodes, kind: str = "control", ax=None, labels=None, title=None): r"""Distances between the configured nodes (columns) and the states (rows). Rows are sorted by region and depth, so that every driver (sensor) appears as a block of the states it serves first; cells are the number of derivations :math:`\ell+1` (the MATLAB ``controlling``/``observing`` matrices), empty where the node does not reach the state. """ A = as_adjacency(adj) labels = resolve_labels(adj, labels) n = A.shape[0] nodes = np.asarray(nodes, dtype=int) D = geodesic_distances(A) M = D[nodes, :].T if kind == "control" else D[:, nodes] depth = M.min(axis=1) reg = np.argmin(M, axis=1) order = np.lexsort((depth, reg)) vals = M[order] + 1 mx = int(np.nanmax(np.where(np.isfinite(vals), vals, 0))) if n else 1 cmap, norm = depth_colormap(mx, kind) ax = _ax(ax, figsize=(0.45 * nodes.size + 2.4, 0.18 * n + 1.2)) masked = np.ma.masked_invalid(np.where(np.isfinite(vals), vals - 1, np.nan)) im = ax.imshow(masked, aspect="auto", cmap=cmap, norm=norm, interpolation="nearest") ax.set_yticks(range(n)) ax.set_yticklabels([labels[i] for i in order], fontsize=6 if n > 30 else 7) ax.set_xticks(range(nodes.size)) sym = "u" if kind == "control" else "y" ax.set_xticklabels([f"${sym}_{{{k + 1}}}$\n{labels[v]}" for k, v in enumerate(nodes)], fontsize=7) for r in range(n): for c in range(nodes.size): if np.isfinite(vals[r, c]): ax.text( c, r, int(vals[r, c]), ha="center", va="center", fontsize=6, color="white" if vals[r, c] - 1 <= 0.55 * mx else "#1F2A36", ) cb = ax.figure.colorbar(im, ax=ax, fraction=0.05, pad=0.02, ticks=range(mx + 1)) cb.set_label("distance $\\ell$ (cell: derivations $\\ell+1$)", fontsize=7) cb.ax.tick_params(labelsize=6) cb.outline.set_visible(False) if title: ax.set_title(title, fontsize=10) return ax
[docs] def plot_node_roles(adj, pos=None, ax=None, labels=None, node_size=240, title=None, legend=True): r"""Network colored by the role of every node across all maximum matchings. Critical nodes (vermilion) are driver nodes in every minimum driver set, redundant nodes (gray) in none, intermittent nodes (blue) in some (Jia et al. 2013). """ A = as_adjacency(adj) labels = resolve_labels(adj, labels) pos = default_layout(A) if pos is None else resolve_pos(adj, pos) roles = node_roles(A) cmap = { "critical": ROLE_COLORS["critical"], "intermittent": ROLE_COLORS["driver"], "redundant": "#AEB8C2", } ax = draw_network( A, pos, ax=ax, node_color=[cmap[r] for r in roles], labels=labels, io_stubs=False, node_size=node_size ) if title: ax.set_title(title, fontsize=10) if legend: h = [ Line2D([0], [0], marker="o", ls="", ms=8, mfc=c, mec="white", label=f"{k} ({(roles == k).sum()})") for k, c in cmap.items() ] ax.legend(handles=h, frameon=False, fontsize=7, loc="upper left", bbox_to_anchor=(1.0, 1.0)) return ax
[docs] def plot_edge_classes(adj, pos=None, ax=None, labels=None, node_size=220, title=None, legend=True): """Network with every edge colored by its class across all maximum matchings.""" A = as_adjacency(adj) labels = resolve_labels(adj, labels) pos = default_layout(A) if pos is None else resolve_pos(adj, pos) cls = edge_classes(A, maximum_matching(A)) style = { "critical": {"color": ROLE_COLORS["matched"], "lw": 2.4, "alpha": 1.0}, "ordinary": {"color": ROLE_COLORS["attach"], "lw": 1.8, "alpha": 1.0}, "redundant": {"color": "#C3CAD2", "lw": 1.0, "ls": ":", "alpha": 1.0}, } hl = {e: style[c] for e, c in cls.items()} ax = draw_network( A, pos, ax=ax, node_color=ROLE_COLORS["state"], highlight=hl, labels=labels, io_stubs=False, node_size=node_size, label_color="#1F2A36", ) if title: ax.set_title(title, fontsize=10) if legend: counts = {k: sum(v == k for v in cls.values()) for k in style} h = [ Line2D([0], [0], color=s["color"], lw=s["lw"], ls=s.get("ls", "-"), label=f"{k} ({counts[k]})") for k, s in style.items() ] ax.legend(handles=h, frameon=False, fontsize=7, loc="upper left", bbox_to_anchor=(1.0, 1.0)) return ax
[docs] def plot_robustness_map( adj, result, kind: str = "control", pos=None, ax=None, labels=None, drivers=(), sensors=(), node_size=240, title=None, legend=True, ): """Network with the critical nodes of a configuration (from :func:`nocad.node_removal_robustness`).""" A = as_adjacency(adj) labels = resolve_labels(adj, labels) n = A.shape[0] pos = default_layout(A) if pos is None else resolve_pos(adj, pos) ok = result["controllable" if kind == "control" else "observable"] cols = [ROLE_COLORS["matched"] if ok[i] else ROLE_COLORS["critical"] for i in range(n)] ax = draw_network( A, pos, ax=ax, node_color=cols, labels=labels, drivers=drivers, sensors=sensors, node_size=node_size ) for i in np.asarray(drivers if kind == "control" else sensors, dtype=int): ax.add_patch(Circle(pos[i], 0.07, fill=False, ec=ROLE_COLORS["ink"], lw=1.0, zorder=3)) if title: ax.set_title(title, fontsize=10) if legend: word = "controllable" if kind == "control" else "observable" h = [ Line2D( [0], [0], marker="o", ls="", ms=8, mfc=ROLE_COLORS["matched"], mec="white", label=f"removable, stays {word}", ), Line2D( [0], [0], marker="o", ls="", ms=8, mfc=ROLE_COLORS["critical"], mec="white", label="critical" ), ] h += legend_handles(["driver"] if kind == "control" else ["sensor"])[:0] ax.legend(handles=h, frameon=False, fontsize=7, loc="upper left", bbox_to_anchor=(1.0, 1.0)) return ax
_CATEGORY_COLORS = { "driver": ROLE_COLORS["driver"], "sensor": ROLE_COLORS["sensor"], "driver+sensor": ROLE_COLORS["both"], "state": ROLE_COLORS["state"], "critical": ROLE_COLORS["critical"], "intermittent": ROLE_COLORS["driver"], "redundant": "#AEB8C2", "source": PALETTE[0], "external": PALETTE[4], "internal": PALETTE[2], "inaccessible": PALETTE[3], "stem": ROLE_COLORS["driver"], "bud": ROLE_COLORS["matched"], "unattached": ROLE_COLORS["critical"], "": "#D5DBE1", }
[docs] def plot_annotation( adj, column: str, annotation=None, pos=None, ax=None, labels=None, node_size=240, title=None, legend: bool = True, cmap=None, design=None, method: str = "path_finding", ): r"""Network with every node colored by a column of the annotation table. Parameters ---------- adj : network column : str A column of :func:`nocad.annotation.annotate` (``"io_role"``, ``"control_role"``, ``"driver_type"``, ``"control_cactus"``, ``"scc"``, ``"control_depth"``, ...). Text and boolean columns are drawn with fixed categorical colors, numeric columns with a sequential colormap (``-1``, unreachable, in white). annotation : Bunch or DataFrame, optional Result of :func:`~nocad.annotation.annotate` or its node table; computed (with ``design`` or ``method``) when omitted. pos : ndarray or dict, optional Positions (NetworkX-style dictionaries accepted). Returns ------- ax : matplotlib Axes """ from ..annotation import annotate A = as_adjacency(adj) labels = resolve_labels(adj, labels) if annotation is None: annotation = annotate(A, design=design, method=method, labels=labels if labels else None) nodes = annotation.nodes if hasattr(annotation, "nodes") else annotation pos = default_layout(A) if pos is None else resolve_pos(adj, pos) vals = nodes[column].to_numpy() numeric = vals.dtype.kind in "iuf" and column not in ("scc",) ax = _ax(ax, figsize=(5.6, 4.4)) drivers = np.flatnonzero(nodes["driver"].to_numpy()) if "driver" in nodes else () sensors = np.flatnonzero(nodes["sensor"].to_numpy()) if "sensor" in nodes else () if numeric: v = vals.astype(float) ok = v >= 0 vmax = max(v[ok].max(), 1.0) if ok.any() else 1.0 cm = plt.get_cmap(cmap or "Blues_r") norm = mcolors.Normalize(vmin=0, vmax=vmax * 1.25) cols = [cm(norm(x)) if x >= 0 else "white" for x in v] else: keys = [str(x) for x in vals] uniq = list(dict.fromkeys(keys)) if vals.dtype.kind == "b": cmap_ = {"True": ROLE_COLORS["brand"], "False": "#D5DBE1"} else: spare = iter(c for c in PALETTE if c not in _CATEGORY_COLORS.values()) cmap_ = {k: _CATEGORY_COLORS.get(k) or next(spare, "#999999") for k in uniq} if column == "scc": cmap_ = {k: PALETTE[i % len(PALETTE)] for i, k in enumerate(uniq)} cols = [cmap_[k] for k in keys] draw_network( A, pos, ax=ax, node_color=cols, labels=False, drivers=drivers, sensors=sensors, node_size=node_size ) if labels is not False: for i, (lab, c) in enumerate(zip(labels, cols, strict=True)): r, g, b = mcolors.to_rgb(c) ink = "white" if 0.299 * r + 0.587 * g + 0.114 * b < 0.6 else "#1F2A36" ax.text( pos[i, 0], pos[i, 1], lab, ha="center", va="center", color=ink, zorder=3, fontsize=7.5 if len(lab) <= 3 else 6.2, fontweight="bold", ) if numeric: sm = plt.cm.ScalarMappable(cmap=cm, norm=norm) cb = ax.figure.colorbar(sm, ax=ax, fraction=0.04, pad=0.02) cb.set_label(column.replace("_", " "), fontsize=8) cb.ax.tick_params(labelsize=7) cb.outline.set_visible(False) elif legend: h = [ Line2D( [0], [0], marker="o", ls="", ms=8, mfc=cmap_[k], mec="white", label=f"{k or '(none)'} ({keys.count(k)})", ) for k in uniq ] ax.legend( handles=h, frameon=False, fontsize=7, loc="upper left", bbox_to_anchor=(1.0, 1.0), title=column.replace("_", " "), title_fontsize=7.5, ) if title: ax.set_title(title, fontsize=10) return ax