Frame the map's dense node core by default, tunable with --fraction
The default view fitted every located node, so a few distant outliers (here a node near Toronto, 500+ km from the Montréal core) zoomed the whole mesh out to a continental scale. Frame the densest half instead — the nodes nearest the median centre — so the map opens on a useful local region; the rest simply fall off the edges. Verified against a live 159-node mesh: 0.5 lands on the Greater Montréal metro (~77 km across, two-thirds of nodes visible) rather than eastern Canada. Viewport.fit gains a `fraction` argument (default 1.0, unchanged for existing callers); the map's opening view and `r` reset pass 0.5, and `meshterm map --fraction/-f` exposes the knob on the CLI. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
61f4eff8dc
commit
97557fc9b8
4 files changed
+124
-11
No files matched your search
+38
-2
@@ -78,6 +78,35 @@ def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
return 2 * EARTH_RADIUS_KM * math.asin(math.sqrt(a))
|
||||
|
||||
|
||||
def _central_points(
|
||||
points: list[tuple[float, float]], fraction: float
|
||||
) -> list[tuple[float, float]]:
|
||||
"""Return the ``fraction`` of ``points`` nearest their median centre (the dense core).
|
||||
|
||||
The centre is the per-axis *median* so outliers don't drag it, and points are ranked by
|
||||
great-circle distance from it. At least two points are always kept (so the result still
|
||||
constrains a zoom), and the whole list is returned once the kept count reaches it.
|
||||
|
||||
Args:
|
||||
points: Latitude/longitude pairs (non-empty).
|
||||
fraction: Portion to keep, ``0 < fraction <= 1``.
|
||||
|
||||
Returns:
|
||||
The closest ``ceil(len(points) * fraction)`` points (min 2), or all of them.
|
||||
"""
|
||||
n = len(points)
|
||||
keep = max(2, math.ceil(n * fraction))
|
||||
if keep >= n:
|
||||
return points
|
||||
lats = sorted(lat for lat, _ in points)
|
||||
lons = sorted(lon for _, lon in points)
|
||||
mid = n // 2
|
||||
med_lat = lats[mid] if n % 2 else (lats[mid - 1] + lats[mid]) / 2
|
||||
med_lon = lons[mid] if n % 2 else (lons[mid - 1] + lons[mid]) / 2
|
||||
ordered = sorted(points, key=lambda p: haversine_km(p[0], p[1], med_lat, med_lon))
|
||||
return ordered[:keep]
|
||||
|
||||
|
||||
def clamp_lat(lat: float) -> float:
|
||||
"""Clamp latitude to the Web Mercator limit (~±85.051°) where the projection is finite."""
|
||||
return max(-85.05112878, min(85.05112878, lat))
|
||||
@@ -247,6 +276,7 @@ class Viewport:
|
||||
min_zoom: int = 2,
|
||||
max_zoom: int = 16,
|
||||
default_zoom: int = 14,
|
||||
fraction: float = 1.0,
|
||||
) -> "Viewport":
|
||||
"""Build a viewport framing ``points`` — centred on them at the tightest fitting zoom.
|
||||
|
||||
@@ -258,13 +288,19 @@ class Viewport:
|
||||
min_zoom: Lowest zoom to consider.
|
||||
max_zoom: Highest zoom to consider.
|
||||
default_zoom: Zoom used when the points don't constrain it (0 or 1 point).
|
||||
fraction: Fraction of the points to actually frame, ``0 < fraction <= 1``. Below
|
||||
``1`` only the densest core — the points nearest the median centre — is framed,
|
||||
so a handful of distant outliers can't force the whole view to zoom out. The
|
||||
remaining nodes simply fall off the edges.
|
||||
|
||||
Returns:
|
||||
A :class:`Viewport` centred on the points at a zoom where they fit with margin.
|
||||
Empty input centres on the world at ``min_zoom``.
|
||||
A :class:`Viewport` centred on the framed points at a zoom where they fit with
|
||||
margin. Empty input centres on the world at ``min_zoom``.
|
||||
"""
|
||||
if not points:
|
||||
return cls(0.0, 0.0, min_zoom, dot_w, dot_h)
|
||||
if fraction < 1.0:
|
||||
points = _central_points(points, fraction)
|
||||
box = BBox.around(points)
|
||||
center_lat, center_lon = box.center
|
||||
if len(points) == 1 or (box.min_lat == box.max_lat and box.min_lon == box.max_lon):
|
||||
|
||||
+28
-6
@@ -61,9 +61,11 @@ class MapTool(Tool):
|
||||
|
||||
interactive = isinstance(ctx.ui, TuiUi) and not params.get("static")
|
||||
if interactive:
|
||||
from ..ui.map_screen import open_map
|
||||
from ..ui.map_screen import DEFAULT_VIEW_FRACTION, open_map
|
||||
|
||||
await open_map(ctx, markers)
|
||||
await open_map(
|
||||
ctx, markers, fraction=params.get("fraction", DEFAULT_VIEW_FRACTION)
|
||||
)
|
||||
else:
|
||||
await self._render_static(ctx, markers, params)
|
||||
|
||||
@@ -172,7 +174,7 @@ class MapTool(Tool):
|
||||
|
||||
from ..core.geo import Viewport
|
||||
from ..ui.map_render import render_map
|
||||
from ..ui.map_screen import basemap_source
|
||||
from ..ui.map_screen import DEFAULT_VIEW_FRACTION, basemap_source
|
||||
|
||||
cell_w = int(params.get("width") or min(ctx.console.size.width - 2, 160))
|
||||
cell_h = max(12, cell_w * 4 // 13) # keep roughly the terminal's aspect
|
||||
@@ -187,7 +189,13 @@ class MapTool(Tool):
|
||||
center = BBox.around(coords).center
|
||||
vp = Viewport(center[0], center[1], int(params["zoom"]), dot_w, dot_h)
|
||||
else:
|
||||
vp = Viewport.fit(coords, dot_w, dot_h, max_zoom=max_zoom)
|
||||
vp = Viewport.fit(
|
||||
coords,
|
||||
dot_w,
|
||||
dot_h,
|
||||
max_zoom=max_zoom,
|
||||
fraction=params.get("fraction", DEFAULT_VIEW_FRACTION),
|
||||
)
|
||||
|
||||
tiles = {}
|
||||
if params.get("basemap", True):
|
||||
@@ -205,6 +213,7 @@ class MapTool(Tool):
|
||||
app: The Typer application.
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
from ..ui.map_screen import DEFAULT_VIEW_FRACTION
|
||||
|
||||
@app.command(name=self.name, help=self.help)
|
||||
def _map(
|
||||
@@ -212,13 +221,26 @@ class MapTool(Tool):
|
||||
None, "--width", "-w", help="Map width in character cells."
|
||||
),
|
||||
zoom: Optional[int] = typer.Option(
|
||||
None, "--zoom", "-z", help="Fixed zoom level (omit to fit all nodes)."
|
||||
None, "--zoom", "-z", help="Fixed zoom level (omit to fit the nodes)."
|
||||
),
|
||||
fraction: float = typer.Option(
|
||||
DEFAULT_VIEW_FRACTION,
|
||||
"--fraction",
|
||||
"-f",
|
||||
min=0.0,
|
||||
max=1.0,
|
||||
help="Fraction of nodes to frame: the densest that many, so distant "
|
||||
"outliers don't zoom the view out. 1.0 fits every node. Ignored with --zoom.",
|
||||
),
|
||||
basemap: bool = typer.Option(
|
||||
True, "--basemap/--no-basemap", help="Draw the OpenStreetMap street basemap."
|
||||
),
|
||||
) -> None:
|
||||
params: dict[str, Any] = {"static": True, "basemap": basemap}
|
||||
if not 0.0 < fraction <= 1.0:
|
||||
raise typer.BadParameter("--fraction must be greater than 0 and at most 1")
|
||||
params: dict[str, Any] = {
|
||||
"static": True, "basemap": basemap, "fraction": fraction,
|
||||
}
|
||||
if width is not None:
|
||||
params["width"] = width
|
||||
if zoom is not None:
|
||||
|
||||
@@ -9,7 +9,8 @@ render_map`. Keys:
|
||||
* holding **Shift** (Shift+arrows, or the uppercase ``W`` / ``A`` / ``S`` / ``D``) pans by a
|
||||
single character cell for fine positioning,
|
||||
* ``=`` / ``+`` zoom in, ``-`` / ``_`` zoom out,
|
||||
* ``r`` recenters and refits to the nodes,
|
||||
* ``r`` recenters and refits to the dense core of the nodes (the same default view the map
|
||||
opens on),
|
||||
* ``Esc`` / ``q`` leaves the map.
|
||||
|
||||
With no network (and no cached tiles) the basemap is simply absent and nodes are plotted on a
|
||||
@@ -48,6 +49,10 @@ _PAN_KEYS: dict[str, str] = {"w": "up", "a": "left", "s": "down", "d": "right"}
|
||||
#: How far past the tile source's max zoom the display may go (lower tiles are magnified).
|
||||
_OVERZOOM = 2
|
||||
|
||||
#: Default fraction of nodes the map frames on open — the densest half, so a few distant
|
||||
#: outliers don't zoom the whole mesh out to a continent. See :meth:`geo.Viewport.fit`.
|
||||
DEFAULT_VIEW_FRACTION = 0.5
|
||||
|
||||
|
||||
class MapScreen(Screen):
|
||||
"""A full-screen, keyboard-driven map of the mesh's located nodes over an OSM basemap."""
|
||||
@@ -63,6 +68,7 @@ class MapScreen(Screen):
|
||||
*,
|
||||
saved_view: Optional[tuple[float, float, int]] = None,
|
||||
on_view_change: Optional[Callable[[Viewport], None]] = None,
|
||||
view_fraction: float = DEFAULT_VIEW_FRACTION,
|
||||
) -> None:
|
||||
"""Create the map screen.
|
||||
|
||||
@@ -75,6 +81,8 @@ class MapScreen(Screen):
|
||||
on, or ``None`` to frame the nodes instead.
|
||||
on_view_change: Called with the viewport whenever the centre or zoom changes, so
|
||||
the caller can persist it. Deduplicated — only actual changes fire it.
|
||||
view_fraction: Fraction of the nodes the default frame (and ``r`` reset) fits —
|
||||
the densest that many, so outliers don't dominate. See :meth:`geo.Viewport.fit`.
|
||||
"""
|
||||
super().__init__()
|
||||
self.title = "mesh map"
|
||||
@@ -84,6 +92,7 @@ class MapScreen(Screen):
|
||||
self._max_tile_zoom = max_tile_zoom
|
||||
self._saved_view = saved_view
|
||||
self._on_view_change = on_view_change
|
||||
self._view_fraction = view_fraction
|
||||
# The view last handed to ``on_view_change``; seeded with the restored view so
|
||||
# reopening unchanged doesn't rewrite it.
|
||||
self._last_saved = saved_view
|
||||
@@ -125,7 +134,11 @@ class MapScreen(Screen):
|
||||
return render_map(self._viewport, tiles, self._markers)
|
||||
|
||||
def _initial_viewport(self, dot_w: int, dot_h: int) -> Viewport:
|
||||
"""Restore the saved view (clamped to sane bounds) or frame the nodes."""
|
||||
"""Restore the saved view (clamped to sane bounds) or frame the nodes' dense core.
|
||||
|
||||
With no saved view the default frames the half of the nodes nearest the median
|
||||
centre, so distant outliers don't zoom the whole mesh out to a useless scale.
|
||||
"""
|
||||
if self._saved_view is not None:
|
||||
lat, lon, zoom = self._saved_view
|
||||
z = max(2, min(int(zoom), self._max_tile_zoom + _OVERZOOM))
|
||||
@@ -135,6 +148,7 @@ class MapScreen(Screen):
|
||||
dot_w,
|
||||
dot_h,
|
||||
max_zoom=self._max_tile_zoom,
|
||||
fraction=self._view_fraction,
|
||||
)
|
||||
|
||||
def _persist(self) -> None:
|
||||
@@ -233,6 +247,7 @@ class MapScreen(Screen):
|
||||
vp.dot_w,
|
||||
vp.dot_h,
|
||||
max_zoom=self._max_tile_zoom,
|
||||
fraction=self._view_fraction,
|
||||
)
|
||||
elif low == "q":
|
||||
self.resolve(None)
|
||||
@@ -243,7 +258,12 @@ def basemap_source(ctx: "AppContext") -> BasemapSource:
|
||||
return BasemapSource(ctx.settings.config_dir / "tilecache")
|
||||
|
||||
|
||||
async def open_map(ctx: "AppContext", markers: list[MapMarker]) -> None:
|
||||
async def open_map(
|
||||
ctx: "AppContext",
|
||||
markers: list[MapMarker],
|
||||
*,
|
||||
fraction: float = DEFAULT_VIEW_FRACTION,
|
||||
) -> None:
|
||||
"""Open the interactive full-screen map over ``markers`` and run until dismissed.
|
||||
|
||||
Warms the tile source off the event loop (so the first paint doesn't block on the
|
||||
@@ -252,6 +272,7 @@ async def open_map(ctx: "AppContext", markers: list[MapMarker]) -> None:
|
||||
Args:
|
||||
ctx: Shared application context (must be in the interactive menu).
|
||||
markers: The located mesh nodes to plot (non-empty).
|
||||
fraction: Fraction of the nodes the default view frames (see :class:`MapScreen`).
|
||||
|
||||
Raises:
|
||||
RuntimeError: If called outside the interactive menu (no full-screen session).
|
||||
@@ -273,5 +294,6 @@ async def open_map(ctx: "AppContext", markers: list[MapMarker]) -> None:
|
||||
on_view_change=lambda vp: ctx.repo.set_map_view(
|
||||
vp.center_lat, vp.center_lon, vp.zoom
|
||||
),
|
||||
view_fraction=fraction,
|
||||
)
|
||||
await session.run_screen(screen)
|
||||
@@ -106,6 +106,39 @@ def test_viewport_fit_frames_all_points() -> None:
|
||||
assert 0 <= x < vp.dot_w and 0 <= y < vp.dot_h # every point is on-canvas
|
||||
|
||||
|
||||
def test_viewport_fit_fraction_ignores_outliers() -> None:
|
||||
"""Framing half the nodes zooms to the dense core, letting far outliers fall off-canvas."""
|
||||
# A tight downtown cluster of five nodes (~50 m across) plus one distant outlier.
|
||||
core = [
|
||||
(45.5000, -73.5600), (45.5003, -73.5602), (45.4998, -73.5598),
|
||||
(45.5001, -73.5599), (45.4999, -73.5601),
|
||||
]
|
||||
outlier = (46.80, -71.20)
|
||||
pts = core + [outlier]
|
||||
|
||||
full = Viewport.fit(pts, 200, 120, max_zoom=16)
|
||||
half = Viewport.fit(pts, 200, 120, max_zoom=16, fraction=0.5)
|
||||
|
||||
# The core-only frame is zoomed in tighter than the frame that must hold the outlier.
|
||||
assert half.zoom > full.zoom
|
||||
# Every clustered node stays on-canvas; the outlier is pushed off.
|
||||
for lat, lon in core:
|
||||
x, y = half.lonlat_to_dot(lat, lon)
|
||||
assert 0 <= x < half.dot_w and 0 <= y < half.dot_h
|
||||
ox, oy = half.lonlat_to_dot(*outlier)
|
||||
assert not (0 <= ox < half.dot_w and 0 <= oy < half.dot_h)
|
||||
|
||||
|
||||
def test_viewport_fit_fraction_keeps_small_sets_whole() -> None:
|
||||
"""With only two nodes there is no core to isolate — both are still framed."""
|
||||
pts = [(45.5019, -73.5674), (45.4768, -73.5990)]
|
||||
half = Viewport.fit(pts, 200, 120, max_zoom=14, fraction=0.5)
|
||||
full = Viewport.fit(pts, 200, 120, max_zoom=14)
|
||||
assert (half.center_lat, half.center_lon, half.zoom) == (
|
||||
full.center_lat, full.center_lon, full.zoom
|
||||
)
|
||||
|
||||
|
||||
def test_viewport_zoom_and_pan() -> None:
|
||||
"""Zooming and panning return new viewports; zoom clamps to its bounds."""
|
||||
vp = Viewport(45.5, -73.6, 10, 200, 120)
|
||||
|
||||
Reference in new issue
Block a user