Skip to content
Edit this page

ictdesigntools.draw.graph

Network topologies: graphs drawn with their attributes, and routes through them highlighted.

A graph comes in from anywhere: a networkx graph (read by duck typing, so networkx is never imported), node-link JSON as networkx.node_link_data writes it, or this module's Graph. Nodes are placed by a given pos (any networkx layout) or by a layout here: layered puts nodes in rows by an attribute (tier, subset) and orders each row to reduce crossings, as for Clos and leaf-spine fabrics; tree spreads a point-to-multipoint network such as GPON from its root. topology turns it into a Drawing: nodes and edges styled by an attribute (role → colour, media → line), labels from templates ("{name}", "{speed}"), edges straight or orthogonal with separate lanes, routes (node paths, as nx.shortest_path returns) drawn over the graph in their own colours, and a legend. Every node, edge and route carries a Meta with its attributes for to_svg(interactive=True).

>>> g = Graph()
>>> g.add_edge("spine1", "leaf1", speed="400G"); g.add_edge("spine1", "leaf2", speed="400G")
>>> for n in ("spine1",): g.nodes[n]["tier"] = 0
>>> for n in ("leaf1", "leaf2"): g.nodes[n]["tier"] = 1
>>> d = topology(g, layer_key="tier", routes=[Route(["leaf1", "spine1", "leaf2"])])
>>> d.title
'Topology: 3 nodes, 2 edges'

Graph dataclass

Graph(
    nodes: dict[Hashable, dict[str, Any]] = dict(),
    edges: list[Edge] = list(),
    directed: bool = False,
    multigraph: bool = False,
)

Nodes with attributes and edges between them; enough of networkx's shape to draw.

to_networkx

to_networkx()

A networkx graph of the same kind (needs networkx).

Source code in src/ictdesigntools/draw/graph.py
def to_networkx(self):
    """A networkx graph of the same kind (needs networkx)."""
    import networkx as nx

    kind = {(False, False): nx.Graph, (True, False): nx.DiGraph,
            (False, True): nx.MultiGraph, (True, True): nx.MultiDiGraph}  # fmt: skip
    g = kind[self.directed, self.multigraph]()
    g.add_nodes_from(self.nodes.items())
    for e in self.edges:
        if self.multigraph:
            g.add_edge(e.u, e.v, key=e.key, **e.attrs)
        else:
            g.add_edge(e.u, e.v, **e.attrs)
    return g

Route dataclass

Route(
    path: Sequence[Hashable] | Sequence[tuple],
    name: str = "",
    style: str = "",
)

A path to highlight: nodes in order (nx.shortest_path), or edges as (u, v) or (u, v, key). style names a drawing style; left empty, routes take colours in turn.

from_networkx

from_networkx(G) -> Graph

A Graph from anything shaped like a networkx graph (nodes(data=True), edges(data=True), is_directed(), is_multigraph()).

Source code in src/ictdesigntools/draw/graph.py
def from_networkx(G) -> Graph:
    """A ``Graph`` from anything shaped like a networkx graph (``nodes(data=True)``,
    ``edges(data=True)``, ``is_directed()``, ``is_multigraph()``)."""
    multi = bool(G.is_multigraph())
    g = Graph(directed=bool(G.is_directed()), multigraph=multi)
    for n, attrs in G.nodes(data=True):
        g.add_node(n, **dict(attrs))
    if multi:
        for u, v, k, attrs in G.edges(keys=True, data=True):
            g.edges.append(Edge(u, v, k, dict(attrs)))
    else:
        for u, v, attrs in G.edges(data=True):
            g.edges.append(Edge(u, v, None, dict(attrs)))
    return g
from_node_link(
    data: Mapping[str, Any],
    source: str = "source",
    target: str = "target",
    name: str = "id",
    key: str = "key",
    edges: str | None = None,
) -> Graph

A Graph from node-link data, as networkx.node_link_data writes it (edges under edges, or links in older files).

Source code in src/ictdesigntools/draw/graph.py
def from_node_link(data: Mapping[str, Any], source: str = "source", target: str = "target",
                   name: str = "id", key: str = "key",
                   edges: str | None = None) -> Graph:  # fmt: skip
    """A ``Graph`` from node-link data, as ``networkx.node_link_data`` writes it (edges under
    ``edges``, or ``links`` in older files)."""
    edges = edges or ("edges" if "edges" in data else "links")
    g = Graph(directed=bool(data.get("directed")), multigraph=bool(data.get("multigraph")))
    for node in data.get("nodes", []):
        attrs = {k: v for k, v in node.items() if k != name}
        g.add_node(node[name], **attrs)
    for link in data.get(edges, []):
        attrs = {k: v for k, v in link.items() if k not in (source, target, key)}
        g.add_node(link[source])
        g.add_node(link[target])
        g.edges.append(Edge(link[source], link[target], link.get(key), attrs))
    return g
to_node_link(g: Graph) -> dict[str, Any]

Node-link data that networkx.node_link_graph(data, edges="edges") reads back.

Source code in src/ictdesigntools/draw/graph.py
def to_node_link(g: Graph) -> dict[str, Any]:
    """Node-link data that ``networkx.node_link_graph(data, edges="edges")`` reads back."""
    links = []
    for e in g.edges:
        link = {"source": e.u, "target": e.v, **e.attrs}
        if g.multigraph:
            link["key"] = e.key
        links.append(link)
    return {"directed": g.directed, "multigraph": g.multigraph, "graph": {},
            "nodes": [{"id": n, **a} for n, a in g.nodes.items()], "edges": links}  # fmt: skip

as_graph

as_graph(obj) -> Graph

A Graph from a Graph, node-link data or a networkx-shaped graph.

Source code in src/ictdesigntools/draw/graph.py
def as_graph(obj) -> Graph:
    """A ``Graph`` from a ``Graph``, node-link data or a networkx-shaped graph."""
    if isinstance(obj, Graph):
        return obj
    if isinstance(obj, Mapping):
        return from_node_link(obj)
    if hasattr(obj, "nodes") and hasattr(obj, "edges") and hasattr(obj, "is_directed"):
        return from_networkx(obj)
    raise TypeError(f"Cannot read a graph from {type(obj).__name__}.")

layered

layered(
    g: Graph,
    key="tier",
    order: Sequence[Any] | None = None,
    sweeps: int = 8,
) -> dict[Hashable, tuple[float, float]]

Rows by the attribute key (or a dict of layer → nodes, or a function of node and attributes), in order or sorted; each row ordered to reduce crossings by alternating barycentre sweeps, and centred on the widest row.

Source code in src/ictdesigntools/draw/graph.py
def layered(g: Graph, key="tier", order: Sequence[Any] | None = None,
            sweeps: int = 8) -> dict[Hashable, tuple[float, float]]:  # fmt: skip
    """Rows by the attribute ``key`` (or a dict of layer → nodes, or a function of node and
    attributes), in ``order`` or sorted; each row ordered to reduce crossings by alternating
    barycentre sweeps, and centred on the widest row."""
    layer = _layer_of(g, key)
    layers = _sort_layers(layer.values(), order)
    rows: list[list[Hashable]] = [[n for n in g.nodes if layer[n] == lv] for lv in layers]
    nbrs = g.neighbours()
    row_of = {n: i for i, row in enumerate(rows) for n in row}

    def reorder(i: int, ref: list[int]) -> None:
        index = {n: k for r in ref for k, n in enumerate(rows[r])}

        def bary(n):  # noqa: E306
            ks = [index[m] for m in nbrs[n] if row_of[m] in ref]
            return sum(ks) / len(ks) if ks else None

        current = {n: k for k, n in enumerate(rows[i])}
        scored = [(bary(n), current[n], n) for n in rows[i]]
        # Nodes with no neighbour in the reference rows keep their place.
        fixed = sorted(s for s in scored if s[0] is None)
        moving = sorted((s for s in scored if s[0] is not None), key=lambda s: (s[0], s[1]))
        out: list = [None] * len(scored)
        for s in fixed:
            out[s[1]] = s[2]
        it = iter(moving)
        rows[i] = [x if x is not None else next(it)[2] for x in out]

    best = [list(r) for r in rows]
    best_cross = crossings(rows, nbrs, row_of)
    for s in range(sweeps):
        span = range(1, len(rows)) if s % 2 == 0 else range(len(rows) - 2, -1, -1)
        for i in span:
            reorder(i, [i - 1] if s % 2 == 0 else [i + 1])
        c = crossings(rows, nbrs, row_of)
        if c < best_cross:
            best, best_cross = [list(r) for r in rows], c
    widest = max((len(r) for r in best), default=0)
    return {n: (k + (widest - len(row)) / 2, i) for i, row in enumerate(best)
            for k, n in enumerate(row)}  # fmt: skip

crossings

crossings(rows, nbrs, row_of) -> int

Edge crossings between adjacent rows (edges that skip rows are not counted).

Source code in src/ictdesigntools/draw/graph.py
def crossings(rows, nbrs, row_of) -> int:
    """Edge crossings between adjacent rows (edges that skip rows are not counted)."""
    total = 0
    for i in range(len(rows) - 1):
        pos_a = {n: k for k, n in enumerate(rows[i])}
        pos_b = {n: k for k, n in enumerate(rows[i + 1])}
        pairs = sorted((pos_a[u], pos_b[v]) for u in rows[i] for v in nbrs[u]
                       if row_of.get(v) == i + 1)  # fmt: skip
        for a in range(len(pairs)):
            for b in range(a + 1, len(pairs)):
                if pairs[a][0] < pairs[b][0] and pairs[a][1] > pairs[b][1]:
                    total += 1
    return total

tree

A tree spread from root (or several roots side by side): each leaf its own column, each parent centred over its children, rows by distance from the root.

Source code in src/ictdesigntools/draw/graph.py
def tree(g: Graph, root: Hashable | Sequence[Hashable]) -> dict[Hashable, tuple[float, float]]:
    """A tree spread from ``root`` (or several roots side by side): each leaf its own column,
    each parent centred over its children, rows by distance from the root."""
    roots = [root] if root in g.nodes else list(root)
    nbrs = g.neighbours()
    depth: dict[Hashable, int] = {}
    children: dict[Hashable, list[Hashable]] = defaultdict(list)
    for r in roots:
        depth[r] = 0
    frontier = list(roots)
    while frontier:
        nxt = []
        for n in frontier:
            for m in sorted(nbrs[n], key=_natural):
                if m not in depth:
                    depth[m] = depth[n] + 1
                    children[n].append(m)
                    nxt.append(m)
        frontier = nxt
    pos: dict[Hashable, tuple[float, float]] = {}
    column = [0.0]

    def place(n) -> float:
        kids = children[n]
        if not kids:
            x = column[0]
            column[0] += 1
        else:
            xs = [place(k) for k in kids]
            x = (xs[0] + xs[-1]) / 2
        pos[n] = (x, depth[n])
        return x

    for r in roots:
        place(r)
    for n in g.nodes:  # unreachable nodes go in a row underneath
        if n not in pos:
            pos[n] = (column[0], max(depth.values(), default=0) + 1)
            column[0] += 1
    return pos

label

label(
    template: str | Callable | None,
    n_or_e,
    attrs: Mapping[str, Any],
) -> str

A label from a template such as "{name} · {speed}" (missing fields come out empty) or a function of the node (or edge) and its attributes.

Source code in src/ictdesigntools/draw/graph.py
def label(template: str | Callable | None, n_or_e, attrs: Mapping[str, Any]) -> str:
    """A label from a template such as ``"{name} · {speed}"`` (missing fields come out empty)
    or a function of the node (or edge) and its attributes."""
    if template is None:
        return ""
    if callable(template):
        return str(template(n_or_e, attrs))
    values = _Blank({"id": n_or_e, **attrs})
    try:
        text = Formatter().vformat(template, (), values)
    except ValueError, TypeError:  # a format spec that doesn't suit a missing value
        text = Formatter().vformat(re.sub(r"\{(\w+)[^}]*\}", r"{\1}", template), (), values)
    return text.strip(" ·-")

topology

topology(
    graph,
    pos: Mapping[Hashable, tuple[float, float]]
    | None = None,
    *,
    layout: str | Callable = "layered",
    layer_key="tier",
    layer_order=None,
    root=None,
    direction: str = "down",
    node_size: tuple[float, float] = (36.0, 12.0),
    gap: tuple[float, float] = (8.0, 26.0),
    node_label="{id}",
    node_style=None,
    node_shape: Mapping[str, str] | None = None,
    edge_label=None,
    edge_style=None,
    edge_width: Callable | None = None,
    routing: str = "auto",
    merge_parallel: bool = True,
    routes: Sequence[Route] = (),
    styles: Mapping[str, Style] | None = None,
    legend: bool = True,
    title: str = "",
    flip_y: bool = True,
) -> Drawing

A drawing of a graph in millimetres.

Placement: pos from any networkx layout (y up, flipped unless flip_y is False), else layout: "layered" by layer_key (default tier), "tree" from root, or a function of the graph returning grid positions. direction "down" or "right".

Look: node_style / edge_style name an attribute (or a function) whose value picks the style node-<value> / edge-<value>; values without a style in styles get colours in turn. node_shape maps those values to "rect" or "circle". edge_width(edge, attrs) sets a line width in mm. node_label and edge_label are templates ("{name}", "{speed} · {length_m:g} m") or functions.

Edges: routing "orthogonal" (through the gap between rows, parallel runs in separate lanes; for layered and tree layouts) or "straight"; parallel edges are drawn once with a count unless merge_parallel is False. Directed graphs get arrowheads.

routes are drawn over the graph, each in its own colour, with Meta kind route.

Source code in src/ictdesigntools/draw/graph.py
def topology(graph, pos: Mapping[Hashable, tuple[float, float]] | None = None, *,
             layout: str | Callable = "layered", layer_key="tier", layer_order=None,
             root=None, direction: str = "down",
             node_size: tuple[float, float] = (36.0, 12.0), gap: tuple[float, float] = (8.0, 26.0),
             node_label="{id}", node_style=None, node_shape: Mapping[str, str] | None = None,
             edge_label=None, edge_style=None, edge_width: Callable | None = None,
             routing: str = "auto", merge_parallel: bool = True,
             routes: Sequence[Route] = (), styles: Mapping[str, Style] | None = None,
             legend: bool = True, title: str = "", flip_y: bool = True) -> Drawing:  # fmt: skip
    """A drawing of a graph in millimetres.

    Placement: ``pos`` from any networkx layout (y up, flipped unless ``flip_y`` is False), else
    ``layout``: ``"layered"`` by ``layer_key`` (default ``tier``), ``"tree"`` from ``root``, or a
    function of the graph returning grid positions. ``direction`` ``"down"`` or ``"right"``.

    Look: ``node_style`` / ``edge_style`` name an attribute (or a function) whose value picks
    the style ``node-<value>`` / ``edge-<value>``; values without a style in ``styles`` get
    colours in turn. ``node_shape`` maps those values to ``"rect"`` or ``"circle"``.
    ``edge_width(edge, attrs)`` sets a line width in mm. ``node_label`` and ``edge_label`` are
    templates (``"{name}"``, ``"{speed} · {length_m:g} m"``) or functions.

    Edges: ``routing`` ``"orthogonal"`` (through the gap between rows, parallel runs in separate
    lanes; for layered and tree layouts) or ``"straight"``; parallel edges are drawn once with a
    count unless ``merge_parallel`` is False. Directed graphs get arrowheads.

    ``routes`` are drawn over the graph, each in its own colour, with ``Meta`` kind ``route``."""
    g = as_graph(graph)
    nw, nh = node_size
    gx, gy = gap
    styles = dict(styles or {})

    # Placement, in mm, y down; ``down`` frames are transposed at the end for ``right``.
    across, along = (nw, nh) if direction == "down" else (nh, nw)
    if pos is not None:
        pts = {n: (float(x), -float(y) if flip_y else float(y)) for n, (x, y) in pos.items()}
        xs, ys = [p[0] for p in pts.values()], [p[1] for p in pts.values()]
        spread = max(max(xs) - min(xs), max(ys) - min(ys)) or 1.0
        nearest = min((math.hypot(a[0] - b[0], a[1] - b[1]) for i, a in enumerate(pts.values())
                       for b in list(pts.values())[i + 1:]), default=spread) or spread  # fmt: skip
        k = max(nw + gx, nh + gy) * 1.15 / nearest
        k = min(k, 12 * max(nw, nh) * math.sqrt(len(pts)) / spread)
        centre = {n: ((x - min(xs)) * k, (y - min(ys)) * k) for n, (x, y) in pts.items()}
        grid = None
        routing = "straight"
    else:
        if callable(layout):
            grid = layout(g)
        elif layout == "tree":
            if root is None:
                raise ValueError("A tree layout needs a root.")
            grid = tree(g, root)
        else:
            grid = layered(g, layer_key, layer_order)
        centre = {n: (c * (across + gx), r * (along + gy)) for n, (c, r) in grid.items()}

    def frame(x, y):
        return (x, y) if direction == "down" else (y, x)

    # Styles from attribute values.
    def ensure(prefix: str, value: str | None, base: Callable[[str], Style]) -> str:
        if value is None:
            return prefix
        name = f"{prefix}-{_key(value)}"
        if name not in styles:
            taken = {c for k, st in styles.items() if k.startswith(prefix + "-")
                     for c in (st.fill, st.stroke)}  # fmt: skip
            styles[name] = base(next((c for c in PALETTE if c not in taken), OTHER))
        return name

    styles.setdefault("node", Style(fill="#f4f3ef", stroke=MUTED, width=0.35))
    styles.setdefault("node-label", Style(color=INK))
    styles.setdefault("edge", Style(stroke=MUTED, width=0.4))
    styles.setdefault("edge-label", Style(color=MUTED))
    styles.setdefault("legend", Style(color=INK))

    node_kind: dict[Hashable, str] = {}
    legend_nodes: dict[str, str] = {}
    for n, a in g.nodes.items():
        value = _style_value(node_style, n, a)
        name = ensure("node", value, lambda c: Style(fill=c, stroke=MUTED, width=0.35))
        if value is not None and f"{name}-label" not in styles:
            styles[f"{name}-label"] = Style(color=_on(styles[name].fill or "#ffffff"))
        node_kind[n] = name
        if value is not None:
            legend_nodes.setdefault(value, name)

    # Merge parallel edges (same ends, either way round for undirected graphs).
    groups: dict[tuple, list[int]] = defaultdict(list)
    for i, e in enumerate(g.edges):
        ends = (e.u, e.v) if g.directed else tuple(sorted((e.u, e.v), key=str))
        groups[ends if merge_parallel else (i,)].append(i)
    drawn = [idx for idx in groups.values()]

    edge_kind: dict[int, str] = {}
    legend_edges: dict[str, str] = {}
    for i, e in enumerate(g.edges):
        value = _style_value(edge_style, (e.u, e.v), e.attrs)
        name = ensure("edge", value, lambda c: Style(stroke=c, width=0.4))
        edge_kind[i] = name
        if value is not None:
            legend_edges.setdefault(value, name)

    shape_of = {}
    for n in g.nodes:
        value = _style_value(node_style, n, g.nodes[n])
        shape_of[n] = (node_shape or {}).get(value or "", "rect")

    # Edge geometry, in the ``down`` frame: a list of points per drawn edge.
    paths: dict[int, list[tuple[float, float]]] = {}
    if routing == "auto":
        # Orthogonal for trees and sparse layered graphs; straight for meshes such as a Clos
        # fabric, where every node in one row links to many in the next.
        ups = defaultdict(set)
        for e in g.edges:
            if grid[e.u][1] != grid[e.v][1]:
                lo, hi = (e.u, e.v) if grid[e.u][1] > grid[e.v][1] else (e.v, e.u)
                ups[lo].add(hi)
        routing = "orthogonal" if all(len(p) <= 2 for p in ups.values()) else "straight"
    if routing == "orthogonal":
        rank = {n: grid[n][1] for n in g.nodes}
        # Each node's edges down to the next rows leave from the middle of its lower side and
        # share one horizontal bus; edges arriving from above fan out along the upper side when
        # there are several.
        plan = {}
        arrivals: dict[Hashable, list[tuple[float, int]]] = defaultdict(list)
        for gi, idx in enumerate(drawn):
            e = g.edges[idx[0]]
            u, v = (e.u, e.v) if rank[e.u] <= rank[e.v] else (e.v, e.u)
            if rank[u] == rank[v]:
                continue
            plan[gi] = (u, v)
            arrivals[v].append((centre[u][0], gi))
        port: dict[int, float] = {}
        for v, items in arrivals.items():
            items.sort()
            span = (min(nw, nh) if shape_of[v] == "circle" else across) * 0.6
            for k, (_x, gi) in enumerate(items):
                off = 0.0 if len(items) == 1 else -span / 2 + span * k / (len(items) - 1)
                port[gi] = centre[v][0] + off
        # One bus per (parent, gap row), in lanes so that buses that overlap don't touch.
        buses: dict[tuple[Hashable, int], list[int]] = defaultdict(list)
        for gi, (u, v) in plan.items():
            buses[u, rank[v] - 1].append(gi)
        by_gap: dict[int, list[tuple[float, float, int]]] = defaultdict(list)
        bus_ids = list(buses)
        for b_i, (u, gap_row) in enumerate(bus_ids):
            xs_ = [centre[u][0]] + [port[gi] for gi in buses[u, gap_row]]
            by_gap[gap_row].append((min(xs_), max(xs_), b_i))
        lane_of: dict[int, tuple[int, int]] = {}
        for spans in by_gap.values():
            lanes = _lanes(spans)
            count = max(lanes.values()) + 1
            for b_i, k in lanes.items():
                lane_of[b_i] = (k, count)
        for b_i, (u, gap_row) in enumerate(bus_ids):
            k, count = lane_of[b_i]
            y_mid = gap_row * (along + gy) + along / 2 + gy * (k + 1) / (count + 1)
            x1 = centre[u][0]
            for gi in buses[u, gap_row]:
                v = plan[gi][1]
                x2 = port[gi]
                pts = [(x1, centre[u][1] + along / 2)]
                if abs(x1 - x2) > 1e-6:
                    pts += [(x1, y_mid), (x2, y_mid)]
                pts.append((x2, centre[v][1] - along / 2))
                e = g.edges[drawn[gi][0]]
                if (e.u, e.v) != (u, v):
                    pts.reverse()
                paths[gi] = pts
    for gi, idx in enumerate(drawn):  # straight edges, and same-row edges in a layered drawing
        if gi in paths:
            continue
        e = g.edges[idx[0]]
        (ux, uy), (vx, vy) = centre[e.u], centre[e.v]
        ends = []
        for (cx, cy), (tx, ty), n in (((ux, uy), (vx, vy), e.u), ((vx, vy), (ux, uy), e.v)):
            hw, hh = (across / 2, along / 2)
            if shape_of[n] == "circle":
                ends.append(_clip_circle(cx, cy, min(nw, nh) / 2, tx, ty))
            else:
                ends.append(_clip_rect(cx, cy, hw, hh, tx, ty))
        paths[gi] = ends

    # Bounds and drawing.
    xs = [p[0] for p in centre.values()]
    ys = [p[1] for p in centre.values()]
    margin = 6.0
    lo_x, hi_x = min(xs, default=0) - across / 2 - margin, max(xs, default=0) + across / 2 + margin
    lo_y, hi_y = min(ys, default=0) - along / 2 - margin, max(ys, default=0) + along / 2 + margin
    (vx0, vy0), (vx1, vy1) = frame(lo_x, lo_y), frame(hi_x, hi_y)
    entries = list(legend_nodes.items()) + list(legend_edges.items())
    entries += [(r.name or f"Route {i + 1}", "") for i, r in enumerate(routes)]
    legend_h = (8.0 + 7.0 * math.ceil(len(entries) / 3)) if legend and entries else 0.0
    n_edges = len(g.edges)
    plural = "" if n_edges == 1 else "s"
    desc = f"{'Directed' if g.directed else 'Undirected'} graph"
    if routes:
        desc += f" with {len(routes)} highlighted route{'' if len(routes) == 1 else 's'}"
    d = Drawing(
        view=(vx0, vy0, vx1 - vx0, vy1 - vy0 + legend_h), units="mm", stroke=0.35, font=3.0,
        title=title or f"Topology: {len(g.nodes)} nodes, {n_edges} edge{plural}",
        desc=desc + ".", styles=styles,
    )  # fmt: skip

    def tr(points):
        return tuple(frame(x, y) for x, y in points)

    arrow = "end" if g.directed else ""

    def edge_shapes(gi, style, width, meta=NO_META, tip="", shift=0.0):
        pts = tr(paths[gi])
        if shift and len(pts) == 2:  # side by side with other routes on the same edge
            (ax, ay), (bx, by) = pts
            length = math.hypot(bx - ax, by - ay) or 1.0
            ox, oy = -(by - ay) / length * shift, (bx - ax) / length * shift
            pts = ((ax + ox, ay + oy), (bx + ox, by + oy))
        out = []
        if len(pts) == 2:
            out.append(Line(*pts[0], *pts[1], arrow=arrow, style=style, width=width, meta=meta))
        else:
            out.append(Polyline(pts, style=style, width=width, title=tip, meta=meta))
            if arrow:
                (ax, ay), (bx, by) = pts[-2], pts[-1]
                out.append(Line(ax, ay, bx, by, arrow="end", style=style, width=width))
        return out

    # Edges under the nodes.
    for gi, idx in enumerate(drawn):
        e = g.edges[idx[0]]
        attrs = e.attrs
        width = edge_width((e.u, e.v), attrs) if edge_width else None
        text = label(edge_label, (e.u, e.v), attrs)
        if len(idx) > 1:
            text = f"{text} ×{len(idx)}".strip()
        tip = f"{e.u} – {e.v}" + (f" · {text}" if text else "")
        data = {k: v for k, v in attrs.items() if isinstance(v, str | int | float | bool)}
        meta = Meta.of(id=f"edge-{idx[0]}", kind="edge", source=e.u, target=e.v,
                       count=len(idx), **data)  # fmt: skip
        d.add(Group(tuple(edge_shapes(gi, edge_kind[idx[0]], width, meta, tip)), title=tip))
        if text:
            pts = paths[gi]
            # Orthogonal edges: label the drop into the lower node, which is the edge's own;
            # straight edges: the middle.
            if len(pts) > 2:
                seg = (pts[-2], pts[-1]) if pts[-1][1] > pts[0][1] else (pts[0], pts[1])
            else:
                seg = (pts[0], pts[1])
            mx, my = frame((seg[0][0] + seg[1][0]) / 2, (seg[0][1] + seg[1][1]) / 2)
            d.add(Text(mx + 1.2, my, text, 2.6, anchor="start", style="edge-label"))

    # Routes over the edges.
    edge_index: dict[tuple, int] = {}
    for gi, idx in enumerate(drawn):
        for i in idx:
            e = g.edges[i]
            edge_index.setdefault((e.u, e.v, e.key), gi)
            edge_index.setdefault((e.u, e.v), gi)
            if not g.directed:
                edge_index.setdefault((e.v, e.u, e.key), gi)
                edge_index.setdefault((e.v, e.u), gi)
    route_nodes: dict[Hashable, str] = {}

    def hops_of(r):
        hops = list(r.path)
        if hops and not isinstance(hops[0], tuple):
            hops = list(zip(hops, hops[1:], strict=False))
        return hops

    sharing: dict[int, list[int]] = defaultdict(list)  # drawn edge -> routes on it
    for r_i, r in enumerate(routes):
        for hop in hops_of(r):
            gi = edge_index.get(tuple(hop))
            if gi is not None and r_i not in sharing[gi]:
                sharing[gi].append(r_i)
    for r_i, r in enumerate(routes):
        style = r.style or f"route-{r_i}"
        if style not in styles:
            styles[style] = Style(stroke=ROUTE_COLORS[r_i % len(ROUTE_COLORS)], width=1.4)
        hops = hops_of(r)
        parts = []
        for hop in hops:
            gi = edge_index.get(tuple(hop))
            if gi is None:
                raise ValueError(f"Route {r.name or r_i + 1}: no edge {hop[0]} – {hop[1]}.")
            on_edge = sharing[gi]
            shift = (on_edge.index(r_i) - (len(on_edge) - 1) / 2) * 1.6
            parts += edge_shapes(gi, style, None, shift=shift)
            for n in hop[:2]:
                route_nodes.setdefault(n, style)
        names = " → ".join(str(h[0]) for h in hops[:1]) + "".join(f" → {h[1]}" for h in hops)
        d.add(
            Group(
                tuple(parts),
                title=f"{r.name or f'Route {r_i + 1}'}: {names}",
                meta=Meta.of(id=f"route-{r_i}", kind="route", name=r.name, path=names),
            )
        )

    # Nodes on top.
    for n, a in g.nodes.items():
        cx, cy = frame(*centre[n])
        name = node_kind[n]
        data = {k: v for k, v in a.items() if isinstance(v, str | int | float | bool)}
        meta = Meta.of(id=f"node-{n}", kind="node", node=n, **data)
        text = label(node_label, n, a)
        tip = " · ".join([str(n), *(f"{k} {v}" for k, v in data.items() if k != "pos")])
        items = []
        if shape_of[n] == "circle":
            r = min(nw, nh) / 2
            items.append(Circle(cx, cy, r, style=name, title=tip, meta=meta))
            room = r * 1.6
        else:
            items.append(Rect(cx - nw / 2, cy - nh / 2, nw, nh, rx=1.5, style=name, title=tip,
                              meta=meta))  # fmt: skip
            room = nw - 3
        if n in route_nodes:
            ring = route_nodes[n]
            box = (Circle(cx, cy, min(nw, nh) / 2, style=ring)
                   if shape_of[n] == "circle" else
                   Rect(cx - nw / 2, cy - nh / 2, nw, nh, rx=1.5, style=ring))  # fmt: skip
            items.append(box)
        if text:
            size = fit_size(text, min(3.4, nh * 0.42), room, smallest=2.0)
            if size is None:
                size, text = 2.0, truncate(text, 2.0, room)
            items.append(Text(cx, cy, text, size, style=f"{name}-label"
                              if f"{name}-label" in styles else "node-label"))  # fmt: skip
        d.add(Group(tuple(items)))

    # Legend: swatches in three columns under the drawing.
    if legend and entries:
        x0, y0 = vx0 + margin, vy1 + 4.0
        col = (vx1 - vx0 - 2 * margin) / 3
        for k, (text, style) in enumerate(entries):
            x, y = x0 + col * (k % 3), y0 + 7.0 * (k // 3) + 3.0
            if style.startswith("node"):
                d.add(Rect(x, y - 2.0, 6.0, 4.0, rx=0.8, style=style))
            elif style.startswith("edge"):
                d.add(Line(x, y, x + 6.0, y, style=style, width=1.0))
            else:
                r_i = k - len(legend_nodes) - len(legend_edges)
                rs = routes[r_i].style or f"route-{r_i}"
                d.add(Line(x, y, x + 6.0, y, style=rs))
            d.add(Text(x + 8.0, y, truncate(text, 3.0, col - 10), 3.0, anchor="start",
                       style="legend"))  # fmt: skip
    return d