Files
Muse 934c336667 sgeo --trip: draw the journey as an ordered polyline with time labels
Reads a stag CSV, orders the geotagged rows by their parsed
timestamp (ISO and EXIF-colon forms sort together), and draws the
trip on an OSM map: blue line with white halo, direction arrowhead
per leg, red marker per stop, MM-DD HH:MM label per timestamped
stop. Rows without a timestamp go last in CSV order; rows without
coordinates are skipped. Reuses sgeo tile/zoom/marker code via
shared fetch_tiles/draw_attribution helpers. Tests: 11/11 in
tests/run_tests.sh (3 new trip cases + tests/check_trip.py).
Docs: docs/trip-path.md.
2026-12-02 09:36:30 +00:00

339 lines
12 KiB
Python

#!/usr/bin/env python3
"""Check a trip.png produced by `sgeo --trip` (stdlib only).
Usage: check_trip.py trip.csv trip.png
Verifies, against the CSV:
- one red marker cluster per geotagged row, centred on the projected
point (projection mirrors sgeo.c: Web Mercator, zoom from the
bounding box, 64px padding);
- a blue polyline leg between consecutive rows in timestamp order:
blue pixels off the midpoint, so the arrowhead alone cannot pass,
and blue at the midpoint too;
- NO blue line where the CSV file order would have connected points
(the first two wrong-order hops), proving the sort actually
happened rather than the file order being drawn;
- a time-label plaque (white + dark text) by every timestamped
marker, and none by an untimestamped marker.
The attribution plaque is checked by check_map.py in the suite.
"""
import csv
import math
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from check_map import read_png
TILE_PX = 256
MAX_TILES = 100
TARGET_W = 900
TARGET_H = 620
PAD_PX = 64
SINGLE_POINT_ZOOM = 15
MAX_ZOOM = 18
MAX_LAT = 85.05112878
def world_px(z):
return TILE_PX * (1 << z)
def lon_to_px(lon, z):
return (lon + 180.0) / 360.0 * world_px(z)
def lat_to_px(lat, z):
lat = max(-MAX_LAT, min(MAX_LAT, lat))
r = math.radians(lat)
return (1.0 - math.asinh(math.tan(r)) / math.pi) / 2.0 * world_px(z)
def compute_range(xs, ys, zoom):
minx, maxx = min(xs), max(xs)
miny, maxy = min(ys), max(ys)
ntiles = 1 << zoom
tx0 = max(0, math.floor((minx - PAD_PX) / TILE_PX))
tx1 = min(ntiles - 1, math.floor((maxx + PAD_PX) / TILE_PX))
ty0 = max(0, math.floor((miny - PAD_PX) / TILE_PX))
ty1 = min(ntiles - 1, math.floor((maxy + PAD_PX) / TILE_PX))
return zoom, tx0, ty0, tx1, ty1
def pick_zoom(pts):
minlon = min(p[1] for p in pts)
maxlon = max(p[1] for p in pts)
minlat = min(p[0] for p in pts)
maxlat = max(p[0] for p in pts)
lon_span = (maxlon - minlon) / 360.0
y0 = lat_to_px(minlat, 0) / world_px(0)
y1 = lat_to_px(maxlat, 0) / world_px(0)
lat_span = abs(y1 - y0)
if lon_span == 0.0 and lat_span == 0.0:
return SINGLE_POINT_ZOOM
zoom = 0
for z in range(MAX_ZOOM, -1, -1):
if (lon_span * world_px(z) <= TARGET_W
and lat_span * world_px(z) <= TARGET_H):
zoom = z
break
while True:
xs = [lon_to_px(p[1], zoom) for p in pts]
ys = [lat_to_px(p[0], zoom) for p in pts]
_, tx0, ty0, tx1, ty1 = compute_range(xs, ys, zoom)
if (tx1 - tx0 + 1) * (ty1 - ty0 + 1) <= MAX_TILES or zoom == 0:
return zoom
zoom -= 1
def parse_time(s):
"""Mirror sgeo's parse_trip_time: ISO or EXIF-colon, date-only ok.
Returns a dict, or None."""
m = re.match(r"^(\d+)-(\d+)-(\d+)(?: (\d+):(\d+)(?::(\d+))?)?$", s or "")
if not m:
m = re.match(r"^(\d+):(\d+):(\d+)(?: (\d+):(\d+)(?::(\d+))?)?$",
s or "")
if not m:
return None
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
has_clock = m.group(5) is not None
h = int(m.group(4) or 0) if has_clock else 0
mi = int(m.group(5) or 0) if has_clock else 0
sec = int(m.group(6) or 0) if has_clock else 0
if not (1 <= mo <= 12 and 1 <= d <= 31 and 0 <= h <= 23
and 0 <= mi <= 59 and 0 <= sec <= 59):
return None
key = (((((y * 12 + (mo - 1)) * 31 + (d - 1)) * 24 + h) * 60 + mi)
* 60 + sec)
return {"key": key, "has_clock": has_clock, "mo": mo, "dy": d,
"hh": h, "mi": mi}
def label_text(t):
if t["has_clock"]:
return "%02d-%02d %02d:%02d" % (t["mo"], t["dy"], t["hh"], t["mi"])
return "%02d-%02d" % (t["mo"], t["dy"])
def label_rect(mx, my, text, w, h):
"""Mirror sgeo's draw_time_label placement."""
tw = len(text) * 6 - 1
lx, ly = mx + 12, my - 18
if lx + tw + 8 > w:
lx = mx - 12 - (tw + 8)
if lx < 0:
lx = 0
if ly < 0:
ly = my + 12
if ly + 13 > h:
ly = h - 13
if ly < 0:
ly = 0
return lx, ly, tw + 8, 13
def dist_pt_seg(px, py, x0, y0, x1, y1):
dx, dy = x1 - x0, y1 - y0
dd = dx * dx + dy * dy
if dd == 0:
return math.hypot(px - x0, py - y0)
t = max(0.0, min(1.0, ((px - x0) * dx + (py - y0) * dy) / dd))
return math.hypot(px - (x0 + t * dx), py - (y0 + t * dy))
def main():
csv_path, png_path = sys.argv[1], sys.argv[2]
rows = []
with open(csv_path, newline="") as f:
for i, row in enumerate(csv.DictReader(f)):
if not row["latitude"] or not row["longitude"]:
continue
t = parse_time(row["timestamp"])
rows.append({
"file": row["file"],
"lat": float(row["latitude"]),
"lon": float(row["longitude"]),
"order": i,
"time": t,
})
ordered = sorted(rows, key=lambda r: (r["time"] is None,
r["time"]["key"] if r["time"] else 0,
r["order"]))
pts = [(r["lat"], r["lon"]) for r in ordered]
zoom = pick_zoom(pts)
xs = [lon_to_px(p[1], zoom) for p in pts]
ys = [lat_to_px(p[0], zoom) for p in pts]
_, tx0, ty0, tx1, ty1 = compute_range(xs, ys, zoom)
w, h, px = read_png(png_path)
assert w == (tx1 - tx0 + 1) * TILE_PX, "width mismatch: %d" % w
assert h == (ty1 - ty0 + 1) * TILE_PX, "height mismatch: %d" % h
ox, oy = tx0 * TILE_PX, ty0 * TILE_PX
mx = [int(round(x)) - ox for x in xs]
my = [int(round(y)) - oy for y in ys]
def rgb(x, y):
o = (y * w + x) * 3
return px[o], px[o + 1], px[o + 2]
def is_blue(x, y):
r, g, b = rgb(x, y)
return b >= 200 and r <= 90 and g <= 90
def is_red(x, y):
r, g, b = rgb(x, y)
return r >= 200 and g <= 90 and b <= 90
def blue_near(x, y, rad=8):
for dy in range(-rad, rad + 1):
for dx in range(-rad, rad + 1):
if dx * dx + dy * dy > rad * rad:
continue
xx, yy = x + dx, y + dy
if 0 <= xx < w and 0 <= yy < h and is_blue(xx, yy):
return True
return False
fails = []
# 1. Red marker clusters: one per point, centred on the projection.
red = [(x, y) for y in range(h) for x in range(w) if is_red(x, y)]
parent = {}
def find(a):
while parent[a] != a:
parent[a] = parent[parent[a]]
a = parent[a]
return a
cells = {}
for p in red:
parent[p] = p
cells.setdefault((p[0] // 4, p[1] // 4), []).append(p)
for (x, y) in red:
for cx in (x // 4 - 1, x // 4, x // 4 + 1):
for cy in (y // 4 - 1, y // 4, y // 4 + 1):
for q in cells.get((cx, cy), []):
if q != (x, y) and abs(q[0] - x) <= 2 and abs(q[1] - y) <= 2:
ra, rb = find((x, y)), find(q)
if ra != rb:
parent[ra] = rb
groups = {}
for p in red:
groups.setdefault(find(p), []).append(p)
clusters = [(sum(p[0] for p in ps) / len(ps),
sum(p[1] for p in ps) / len(ps), len(ps))
for ps in groups.values() if len(ps) >= 20]
print("trip: %dx%d zoom=%d markers=%d (sizes %s)"
% (w, h, zoom, len(clusters), sorted(c[2] for c in clusters)))
if len(clusters) != len(pts):
fails.append("marker clusters %d != points %d"
% (len(clusters), len(pts)))
else:
unmatched = list(clusters)
for i, (cx, cy) in enumerate(zip(mx, my)):
best = min(unmatched,
key=lambda c: (c[0] - cx) ** 2 + (c[1] - cy) ** 2)
d = math.hypot(best[0] - cx, best[1] - cy)
if d > 4:
fails.append("marker %d off projection by %.1fpx"
% (i, d))
unmatched.remove(best)
# Label plaque rects (for skipping line samples hidden under them).
plaques = []
for i, r in enumerate(ordered):
if r["time"]:
plaques.append(label_rect(mx[i], my[i], label_text(r["time"]),
w, h))
def in_plaque(x, y):
for (lx, ly, pw, ph) in plaques:
if lx - 2 <= x <= lx + pw + 2 and ly - 2 <= y <= ly + ph + 2:
return True
return False
# 2. Ordered legs: blue off the midpoint, and blue at the midpoint.
for i in range(1, len(ordered)):
x0, y0, x1, y1 = mx[i - 1], my[i - 1], mx[i], my[i]
seg_len = math.hypot(x1 - x0, y1 - y0)
off_mid = False
tried = 0
for t in (0.25, 0.4, 0.6, 0.75):
sx, sy = int(round(x0 + t * (x1 - x0))), int(round(y0 + t * (y1 - y0)))
if math.hypot(sx - x0, sy - y0) < 12:
continue
if math.hypot(sx - x1, sy - y1) < 12:
continue
if in_plaque(sx, sy):
continue
tried += 1
if blue_near(sx, sy):
off_mid = True
break
mid = blue_near((x0 + x1) // 2, (y0 + y1) // 2)
print("leg %d->%d len=%.0fpx off-mid=%s (tried %d) mid=%s"
% (i - 1, i, seg_len, off_mid, tried, mid))
if not off_mid:
fails.append("leg %d->%d: no blue off the midpoint" % (i - 1, i))
if not mid:
fails.append("leg %d->%d: no blue at the midpoint" % (i - 1, i))
# 3. Wrong-order hops (file order) must have NO blue at midpoint.
file_order = sorted(rows, key=lambda r: r["order"])
file_xy = []
for r in file_order:
j = ordered.index(r)
file_xy.append((mx[j], my[j]))
legs = [(mx[i - 1], my[i - 1], mx[i], my[i])
for i in range(1, len(ordered))]
for k in range(min(2, len(file_xy) - 1)):
wx = (file_xy[k][0] + file_xy[k + 1][0]) // 2
wy = (file_xy[k][1] + file_xy[k + 1][1]) // 2
mind = min(dist_pt_seg(wx, wy, *leg) for leg in legs)
print("wrong hop %d midpoint (%d,%d) min-dist-to-real-leg %.1fpx"
% (k, wx, wy, mind))
if mind <= 25:
fails.append("wrong-hop probe %d inconclusive (%.1fpx from a "
"real leg)" % (k, mind))
elif blue_near(wx, wy):
fails.append("wrong hop %d: blue line where file order would "
"connect" % k)
# 4. Time labels: plaque + text by timestamped markers, none by the
# untimestamped one.
for i, r in enumerate(ordered):
lx, ly, pw, ph = label_rect(mx[i], my[i],
label_text(r["time"]) if r["time"]
else "MM-DD HH:MM", w, h)
white = dark = 0
for y in range(max(0, ly), min(h, ly + ph)):
for x in range(max(0, lx), min(w, lx + pw)):
rr, gg, bb = rgb(x, y)
if rr > 245 and gg > 245 and bb > 245:
white += 1
elif rr < 100 and gg < 100 and bb < 100:
dark += 1
if r["time"]:
print("label %s: white=%d dark=%d" % (r["file"], white, dark))
if white < 100 or dark < 5:
fails.append("label %s: plaque/text missing (white=%d "
"dark=%d)" % (r["file"], white, dark))
else:
print("no-label %s: white=%d dark=%d" % (r["file"], white, dark))
if white >= 20:
fails.append("untimestamped %s has a label plaque "
"(white=%d)" % (r["file"], white))
if fails:
print("check_trip: FAIL")
for f in fails:
print(" - " + f)
return 1
print("check_trip: PASS")
return 0
if __name__ == "__main__":
sys.exit(main())