diff --git a/meshterm/services/topology.py b/meshterm/services/topology.py index 90f15ee..24bb50c 100644 --- a/meshterm/services/topology.py +++ b/meshterm/services/topology.py @@ -366,6 +366,99 @@ class MeshTopology: ): link.last_seen = when + def coalesce_prefixes(self) -> None: + """Fold each under-specified node id into the longer id it can only be. + + The same physical node reaches the graph at different hash widths: a trace hop + logged at 1 byte (``27``), a packet relay at 3 (``27d439``), a full 6-byte + contact id (``27d4396a2967``). :meth:`canonical` widens a hop onto a contact id + only when the prefix names *exactly one* contact — but the mesh holds two nodes + whose keys both open ``27`` (``27d4…`` and ``27e4…``), so the bare ``27`` hop + stays short and stands beside the wide ``27d4396a2967`` as a phantom second node. + Left alone that doubles the node on every surface the graph feeds — the atlas + draws it twice, the route graph fans two lanes to one repeater, and the scenario + ranker offers a redundant weaker route through the stub. + + This closes the gap using the evidence the graph *actually holds* rather than the + whole contact list: a short id is merged into a longer node id present in the graph + when it is a strict prefix of **exactly one** of them (following a prefix chain — + ``65`` → ``6532`` → ``6532eb`` — to its longest end). A short id that opens two + distinct longer nodes (``c5`` → ``c5bc…`` and ``c5ba…``) is genuinely ambiguous and + is left as its own node; a short id that opens none (a node we have only ever heard + narrowly) keeps its width too — it is one node, merely under-named. Merging folds + the short id's links into the wide id's, summing samples, pooling SNR readings and + sources, and keeping the freshest sighting, so the wide node inherits every reading + the stub had gathered. Idempotent: a second call finds nothing left to merge. + + Called once at the end of :func:`build_topology`, so every consumer sees each node + once. Safe for our own node (its 12-hex id is never a short prefix candidate). + """ + while True: + merge = self._next_prefix_merge(self._node_ids()) + if merge is None: + return + self._merge_node(*merge) + + def _node_ids(self) -> set[str]: + """Every node id that currently appears as a link endpoint.""" + ids: set[str] = set() + for a, b in self._links: + ids.add(a) + ids.add(b) + return ids + + def _next_prefix_merge(self, nodes: set[str]) -> Optional[tuple[str, str]]: + """The next ``(short, long)`` pair to fold, or ``None`` when none remains. + + A short id (under a full 6-byte canonical width) folds when the graph's longer + ids that extend it all lie on one prefix chain — i.e. the longest of them starts + with every other — so the short can only mean that one node. Shortest ids are + offered first, so a ``65`` → ``6532`` → ``6532eb`` chain collapses from the tail + end inward over successive calls. + """ + for short in sorted(nodes, key=len): + if len(short) >= 12: # a full canonical id is never under-specified + continue + exts = [ + other + for other in nodes + if other != short and len(other) > len(short) and other.startswith(short) + ] + if not exts: + continue + longest = max(exts, key=len) + if all(longest.startswith(ext) for ext in exts): # one node, not two + return short, longest + return None + + def _merge_node(self, src: str, dst: str) -> None: + """Relabel every link touching ``src`` onto ``dst``, folding shared links together.""" + for key in list(self._links): + if src not in key: + continue + link = self._links.pop(key) + a, b = key + na = dst if a == src else a + nb = dst if b == src else b + if na == nb: # a src→dst link (src prefixes dst) collapses to a self-loop + continue + new_key = (na, nb) if na < nb else (nb, na) + existing = self._links.get(new_key) + if existing is None: + self._links[new_key] = Link( + a=new_key[0], b=new_key[1], + samples=link.samples, snrs=list(link.snrs), + last_seen=link.last_seen, sources=set(link.sources), + ) + else: + existing.samples += link.samples + existing.snrs.extend(link.snrs) + existing.sources |= link.sources + if link.last_seen is not None and ( + existing.last_seen is None or link.last_seen > existing.last_seen + ): + existing.last_seen = link.last_seen + # --- queries ----------------------------------------------------------------- @property @@ -647,4 +740,7 @@ def build_topology( source="neighbour", ) + # Every source has folded in; collapse any node that reached us at two hash widths + # (a bare trace hop beside its wide contact id) so each appears once everywhere. + topo.coalesce_prefixes() return topo diff --git a/meshterm/ui/message_paths_screen.py b/meshterm/ui/message_paths_screen.py index 7f5fd98..627d555 100644 --- a/meshterm/ui/message_paths_screen.py +++ b/meshterm/ui/message_paths_screen.py @@ -270,13 +270,13 @@ class MessagePathsScreen(Screen): def _graph_lines(self, width: int) -> list[str]: """Draw every distinct path origin → us, the selected one white over gray. - The shared route-graph widget does the layout (lanes fanned from the centre - in first-heard order, shared relays averaged together); this just maps each - distinct path to a :class:`~meshterm.ui.pathgraph.PathLayer` — the selected - one white on top, the rest gray beneath — and hands it the shared route-graph - callbacks (:func:`~meshterm.ui.widgets.route_graph_style`): endpoints named, - relays their own map marker where the type is known, each labelled by its - first hash byte in the node's own hue. + The shared route-graph widget does the layout (a layered left-to-right graph, + each relay drawn once in its own column); this just maps each distinct path to a + :class:`~meshterm.ui.pathgraph.PathLayer` — the selected one white on top, the + rest gray beneath — and hands it the shared route-graph callbacks + (:func:`~meshterm.ui.widgets.route_graph_style`): endpoints named, relays their + own map marker where the type is known, each labelled by its first hash byte in + the node's own hue. """ selected = self._arrivals[self._index].hops layers = [ diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index e7635b5..386ecda 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -272,7 +272,7 @@ class NodeDetailScreen(Screen): max_rows=_PATH_MAX_ROWS, lane_step=_PATH_LANE_STEP, ) - caption = Text("you → node · white = suggested route · labels = hash byte", style="faint") + caption = Text("you → node · white = suggested route", style="faint") lines.extend(render_lines(caption, width, no_wrap=True)) if path.legend: lines.extend(render_lines(node_type_legend(), width, no_wrap=True)) @@ -604,8 +604,8 @@ def _route_row( """The firmware's learned route to the node, or a note that it floods. The hops render through THE path widget (:func:`~meshterm.ui.widgets.path_text`) at a - 1-byte hash width, so each reads ``name (3d)`` — the same first-byte tag the route graph - prints beside its markers, letting the row and the graph be cross-read hop for hop. + 1-byte hash width, so each reads ``name (3d)`` — the same name the route graph prints + beside its markers, plus the short hash it travels under, so row and graph cross-read. """ if device_route is None: return Text("no learned route — floods", style="muted") @@ -620,8 +620,8 @@ def _route_row( def _suggest_row(suggested, *, resolve, self_name: Optional[str]) -> Text: # noqa: ANN001 """The observed best path (the "suggest best path" answer), or a muted stand-in. - Like :func:`_route_row`, the hops render through THE path widget with a 1-byte hash in - parentheses so they match the route graph's byte labels; the bottleneck SNR and sample + Like :func:`_route_row`, the hops render through THE path widget named, with a 1-byte + hash in parentheses (the short id each hop travels under); the bottleneck SNR and sample count trail behind as context. """ if suggested is None: @@ -709,14 +709,34 @@ def _path_view( for scenario in scenarios: add(scenario.hops, 2, grey) - glyph_of, label_of, label_rgb_of = style( + glyph_of, byte_label_of, label_rgb_of = style( resolve=resolve, self_name=self_name, source=node_label, type_of=type_of, key_of=key_of ) + + # This page names every node, not just the two ends. Where the Message paths graph tags + # a relay with only its first hash byte, here each relay wears its resolved contact name + # (its colour is already the name's hue), so the whole route reads as places rather than + # hex; an unidentified relay keeps the byte, the honest most it can be called. The two + # endpoints keep route_graph_style's names. + def label_of(node: str) -> Optional[str]: + if node in (SRC_NODE, DST_NODE): + return byte_label_of(node) + named = resolve(node) + return named if named and named != node else node[:2] + # route_graph_style pins us to DST (the right) and the target to SRC (the left); swap the # two sentinels so the graph draws us on the left and the target on the right. glyph_of = _flip_endpoints(glyph_of) label_of = _flip_endpoints(label_of) label_rgb_of = _flip_endpoints(label_rgb_of) + + # The target wears its own map glyph (▲ repeater, ■ room, ◉ sensor) — the same mark the + # header and the map give it. route_graph_style draws the far endpoint as a plain dot, + # since on its home screen (Message paths) that end is an arbitrary message origin; here + # it is a known contact whose type we can show. + glyph_of = _with_target_glyph( + glyph_of, _NODE_GLYPHS.get(type_of(canonical_target), _DEFAULT_GLYPH) + ) legend = any(type_of(h) is not None for layer in layers for h in layer.hops) return _PathView( layers=layers, @@ -727,6 +747,20 @@ def _path_view( ) +def _with_target_glyph(glyph_of: GlyphOf, target_glyph: tuple[str, str]) -> GlyphOf: + """Wrap the graph's glyph callback so the target endpoint draws its own node glyph. + + The graph's right endpoint is the node this page is about, and here we know its type — + so it draws the map's own mark for that type (``▲`` repeater, ``■`` room, ``◉`` sensor, + ``●`` plain), matching the identity header and the location preview, rather than + ``route_graph_style``'s generic origin dot. Every other node passes through untouched. + """ + def wrapped(node: str) -> tuple[str, str]: + return target_glyph if node == DST_NODE else glyph_of(node) + + return wrapped + + def _flip_endpoints(callback): """Wrap a pathgraph per-node callback so it swaps the two endpoint sentinels. diff --git a/meshterm/ui/packet_viewer.py b/meshterm/ui/packet_viewer.py index 1e7783d..35049d5 100644 --- a/meshterm/ui/packet_viewer.py +++ b/meshterm/ui/packet_viewer.py @@ -7,7 +7,7 @@ that lays the packet out in full, flavoured by kind. An advert shows the node's identity, type, and location; telemetry shows the node and its reported values; an RX-logged packet shows its parsed class and route plus the relay path it rode in on — as a ``via`` chain and, when it actually crossed a relay, as THE route graph -(:mod:`~meshterm.ui.pathgraph`): origin → relays → us, the same fan-lane picture the +(:mod:`~meshterm.ui.pathgraph`): origin → relays → us, the same layered picture the Message paths dialog and the Trophy case draw — and, for an overheard channel-text frame naming a channel we hold the key for, the decrypted text too (see :func:`~meshterm.core.channels.decrypt_channel_text`), even though the radio itself never @@ -535,8 +535,8 @@ class PacketViewer(Screen): a two-node graph would waste the height. The relay chain is the packet's path (originator-nearest first), the left endpoint the origin when the frame named one (an advert's ``adv_key``; other classes arrive origin-less, drawn ``?``), the right - endpoint always us — the same fan-lane widget the Message paths dialog and the - Trophy case draw, in a single white path. + endpoint always us — the same layered route-graph widget the Message paths dialog + and the Trophy case draw, in a single white path. """ if entry.kind != "packet": return [] diff --git a/meshterm/ui/pathgraph.py b/meshterm/ui/pathgraph.py index 10a11a7..59adf6c 100644 --- a/meshterm/ui/pathgraph.py +++ b/meshterm/ui/pathgraph.py @@ -1,21 +1,30 @@ -"""THE route-graph widget: hop sequences drawn as fanned braille lanes between us-es. +"""THE route-graph widget: hop sequences drawn as a tidy left-to-right layered graph. Extracted from the Message paths dialog so every screen that draws walked (or planned) routes draws them the same way. A *layer* is one path — its relay hops, an edge colour, and a draw priority — and the widget lays every distinct path out between a left and a -right endpoint marker: +right endpoint marker. -* **columns** are the distinct node depths, spread evenly across the width, so forks - read clearly however lopsided the paths' lengths are; -* **lanes** fan out from the vertical centre in layer order (first layer on the centre - line, the next below, the next above, …); a node shared between paths averages its - lanes, so a common relay pulls the paths together where they actually met; +Rather than fanning the paths as free lanes and averaging shared relays (which pulls +lines into acute tangles wherever many paths meet the two endpoints), the widget draws +the paths as one **layered graph**, the way a subway map or a dependency chart reads: + +* **ranks** (columns) are hop distance from the left endpoint — a node sits in the column + of its *furthest* appearance across the paths, so every edge runs strictly left-to-right + and a relay shared by several routes is drawn **once**, in one place; +* **long edges** — a path that skips a column (a direct shot past where another route + stops to relay) — are routed through invisible waypoints at each column it crosses, so + the line bends around the intervening nodes instead of slicing through them; +* **within a column** the nodes are ordered to minimise crossings (a few barycentre + sweeps), then spread down the full available height with their vertical positions + pulled toward the average of their neighbours — straightening each route into a lane + while keeping the branches far enough apart to leave readable (~60°) angles; * **shared cells** go to the highest-priority layer (drawn last), so e.g. the Message paths dialog's selected path reads white over the unused grey; -* **labels** sit straight above or below their marker — the side away from the centre - line first, a spot clear of the drawn lines preferred — and endpoints try the same - vertical placements before falling back beside the marker. A caller that wants a - node unlabelled returns ``None`` for it. +* **labels** sit straight above or below their marker — pushed to the side away from the + graph's middle, a spot clear of the drawn lines preferred — and endpoints slide their + label inward from the canvas edge so a long name still lands by its marker. A caller + that wants a node unlabelled returns ``None`` for it. Everything renders onto a :class:`~meshterm.ui.mapcanvas.MapCanvas`; the caller supplies the per-node glyph/label/colour callbacks, so the widget stays free of contact-list and @@ -24,6 +33,7 @@ theme concerns. from __future__ import annotations +from collections import defaultdict from dataclasses import dataclass from math import ceil from typing import Callable, Optional, Sequence @@ -35,24 +45,45 @@ from .mapcanvas import RGB, MapCanvas, parse_hex SRC_NODE = "\x00src" DST_NODE = "\x00dst" -#: Vertical dot separation between path lanes. -_LANE_STEP_DOTS = 12 +#: Prefix for the invisible waypoint ids a long edge is routed through — one per column +#: it crosses. Never handed to the caller's callbacks (waypoints draw line only). +_VIRTUAL_PREFIX = "\x00v" -#: Dots reserved beyond the outermost lane at each end of the fan — a label row for -#: that lane's marker, plus a little air. The box is sized and centred on the fan's -#: real extent (which is rarely symmetric), so it spends its rows on the paths rather -#: than on a mirrored half that stays empty. +#: Vertical dot separation aimed for between adjacent nodes sharing a column — the base +#: "lane" height one unit of the layout maps to. Wide enough to seat a marker and its +#: label row; a tall graph compresses it to fit, a sparse one stretches it (bounded by +#: :data:`_MAX_STRETCH`) to spend the height it has on airier, less acute branch angles. +_LANE_STEP_DOTS = 14 + +#: How far the lane step may stretch beyond :data:`_LANE_STEP_DOTS` when a graph has few +#: rows to fill — enough to open the branch angles up without blowing a two-node fork out +#: to the full height. +_MAX_STRETCH = 1.8 + +#: Dots reserved beyond the outermost node at each end of the graph — a label row for +#: that node's marker, plus a little air. The box is sized and centred on the graph's +#: real vertical extent (which is rarely symmetric), so it spends its rows on the paths +#: rather than on a mirrored half that stays empty. _GRAPH_END_DOTS = 8 #: The dot row within a character cell a horizontal edge line is aimed at — the #: upper-middle of the cell's 2×4 pixel grid (rows 0..3 top-down), where a one-dot #: line reads as running through the glyph rather than hugging its bottom edge. Every -#: node's y is snapped onto this row (see ``pos``) so same-lane runs stay level there. +#: node's y is snapped onto this row (see ``_mid_row``) so same-column runs stay level. _CELL_MID_DOT = 1 #: Dot-space margin the endpoint markers keep from the canvas edges. _GRAPH_PAD_DOTS = 6 +#: Minimum vertical separation, in layout units, between two nodes in the same column — +#: one lane. The ordering/placement passes never seat two markers closer than this. +_MIN_LANE_GAP = 1.0 + +#: Sweeps of the crossing-minimisation and vertical-straightening relaxations. The graphs +#: are tiny (a handful of nodes over a handful of columns), so a few passes converge. +_ORDER_SWEEPS = 6 +_PLACE_ITERS = 10 + #: A node's graph marker: the glyph and its ``#rrggbb`` colour (the shared node-glyph #: tuples from :mod:`~meshterm.ui.map_render` / :mod:`~meshterm.ui.widgets` fit as-is). GlyphOf = Callable[[str], tuple[str, str]] @@ -70,7 +101,7 @@ class PathLayer: Attributes: hops: The relay node ids between the endpoints, in walk order (empty = the - path runs endpoint to endpoint on the centre line). + path runs endpoint to endpoint straight across). color: The edge colour the path draws in. priority: Draw priority — where paths share a cell, the highest priority keeps it (its edges are also drawn last). @@ -81,17 +112,165 @@ class PathLayer: priority: int -def _mid_row(y_dot: int) -> int: +@dataclass +class _LayoutNode: + """A vertex the layout positions — a real node, an endpoint, or an edge waypoint. + + Attributes: + node: The id handed to the caller's callbacks (``SRC_NODE``/``DST_NODE`` for the + endpoints, a hop hash for a relay), or a ``_VIRTUAL_PREFIX`` id for a waypoint. + rank: The column (hop distance from the left endpoint) the node sits in. + real: Whether the node carries a marker and label (waypoints are line-only). + order: Its position within the column, top to bottom (set by the ordering pass). + y: Its vertical coordinate — layout units during placement, canvas dots after. + """ + + node: str + rank: int + real: bool + order: int = 0 + y: float = 0.0 + + +def _mid_row(y_dot: float) -> int: """Snap a dot row onto the upper-middle dot of its character cell. A braille cell is four dot rows tall; a horizontal line drawn on the top or bottom row hugs the glyph's edge and reads as sitting too high or too low. Snapping every node's y to :data:`_CELL_MID_DOT` keeps markers — and the level - runs between same-lane nodes — centred in the cell's pixel space. + runs between same-column nodes — centred in the cell's pixel space. """ return round((y_dot - _CELL_MID_DOT) / 4) * 4 + _CELL_MID_DOT +def _collapse(layers: Sequence[PathLayer]) -> list[PathLayer]: + """Fold layers with identical hop sequences onto their highest-priority instance. + + Re-walking a known route highlights it rather than doubling it: the first appearance + fixes draw order, the strongest priority (and its colour) wins the shared path. + """ + drawn: list[PathLayer] = [] + by_hops: dict[tuple[str, ...], int] = {} + for layer in layers: + at = by_hops.get(layer.hops) + if at is None: + by_hops[layer.hops] = len(drawn) + drawn.append(layer) + elif layer.priority > drawn[at].priority: + drawn[at] = PathLayer(layer.hops, layer.color, layer.priority) + return drawn + + +_HEX_DIGITS = frozenset("0123456789abcdef") + + +def _coalesce_prefixes(layers: Sequence[PathLayer]) -> list[PathLayer]: + """Fold an under-specified hop into the longer id it can only be, across the layers. + + A relay reaches the graph at different hash widths across the paths — a 1-byte trace + hop (``be``) beside the same node's wider id (``be1d1c1dbc4b``). Drawn as-is they double + the node: two markers a column apart, often carrying the same resolved name. The + observed-topology graph coalesces what it can, but only where a hash is unambiguous + against the *whole* contact list; a hash that opens two contacts (``be`` also begins + ``bedd2b``) survives to here, even though among *these* paths it can only be the one wide + node present. So the widget closes the gap locally: using only the ids the layers hold, + a short id is rewritten to the longer id it strictly prefixes when exactly one such id is + present (following a chain to its longest end); a short id that prefixes two distinct + present nodes is genuinely ambiguous and left as itself. The per-node callbacks then see + one id per node, and any paths made identical by the rewrite collapse together downstream. + """ + ids = {hop for layer in layers for hop in layer.hops} + remap: dict[str, str] = {} + remaining = set(ids) + while True: + pair = _prefix_merge(remaining) + if pair is None: + break + short, long = pair + remap[short] = long + remaining.discard(short) + if not remap: + return list(layers) + + def resolved(hop: str) -> str: + for _ in range(len(remap) + 1): # follow a rewrite chain, guarded against cycles + if hop not in remap: + break + hop = remap[hop] + return hop + + return [ + PathLayer(tuple(resolved(hop) for hop in layer.hops), layer.color, layer.priority) + for layer in layers + ] + + +def _prefix_merge(nodes: set[str]) -> Optional[tuple[str, str]]: + """The next ``(short, long)`` id pair to fold among ``nodes``, or ``None`` when none. + + A short hex id (under a full 6-byte width) folds when the longer present ids that + extend it all lie on one prefix chain — the longest starts with every other — so it can + only name that one node. Shortest ids are offered first, collapsing a chain from its end. + """ + for short in sorted(nodes, key=len): + if len(short) >= 12 or not _is_hex(short): + continue + exts = [ + other + for other in nodes + if other != short and len(other) > len(short) + and _is_hex(other) and other.startswith(short) + ] + if not exts: + continue + longest = max(exts, key=len) + if all(longest.startswith(ext) for ext in exts): + return short, longest + return None + + +def _is_hex(value: str) -> bool: + """Whether every character of ``value`` is a hex digit (endpoint sentinels are not).""" + return bool(value) and all(char in _HEX_DIGITS for char in value) + + +def _pava(values: list[float]) -> list[float]: + """Pool-adjacent-violators: the nearest non-decreasing sequence to ``values`` (L2). + + The engine behind :func:`_pack` — it fits a monotone curve to the desired positions, + merging any run that would step backwards into its weighted mean. + """ + means: list[float] = [] + counts: list[int] = [] + for value in values: + means.append(value) + counts.append(1) + while len(means) > 1 and means[-2] > means[-1]: + m2, c2 = means.pop(), counts.pop() + m1, c1 = means.pop(), counts.pop() + means.append((m1 * c1 + m2 * c2) / (c1 + c2)) + counts.append(c1 + c2) + out: list[float] = [] + for mean, count in zip(means, counts): + out.extend([mean] * count) + return out + + +def _pack(desired: list[float], gap: float) -> list[float]: + """Place ordered nodes as close to their desired ys as a minimum gap allows. + + Given each node's preferred y (the average of its neighbours) in column order, return + ys that stay in that order with at least ``gap`` between neighbours and minimise the + total squared shift — the optimal one-dimensional separation, via isotonic regression: + subtract the running gap, fit a monotone curve (:func:`_pava`), add the gap back. + """ + if not desired: + return [] + shifted = [value - i * gap for i, value in enumerate(desired)] + fitted = _pava(shifted) + return [value + i * gap for i, value in enumerate(fitted)] + + def render_path_graph( layers: Sequence[PathLayer], width: int, @@ -106,23 +285,21 @@ def render_path_graph( """Draw the layered route graph and return its ANSI lines. Args: - layers: The paths to draw, in *lane* order (the first rides the centre line, - the next fans below, the next above, …). Layers with identical hop - sequences collapse to one drawn path owned by the highest priority among - them — re-walking a known route highlights it rather than doubling it. + layers: The paths to draw, in draw order (later layers, and higher priorities, + win shared cells). Layers with identical hop sequences collapse to one drawn + path owned by the highest priority among them. width: Canvas width in character cells. glyph_of: Marker glyph + colour per node id (endpoints keyed by :data:`SRC_NODE` / :data:`DST_NODE`). label_of: Label text per node id (``None``/``""`` = bare marker). A label is kept whole unless it is wider than the canvas, when it is ellipsized to fit. label_rgb_of: Label colour per node id. - min_rows: The fewest canvas rows to draw, however flat the fan. - max_rows: The most canvas rows to spend; a taller fan compresses its lane + min_rows: The fewest canvas rows to draw, however flat the graph. + max_rows: The most canvas rows to spend; a taller graph compresses its lane spacing to fit. - lane_step: Vertical dot separation between adjacent path lanes. A smaller step - packs the fan into a shallower band, so the segments leaving each endpoint - run closer to horizontal — flatter, less acute angles — at the cost of the - lanes sitting nearer each other. Defaults to :data:`_LANE_STEP_DOTS`. + lane_step: Vertical dot separation aimed for between column-mates. A smaller step + packs the graph into a shallower band; a larger one opens the branch angles + up. Bounded by the row budget either way. Defaults to :data:`_LANE_STEP_DOTS`. Returns: One ANSI string per canvas row (empty when there are no layers to draw). @@ -130,114 +307,246 @@ def render_path_graph( if not layers: return [] - # Collapse identical paths onto their highest-priority layer, preserving first - # appearance for lane order; then fan lanes over the relayed paths (a direct - # path rides the centre line anyway): 0, -1, 1, -2, 2… - drawn: list[PathLayer] = [] - by_hops: dict[tuple[str, ...], int] = {} - for layer in layers: - at = by_hops.get(layer.hops) - if at is None: - by_hops[layer.hops] = len(drawn) - drawn.append(layer) - elif layer.priority > drawn[at].priority: - drawn[at] = PathLayer(layer.hops, layer.color, layer.priority) - relayed = [layer.hops for layer in drawn if layer.hops] - lane_of = {hops: (-1) ** k * ((k + 1) // 2) for k, hops in enumerate(relayed)} - - # Positions: a node's depth is its mean relative slot along the paths through - # it; the distinct depths then map to evenly spaced columns (endpoints pinned - # to the margins). y is the mean lane, centre-pinned for the endpoints — a - # shared relay averages toward the middle. - rel: dict[str, list[float]] = {} - lanes: dict[str, list[int]] = {} + drawn = _collapse(_coalesce_prefixes(layers)) seqs = [(SRC_NODE, *layer.hops, DST_NODE) for layer in drawn] - for layer, seq in zip(drawn, seqs): - hops = len(seq) - 1 - for i, node in enumerate(seq): - rel.setdefault(node, []).append(i / hops) - lanes.setdefault(node, []).append(lane_of.get(layer.hops, 0)) - depth = {node: sum(r) / len(r) for node, r in rel.items()} - columns = sorted(set(depth.values())) - slot = {d: i / max(1, len(columns) - 1) for i, d in enumerate(columns)} - lane_y = { - node: sum(l) / len(l) - for node, l in lanes.items() - if node not in (SRC_NODE, DST_NODE) - } - # Height follows where the relays actually land after lane-averaging — and how - # far the fan reaches *each* way, which is rarely symmetric (lanes fan 0, −1, +1, - # −2, …). Sizing to the real up/down reach and centring the endpoints' lane-0 - # line on it keeps the box off the empty half a mirrored block would leave. - step = lane_step - ups = -min([0.0, *lane_y.values()]) # lanes rising above the lane-0 line - downs = max([0.0, *lane_y.values()]) # …and dropping below it + # First-appearance order for every node and edge, so the layout is identical on every + # repaint: a set of hash-seeded string ids would iterate in a run-varying order and let + # the ordering pass settle differently each time, making the graph jump between frames. + ordered_nodes: list[str] = [] + ordered_edges: list[tuple[str, str]] = [] + seen_nodes: set[str] = set() + seen_edges: set[tuple[str, str]] = set() + for seq in seqs: + for node in seq: + if node not in seen_nodes: + seen_nodes.add(node) + ordered_nodes.append(node) + for u, v in zip(seq, seq[1:]): + if (u, v) not in seen_edges: + seen_edges.add((u, v)) + ordered_edges.append((u, v)) - def sized(step: int) -> tuple[int, int]: - return (round(ups * step) + _GRAPH_END_DOTS, - round(downs * step) + _GRAPH_END_DOTS) + # -- Ranks (columns): the longest path (in edges) from the source to each node. Ranking + # by longest path — not merely a node's furthest position in some one sequence — is what + # guarantees every edge steps strictly forward (``rank(v) ≥ rank(u) + 1``): a relay that + # one route reaches late is seated in the deeper column, so no edge ever doubles back or + # runs *within* a column (which would draw as a stray vertical bar). The right endpoint, + # the sink of every path, takes the deepest rank of all. Relaxed to a fixed point, capped + # at the node count so a pathological order-flipped pair can't spin it forever. + rank: dict[str, int] = {node: 0 for node in ordered_nodes} + for _ in range(len(ordered_nodes)): + changed = False + for u, v in ordered_edges: + if rank[v] < rank[u] + 1: + rank[v] = rank[u] + 1 + changed = True + if not changed: + break + max_rank = max(rank.values()) + + # -- Edges routed. An edge that spans more than one column is broken over invisible + # waypoints, one per crossed column, so the drawn line bends around the nodes between its + # ends instead of cutting across them. ``route`` maps each directed edge to the full + # waypoint chain the drawing pass threads its line through. + route: dict[tuple[str, str], list[str]] = {} + nodes: dict[str, _LayoutNode] = {} + + def ensure(node: str, node_rank: int, real: bool) -> None: + if node not in nodes: + nodes[node] = _LayoutNode(node=node, rank=node_rank, real=real) + + for node in ordered_nodes: + ensure(node, rank[node], real=True) + + virtual = 0 + for u, v in ordered_edges: + chain = [u] + for r in range(rank[u] + 1, rank[v]): + vid = f"{_VIRTUAL_PREFIX}{virtual}" + virtual += 1 + ensure(vid, r, real=False) + chain.append(vid) + chain.append(v) + route[(u, v)] = chain + + columns: dict[int, list[str]] = defaultdict(list) + for node in nodes.values(): + columns[node.rank].append(node.node) + + # -- Adjacency over the routed (waypoint-inclusive) graph, for ordering + straightening. + adjacent: dict[str, list[str]] = defaultdict(list) + for chain in route.values(): + for a, b in zip(chain, chain[1:]): + adjacent[a].append(b) + adjacent[b].append(a) + + _order_columns(columns, adjacent, nodes) + extent = _place_columns(columns, adjacent, nodes) + + # -- Vertical sizing: fill the row budget with the graph's real extent, stretching a + # sparse graph (bounded) for airier angles and compressing a busy one to fit. + if extent <= 0: + step = 0.0 + rows = min_rows + else: + ideal = extent * lane_step + 2 * _GRAPH_END_DOTS + rows = max(min_rows, min(max_rows, ceil(ideal / 4))) + avail = rows * 4 - 2 * _GRAPH_END_DOTS + step = min(avail / extent, lane_step * _MAX_STRETCH) - top, bot = sized(step) - rows = max(min_rows, ceil((top + bot) / 4)) - if rows > max_rows: - rows = max_rows - reach = ups + downs - if reach: - step = max(4, int((rows * 4 - 2 * _GRAPH_END_DOTS) / reach)) - top, bot = sized(step) canvas = MapCanvas(width, rows) dot_w = width * 2 - cy = _mid_row(top) span = dot_w - 2 * _GRAPH_PAD_DOTS + min_y = min(node.y for node in nodes.values()) + band = extent * step + top = (rows * 4 - band) / 2 # centre the real extent in the chosen rows - def pos(node: str) -> tuple[int, int]: - x = _GRAPH_PAD_DOTS + round(slot[depth[node]] * span) - if node in (SRC_NODE, DST_NODE): - return x, cy - return x, _mid_row(cy + round(lane_y[node] * step)) + def x_of(node_rank: int) -> int: + return _GRAPH_PAD_DOTS + round(node_rank / max_rank * span) if max_rank else dot_w // 2 - # Edges: ascending priority, so where paths share cells the top layer is drawn - # last and keeps them. + pos: dict[str, tuple[int, int]] = {} + for node in nodes.values(): + pos[node.node] = (x_of(node.rank), _mid_row(top + (node.y - min_y) * step)) + mid_y = rows * 2 # canvas vertical middle, in dots — the side labels push away from + + # -- Edges: ascending priority, so where paths share cells the top layer draws last + # and keeps them. Each layer threads its line through the waypoint chain of every edge. for layer, seq in sorted(zip(drawn, seqs), key=lambda ls: ls[0].priority): - for i in range(len(seq) - 1): - canvas.draw_line([pos(seq[i]), pos(seq[i + 1])], layer.color, layer.priority) + for u, v in zip(seq, seq[1:]): + points = [pos[node] for node in route[(u, v)]] + canvas.draw_line(points, layer.color, layer.priority) - # Markers for every node; labels for the nodes the caller names. Endpoints then - # the topmost layer's hops go first so they win collisions. Every label sits - # straight above or below its marker — the side away from the centre line first, - # a spot clear of the drawn lines preferred — with a beside-the-marker placement - # as the endpoints' last resort (their edge columns can starve a centred run). - for node in rel: - glyph, color_hex = glyph_of(node) - canvas.marker(*pos(node), glyph, parse_hex(color_hex)) - labelled = [DST_NODE, SRC_NODE] - for layer in sorted(drawn, key=lambda l: -l.priority): - for hop in layer.hops: - if hop not in labelled: - labelled.append(hop) - for node in labelled: + # -- Markers for every real node; waypoints stay line-only. + for node in nodes.values(): + if not node.real: + continue + glyph, color_hex = glyph_of(node.node) + canvas.marker(*pos[node.node], glyph, parse_hex(color_hex)) + + _place_labels(canvas, nodes, pos, width, mid_y, label_of, label_rgb_of) + return canvas.to_ansi_lines() + + +def _order_columns( + columns: dict[int, list[str]], + adjacent: dict[str, list[str]], + nodes: dict[str, _LayoutNode], +) -> None: + """Order the nodes within each column to reduce edge crossings (barycentre sweeps). + + Starting from first-appearance order, each node is repeatedly re-seated at the mean + position of its neighbours in the column just settled — down the ranks, then up — + which is the standard cheap crossing-minimiser. A node with no neighbour in the + reference column keeps its place. The results are written back as each node's + ``order`` (its index within the column). + """ + order: dict[str, int] = {} + for column in columns.values(): + for i, node in enumerate(column): + order[node] = i + + max_rank = max(columns) + + def barycentre(node: str, ref_rank: int) -> float: + refs = [order[n] for n in adjacent[node] if nodes[n].rank == ref_rank] + return sum(refs) / len(refs) if refs else float(order[node]) + + for _ in range(_ORDER_SWEEPS): + for r in range(1, max_rank + 1): + columns[r].sort(key=lambda n: barycentre(n, r - 1)) # noqa: B023 - r is bound per loop + for i, node in enumerate(columns[r]): + order[node] = i + for r in range(max_rank - 1, -1, -1): + columns[r].sort(key=lambda n: barycentre(n, r + 1)) # noqa: B023 - r is bound per loop + for i, node in enumerate(columns[r]): + order[node] = i + + for column in columns.values(): + for i, node in enumerate(column): + nodes[node].order = i + + +def _place_columns( + columns: dict[int, list[str]], + adjacent: dict[str, list[str]], + nodes: dict[str, _LayoutNode], +) -> float: + """Assign each node a vertical coordinate (layout units) and return the total extent. + + Seeded from the column orders, every node is pulled toward the average height of its + neighbours and its column re-separated to the minimum lane gap (:func:`_pack`) — a few + passes each way. This straightens each route into a near-level lane while keeping + branches apart; an endpoint, being the lone node in its column, drifts to the centroid + of its own branches so the whole fan reads as leaving (or arriving at) one point. + Returns ``max_y - min_y`` across all nodes, the height the caller scales to the canvas. + """ + for column in columns.values(): + for node in column: + nodes[node].y = float(nodes[node].order) + + max_rank = max(columns) + ranks_desc = list(range(max_rank + 1)) + + def relax(order_of_ranks: list[int]) -> None: + for r in order_of_ranks: + column = columns[r] + desired = [] + for node in column: + neighbours = adjacent[node] + if neighbours: + desired.append(sum(nodes[n].y for n in neighbours) / len(neighbours)) + else: + desired.append(nodes[node].y) + for node, y in zip(column, _pack(desired, _MIN_LANE_GAP)): + nodes[node].y = y + + for _ in range(_PLACE_ITERS): + relax(ranks_desc) + relax(ranks_desc[::-1]) + + ys = [node.y for node in nodes.values()] + return max(ys) - min(ys) + + +def _place_labels( + canvas: MapCanvas, + nodes: dict[str, _LayoutNode], + pos: dict[str, tuple[int, int]], + width: int, + mid_y: int, + label_of: LabelOf, + label_rgb_of: LabelRgbOf, +) -> None: + """Write each real node's label above or below its marker, clear of the lines if it can. + + Endpoints first, then relays column by column, so the named ends win any contest for a + cell. Each label is tried on the side away from the graph's middle first (spreading the + text outward off the busy centre), preferring a row the drawn lines don't already + occupy; an endpoint, hard against a canvas edge, slides its anchor inward far enough for + the whole name to land, and falls back to sitting beside its marker. A name is only + ever shortened when it is wider than the entire canvas. + """ + endpoints = [n for n in (DST_NODE, SRC_NODE) if n in nodes] + relays = [ + layout.node + for layout in sorted(nodes.values(), key=lambda n: (n.rank, n.order)) + if layout.real and layout.node not in (SRC_NODE, DST_NODE) + ] + for node in [*endpoints, *relays]: label = label_of(node) if not label: continue - # A name only shortens when it is wider than the whole canvas — there is - # physically nowhere for the extra cells to go. Anything that fits the width is - # kept whole and handed to the placement pass below, which slides an endpoint's - # label inward (or drops a crowded relay's) rather than pre-clipping a name that - # would have fit. if len(label) > width: label = label[: max(1, width - 1)] + "…" rgb = label_rgb_of(node) - x, y = pos(node) - # An endpoint hugs a canvas edge, where a run centred on its marker falls - # off; its label anchor slides inward just far enough to fit, so the name - # still lands above/below the star instead of being dropped. + x, y = pos[node] anchor_x = x if node in (SRC_NODE, DST_NODE): half = len(label) // 2 cx = min(max(x >> 1, half), max(half, width - (len(label) - half))) anchor_x = cx * 2 - rows_out = (y - 4, y + 4) if y <= cy else (y + 4, y - 4) + rows_out = (y - 4, y + 4) if y <= mid_y else (y + 4, y - 4) if any( canvas.place_label(anchor_x, sy, label, rgb, bold=True, avoid_dots=True) for sy in rows_out @@ -250,4 +559,3 @@ def render_path_graph( if node in (SRC_NODE, DST_NODE): if not canvas.marker_label(x, y, label, rgb, avoid_dots=True): canvas.marker_label(x, y, label, rgb) - return canvas.to_ansi_lines() diff --git a/meshterm/ui/records_screen.py b/meshterm/ui/records_screen.py index 29e5cc8..dccce77 100644 --- a/meshterm/ui/records_screen.py +++ b/meshterm/ui/records_screen.py @@ -222,12 +222,12 @@ class RecordDialog(Screen): """Draw the walked route as one path on THE route graph — us at both ends. A scored walk leaves home and comes back, so it draws us (left) → its relays → - us (right) as a single white path through the shared fan-lane widget + us (right) as a single white path through the shared route-graph widget (:func:`~meshterm.ui.pathgraph.render_path_graph`), the same shape the Message paths dialog draws a delivery over. Relays wear their own map marker (``▲`` repeater, …) where the type is known. Nodes the walk passed through more than once — a boomerang's mirrored return leg — collapse to their first appearance: the - depth-ordered graph can only seat a node once, and the route line below still + layered graph can only seat a node once, and the route line below still carries every hop, revisits and all. """ seen: set[str] = set() diff --git a/tests/test_node_detail.py b/tests/test_node_detail.py index 7b15b80..ba57ad7 100644 --- a/tests/test_node_detail.py +++ b/tests/test_node_detail.py @@ -146,7 +146,7 @@ def test_route_and_suggest_rows_speak_the_evidence() -> None: resolve = make_node_resolver([HUB, FAR]) learned = _plain([_route_row(("3d63c6429436",), resolve=resolve, self_name="Us").plain]) assert "device route" in learned and "Hub" in learned - assert "(3d)" in learned # the first-byte tag, matching the graph's byte label + assert "(3d)" in learned # the row tags each hop with its first hash byte assert "floods" in _route_row(None, resolve=resolve, self_name="Us").plain # no route best = topo.suggested("f2c24f54551e") @@ -198,8 +198,46 @@ def test_path_view_puts_us_on_the_left_and_the_target_on_the_right() -> None: assert view.glyph_of(SRC_NODE)[0] == "★" # the left endpoint is our own star assert view.label_of(SRC_NODE) == "Us" # …labelled as us assert view.label_of(DST_NODE) == "Far" # the right endpoint is the target - # A relay resolves to its first hash byte, wherever it lands between the endpoints. - assert view.label_of("3d63c6429436") == "3d" + # This page names every node: a known relay reads by its contact name, not its hash byte. + assert view.label_of("3d63c6429436") == "Hub" + + +def test_path_view_relay_falls_back_to_the_hash_byte_when_unnamed() -> None: + """A relay no contact can name keeps the honest first-byte tag rather than a blank.""" + topo = _topo_with_route() + view = _path_view( + topo, topo.scenarios("f2c24f54551e", device_route=("abcd1234ef56",)), + None, ("abcd1234ef56",), "f2c24f54551e", + resolve=make_node_resolver([FAR]), # the relay abcd… is not among the contacts + type_of=make_node_type_resolver([FAR]), + key_of=make_name_key_resolver([FAR]), + style=route_graph_style, self_name="Us", node_label="Far", + ) + assert view.label_of("abcd1234ef56") == "ab" # unnamed → its first hash byte + + +def test_path_view_target_wears_its_node_type_glyph() -> None: + """The right endpoint draws the target's own map mark (a repeater ▲), not a plain dot.""" + from meshterm.persistence.repository import TracedPath + from meshterm.ui.pathgraph import DST_NODE + + leaf = Contact(name="Leaf", public_key="27d4396a2967" + "0" * 52, key_prefix="27d4396a2967") + # Reach the Hub (a repeater) through the Leaf, so the Hub is the drawn right endpoint. + walks = [ + TracedPath(when=utcnow(), hops=[("27d4", 8.0), ("3d", 6.0), ("27d4", 6.0), (None, 8.0)]) + for _ in range(3) + ] + topo = build_topology(self_id=US + "0" * 52, contacts=[HUB, leaf], + trace_paths=walks, packet_paths=[], neighbour_links=[]) + view = _path_view( + topo, topo.scenarios("3d63c6429436"), topo.suggested("3d63c6429436"), + None, "3d63c6429436", + resolve=make_node_resolver([HUB, leaf]), + type_of=make_node_type_resolver([HUB, leaf]), + key_of=make_name_key_resolver([HUB, leaf]), + style=route_graph_style, self_name="Us", node_label="Hub", + ) + assert view.glyph_of(DST_NODE)[0] == "▲" # the repeater target keeps its own glyph def test_located_accepts_real_fixes_and_rejects_junk() -> None: diff --git a/tests/test_pathgraph.py b/tests/test_pathgraph.py index 0f57db6..c23f778 100644 --- a/tests/test_pathgraph.py +++ b/tests/test_pathgraph.py @@ -4,13 +4,20 @@ from __future__ import annotations import re -from meshterm.ui.pathgraph import DST_NODE, SRC_NODE, PathLayer, render_path_graph +from meshterm.ui.pathgraph import ( + DST_NODE, + SRC_NODE, + PathLayer, + _coalesce_prefixes, + render_path_graph, +) _ANSI = re.compile(r"\x1b\[[0-9;]*m") WHITE = (255, 255, 255) GREEN = (74, 222, 128) YELLOW = (250, 204, 21) +GREY = (120, 120, 120) def _glyph(node: str) -> tuple[str, str]: @@ -92,6 +99,36 @@ def test_endpoint_labels_may_leave_the_marker_row() -> None: assert "…" not in plain +def test_prefix_dupe_relay_folds_onto_its_only_wide_match() -> None: + """A 1-byte hop beside the same node's wide id, across layers, becomes one node.""" + layers = [ + PathLayer(("e9043958308d", "be"), WHITE, 3), + PathLayer(("3d63c6429436", "be1d1c1dbc4b"), GREY, 2), + ] + out = _coalesce_prefixes(layers) + assert out[0].hops == ("e9043958308d", "be1d1c1dbc4b") # "be" rewritten to the wide id + assert out[1].hops == ("3d63c6429436", "be1d1c1dbc4b") + + +def test_ambiguous_prefix_relay_is_left_alone() -> None: + """A short hop that prefixes two distinct present nodes is not guessed onto either.""" + layers = [ + PathLayer(("be",), WHITE, 3), + PathLayer(("be1d1c1dbc4b",), GREY, 2), + PathLayer(("bedd2bff0011",), GREY, 2), + ] + out = _coalesce_prefixes(layers) + assert out[0].hops == ("be",) # opens two present nodes — kept as its honest short self + + +def test_a_shared_relay_draws_a_single_marker() -> None: + """A relay two paths pass through is one vertex, labelled once — never doubled.""" + layers = [PathLayer(("aa", "bb"), WHITE, 3), PathLayer(("cc", "bb"), YELLOW, 2)] + plain = _ANSI.sub("", "\n".join(_render(layers))) + assert plain.count("bb") == 1 # the shared relay is seated once + assert plain.count("aa") == 1 and plain.count("cc") == 1 + + def test_labels_ellipsize_only_when_wider_than_the_canvas() -> None: """A name shortens only when it physically cannot fit — wider than the whole canvas.""" name = "x" * 30 diff --git a/tests/test_topology.py b/tests/test_topology.py index 1da97ef..1988f18 100644 --- a/tests/test_topology.py +++ b/tests/test_topology.py @@ -73,6 +73,34 @@ def test_canonicalization_maps_prefixes_and_rejects_junk() -> None: assert ambiguous.canonical("3d") == "3d" # two contacts match: keep the short id +def test_coalesce_folds_a_short_hop_into_its_only_wide_match() -> None: + """A bare hop beside the same node's wide id collapses to one node, its evidence pooled.""" + twin = Contact(name="Twin", public_key="27e4" + "0" * 60) # makes a bare "27" ambiguous + walks = [ + _traced(("27", 5.0), ("f2", -3.0), ("27", -3.5), (None, 5.0)), # us→27→Far + _traced(("27d4", 7.0), ("f2", -4.0), ("27d4", -4.5), (None, 7.0)), # us→27d4→Far + ] + topo = _topo(trace_paths=walks, contacts=[REPEATER, FAR, LEAF, twin]) + ids = {node for link in topo.links() for node in (link.a, link.b)} + assert "27" not in ids # the 1-byte stub folded onto its only wide match in the graph + assert "27d4396a2967" in ids + link = topo.link(topo.self_id, "27d4396a2967") + assert link is not None and link.samples == 4 # both walks' out+back readings pooled + + +def test_coalesce_leaves_a_genuinely_ambiguous_stub_alone() -> None: + """A short hop that opens two nodes both present in the graph is not guessed onto one.""" + twin = Contact(name="Twin", public_key="27e41e2d7cb5" + "0" * 52, key_prefix="27e41e2d7cb5") + walks = [ # both 27d4… and 27e4… land in the graph, plus a bare, undecidable 27 + _traced(("27d4", 5.0), (None, 5.0)), + _traced(("27e4", 5.0), (None, 5.0)), + _traced(("27", 5.0), (None, 5.0)), + ] + topo = _topo(trace_paths=walks, contacts=[REPEATER, FAR, LEAF, twin]) + ids = {node for link in topo.links() for node in (link.a, link.b)} + assert {"27", "27d4396a2967", "27e41e2d7cb5"} <= ids # the stub stays its own node + + def test_contact_routes_and_packet_paths_feed_the_graph() -> None: """Firmware-learned routes and RX-logged packet paths both count as evidence.""" routed = Contact(