Path graph: pack lanes by column so sparse fans draw tight

A lane per route stacked the band as tall as the graph had routes, even
where the routes barely overlapped: TSFCT SUTTON-680M's five observed
routes drew five lanes deep though at no column did more than two nodes
coexist. A lane is a whole-width row, but two routes need distinct rows
only in the columns where they both carry a node — endpoint to endpoint
every route already shares the origin and us.

So after _assign_lanes seats the routes (best centred, sharing routes
adjacent), _compress_lanes squeezes them: each node keeps its side of the
best spine but slides to the innermost free row in its own column. A
column with one off-spine node claims one flanking row however many routes
fan past it; only a column where routes genuinely stack pays for deeper
rows. SUTTON now draws three lanes / ten rows instead of five / sixteen.

The best path's nodes stay on the spine, so it still runs straight through
the centred endpoints; the even/odd endpoint-centring is untouched (its
single-column shapes can't compress). Adds pack/stack tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-22 00:14:32 -04:00
1 parent 8f6fa6b6ae
commit 5c6052884a
2 files changed
+175 -18

No files matched your search

+88 -18
View File
@@ -15,14 +15,20 @@ now draws the fan as a **multilane highway**: a node always sits on a level plat
lane, and a route changes lane only *between* nodes, easing across on a single gentle shift
the way a car drifts one lane over and then stays there. Concretely:
* **lanes** — each distinct path owns one horizontal lane, the lanes a fixed pitch of text rows
apart; the highest-priority (drawn last, e.g. the selected or best-evidence) path takes the
centre lane and the alternatives lie above and below it. The two endpoints sit at the vertical
centre of the lane band, so the strongest route runs through them as the flow's spine — dead
straight when the lanes are odd (its own lane is the centre), easing gently when they are even,
where one extra padding row is opened between the two central lanes so the endpoints land on an
exact centred row between them. The lanes are ordered to seat routes that share relays near
each other, so a shared hop costs the shortest possible detour;
* **lanes** — the highest-priority (drawn last, e.g. the selected or best-evidence) path runs
along the centre lane as the flow's straight spine, and the alternatives fan above and below
it, a fixed pitch of text rows apart. The routes are first ordered so ones that share relays
seat next to each other (a shared hop costs the shortest detour), then the lanes are *packed
by column*: rather than give every route a full-width lane of its own — which stacks the band
as tall as the route count even where the routes barely overlap — each node keeps its side of
the spine but slides to the innermost free row *in its own column*. So a column with a single
off-spine node claims just one flanking row however many routes cross the graph, and only a
column where routes genuinely stack pays for the deeper rows; a five-route fan through at most
two nodes per column draws three lanes deep, not five. The two endpoints sit at the vertical
centre of the packed band, so the spine runs through them — dead straight when the lanes are
odd (its own lane is the centre), easing gently when they are even, where one extra padding row
is opened between the two central lanes so the endpoints land on an exact centred row between
them;
* **columns** (x) place each node by *balanced* rank — its distance from the origin over its
distance-plus-remaining-distance to us — so a path's relays spread evenly between the two
ends however long the other paths are, and a shared relay lands in one place;
@@ -328,16 +334,31 @@ def render_path_graph(
_fold_detours(drawn, seqs, owner, xfrac, width)
lane_of_path = _assign_lanes(drawn, seqs, owner, best)
# The endpoints sit at the vertical centre of the lane band, where the strongest route runs
# through them as the graph's spine; the alternatives fan above and below. For an odd lane
# count that centre *is* the best path's own lane, so the spine runs dead straight; for an
# even count it is the midpoint between the two central lanes (the best path takes the upper
# of the two), so the endpoints stay centred and a best path carrying relays of its own eases
# half a lane to reach them rather than seating the whole graph off-centre.
max_lane = max(lane_of_path.values())
# Compress the per-path lanes onto the fewest rows the picture actually needs. A lane per
# path stacks the whole graph as tall as it has routes, even where the routes barely overlap
# — five routes through at most two nodes per column drew five lanes deep. So each node is
# slid to the innermost free lane *in its own column*, keeping its side of the best spine:
# a column holding one off-spine node needs one off-spine row however many paths cross the
# graph, and only a column where several routes genuinely stack pays for the extra rows.
span = width * 2 - 2 * _GRAPH_PAD_DOTS
def col_of(node: str) -> int:
return (_GRAPH_PAD_DOTS + round(xfrac[node] * span)) >> 1
signed = _compress_lanes(ordered_nodes, lane_of_path, owner, best, col_of)
# The endpoints sit at the vertical centre of the compressed lane band, where the strongest
# route runs through them as the graph's spine; the alternatives fan above and below. For an
# odd lane count that centre *is* the best path's own lane, so the spine runs dead straight;
# for an even count it is the midpoint between the two central lanes (the best path takes the
# upper of the two), so the endpoints stay centred and a best path carrying relays of its own
# eases half a lane to reach them rather than seating the whole graph off-centre.
low = min(signed.values(), default=0)
high = max(signed.values(), default=0)
max_lane = high - low
centre_lane = max_lane / 2.0
node_lane: dict[str, float] = {
node: (centre_lane if node in (SRC_NODE, DST_NODE) else float(lane_of_path[owner[node]]))
node: (centre_lane if node in (SRC_NODE, DST_NODE) else float(signed[node] - low))
for node in ordered_nodes
}
@@ -371,8 +392,6 @@ def render_path_graph(
scale = min(1.0, avail / (lane_rows * 4)) if lane_rows else 0.0
canvas = MapCanvas(width, rows)
dot_w = width * 2
span = dot_w - 2 * _GRAPH_PAD_DOTS
band = lane_rows * 4 * scale
# Centre the band, anchored on a cell-mid row so the (unscaled) integer lane rows land dead
# on their cells — no per-lane snap drift that would nudge a centred endpoint off its middle.
@@ -686,6 +705,57 @@ def _barycentre_lanes(
return {p: int(lane[p]) for p in order}
def _compress_lanes(
ordered_nodes: list[str],
lane_of_path: dict[int, int],
owner: dict[str, int],
best: int,
col_of: Callable[[str], int],
) -> dict[str, int]:
"""Squeeze the per-path lanes onto the fewest rows, one node at a time within each column.
:func:`_assign_lanes` seats each path on a lane of its own, so the band is as tall as the
graph has routes — even where the routes only ever run one or two abreast. But a lane is a
whole-width row: two routes need distinct rows only in the *columns* where they both carry a
node, and endpoint-to-endpoint every route already shares the origin and us. So this pass
keeps each node's **side** of the best spine (above it, below it, or on it) but slides it to
the innermost free lane *in its own column*: a column with one node above the spine uses the
first row above however many routes fan past it, and only a column where several routes truly
stack claims the deeper rows. The best path's own nodes stay on the spine (offset ``0``), so
it still runs straight through the centre; the returned lanes are signed offsets from that
spine (``<0`` above, ``>0`` below), which the caller shifts to a ``0``-based band.
Returns ``{node: signed_lane}`` for every relay (endpoints are placed on the band centre by
the caller, not here). A node a column holds alone off the spine always lands on ``±1``, so
a sparse multi-route graph collapses to the three-lane spine-and-two-flanks it really is.
"""
best_lane = lane_of_path[best]
# Signed distance of each relay's owning-path lane from the best spine: 0 on the spine,
# negative above it, positive below. The magnitude only orders the packing; the gaps close.
offset = {
node: lane_of_path[owner[node]] - best_lane
for node in ordered_nodes
if node not in (SRC_NODE, DST_NODE)
}
columns: dict[int, list[str]] = {}
for node in offset:
columns.setdefault(col_of(node), []).append(node)
signed: dict[str, int] = {}
for members in columns.values():
# Pack each side toward the spine, nearest-first, so the closest route keeps ±1.
above = sorted((n for n in members if offset[n] < 0), key=lambda n: -offset[n])
below = sorted((n for n in members if offset[n] > 0), key=lambda n: offset[n])
for n in members:
if offset[n] == 0: # the best path itself — stays on the spine
signed[n] = 0
for depth, n in enumerate(above, start=1):
signed[n] = -depth
for depth, n in enumerate(below, start=1):
signed[n] = depth
return signed
def _place_labels(
canvas: MapCanvas,
ordered_nodes: list[str],
+87
View File
@@ -9,10 +9,13 @@ import pytest
from meshterm.ui.pathgraph import (
DST_NODE,
SRC_NODE,
_GRAPH_PAD_DOTS,
PathLayer,
_assign_lanes,
_balanced_x,
_coalesce_prefixes,
_collapse,
_compress_lanes,
_fold_detours,
_route,
render_path_graph,
@@ -218,6 +221,45 @@ def _owner_after_fold(layers, width=72): # noqa: ANN001
return owner, lanes
def _packed_lanes(layers, width=60): # noqa: ANN001
"""Run the lane pipeline through compression, as ``render_path_graph`` does.
Returns ``(signed, columns, route_lanes)``: the packed signed lane per relay (``0`` on the
best spine, ``<0`` above, ``>0`` below), each relay's cell column, and how many lanes the
per-path assignment used *before* packing — so a test can assert the pack squeezed them.
"""
drawn = _collapse(_coalesce_prefixes(layers))
seqs = [(SRC_NODE, *layer.hops, DST_NODE) for layer in drawn]
ordered: list[str] = []
seen: set[str] = set()
edges: set[tuple[str, str]] = set()
for seq in seqs:
for node in seq:
if node not in seen:
seen.add(node)
ordered.append(node)
edges.update(zip(seq, seq[1:]))
xfrac = _balanced_x(ordered, edges)
best = max(range(len(drawn)), key=lambda j: drawn[j].priority)
owner: dict[str, int] = {}
for i in sorted(range(len(drawn)), key=lambda j: -drawn[j].priority):
for node in seqs[i]:
owner.setdefault(node, i)
_fold_detours(drawn, seqs, owner, xfrac, width)
lane_of_path = _assign_lanes(drawn, seqs, owner, best)
route_lanes = max(lane_of_path.values()) + 1
span = width * 2 - 2 * _GRAPH_PAD_DOTS
col_of = lambda node: (_GRAPH_PAD_DOTS + round(xfrac[node] * span)) >> 1 # noqa: E731
signed = _compress_lanes(ordered, lane_of_path, owner, best, col_of)
columns = {node: col_of(node) for node in signed}
return signed, columns, route_lanes
def _lane_count(signed) -> int: # noqa: ANN001
"""Number of distinct rows the packed lanes span (spine included)."""
return max(signed.values()) - min(signed.values()) + 1
def test_detour_path_rides_its_siblings_lane_not_a_new_one() -> None:
"""A route that is a sibling *plus* one inserted relay folds onto that sibling's lane.
@@ -266,6 +308,51 @@ def test_two_detours_sharing_a_column_do_not_overprint() -> None:
assert lanes == 3
def test_routes_pack_onto_shared_flanks_when_their_columns_differ() -> None:
"""Routes that diverge at different columns share a flank lane, so the band packs tight.
Four routes: a three-relay best spine, and three alternatives that each swap a *different*
one of the spine's relays (a different column). Given a full-width lane apiece they draw
four deep, yet at no column do more than two nodes coexist — so the pack squeezes them onto
the spine plus a single row above and below: three lanes, not four. This is the SUTTON-680M
shape (five routes, ≤2 nodes per column) drawn small.
"""
layers = [
PathLayer(("aa", "bb", "cc"), WHITE, 4), # spine
PathLayer(("xx", "bb", "cc"), GREY, 2), # swaps the first relay (col of aa)
PathLayer(("aa", "yy", "cc"), GREY, 2), # swaps the middle relay (col of bb)
PathLayer(("aa", "bb", "zz"), GREY, 2), # swaps the last relay (col of cc)
]
signed, columns, route_lanes = _packed_lanes(layers)
assert route_lanes == 4 # a lane per route before packing
assert _lane_count(signed) == 3 # packed down to spine + one flank each side
assert signed["aa"] == signed["bb"] == signed["cc"] == 0 # best rides the straight spine
assert all(signed[n] != 0 for n in ("xx", "yy", "zz")) # alternatives leave the spine
# Two alternatives sharing a flank must sit in different columns (no overprint).
for lane in {signed["xx"], signed["yy"], signed["zz"]}:
on_lane = [n for n in ("xx", "yy", "zz") if signed[n] == lane]
assert len({columns[n] for n in on_lane}) == len(on_lane)
def test_routes_stacking_in_one_column_keep_separate_lanes() -> None:
"""The pack never collapses routes that genuinely coexist in a column onto one row.
Three alternatives all diverge through the *same* column off the origin, so three nodes
truly stack there. Packing can't squeeze that — the column needs a distinct row per node —
so the spine plus three stacked alternatives hold their own lanes; the floor is honest.
"""
layers = [
PathLayer(("aa", "zz"), WHITE, 4), # spine relay aa, then shared zz near us
PathLayer(("bb", "zz"), GREY, 3), # bb shares aa's column
PathLayer(("cc", "zz"), GREY, 2), # cc shares aa's column
PathLayer(("dd", "zz"), GREY, 1), # dd shares aa's column
]
signed, columns, _route_lanes = _packed_lanes(layers)
diverging = ("aa", "bb", "cc", "dd")
assert len({columns[n] for n in diverging}) == 1 # they all stack in one column
assert len({signed[n] for n in diverging}) == 4 # so each keeps a row of its own
def test_edge_pinned_relay_labels_are_not_dropped() -> None:
"""A relay a balanced rank pins near a canvas edge still shows its whole name.