maps project: design, survey, mock app, and route-aware planning backend

- DESIGN.md: full design incl. driving-trip requirements (R1-R4),
  stays model, focus mode, mobile, provenance rules
- SURVEY.md: open-source landscape
- mock/: interaction mock (Florence itinerary, focus mode, stays,
  region stops, mobile layout)
- router/: Go module (stdlib-only) with Router interface
  (Valhalla + OSRM backends), stop_cost, optimize_stops, corridor,
  routectl CLI, bench (5 real NE-corridor tasks, 26 checks passing),
  integration tests, and setup-osrm.sh for the self-hosted router
- osm/: NH+MA+CT+NY PBFs (gitignored) + setup artifacts
This commit is contained in:
gmp
2026-09-06 00:05:17 -04:00
commit efde2cc71b
24 changed files with 4921 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
// Package geo holds the small, dependency-free geodesy used by the
// router/plan layers. Kept tiny on purpose: anything heavier belongs
// in the router backend, not here.
package geo
import "math"
// Point is a lat/lon in degrees.
type Point struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
const R = 6371000.0 // meters
func rad(d float64) float64 { return d * math.Pi / 180 }
// Meters is great-circle distance in meters.
func Meters(a, b Point) float64 {
dLat := rad(b.Lat - a.Lat)
dLon := rad(b.Lon - a.Lon)
q := math.Sin(dLat/2)*math.Sin(dLat/2) +
math.Cos(rad(a.Lat))*math.Cos(rad(b.Lat))*math.Sin(dLon/2)*math.Sin(dLon/2)
return 2 * R * math.Asin(math.Sqrt(q))
}
// MinAt walking minutes at the given km/h, rounded up to whole minutes.
func MinAt(meters float64, kmh float64) int {
if meters <= 0 {
return 0
}
return int(math.Ceil(meters / 1000.0 / (kmh / 60.0)))
}
// distToSeg is the planar (equirect, local) distance from p to segment ab, in meters.
// Accurate to <0.1% over the extents we use (tens of km).
func distToSeg(p, a, b Point) float64 {
x := func(q Point) [2]float64 {
lat0 := rad(a.Lat)
return [2]float64{rad(q.Lon) * math.Cos(lat0) * R, rad(q.Lat) * R}
}
px, ax, bx := x(p), x(a), x(b)
dx, dy := bx[0]-ax[0], bx[1]-ax[1]
l2 := dx*dx + dy*dy
t := 0.0
if l2 > 0 {
t = ((px[0]-ax[0])*dx + (px[1]-ax[1])*dy) / l2
if t < 0 {
t = 0
} else if t > 1 {
t = 1
}
}
cx, cy := ax[0]+t*dx, ax[1]+t*dy
return math.Hypot(px[0]-cx, px[1]-cy)
}
// DistToPolylineMeters is the minimum distance from p to any segment of the polyline.
func DistToPolylineMeters(p Point, poly []Point) float64 {
best := float64(1e18)
for i := 0; i+1 < len(poly); i++ {
if d := distToSeg(p, poly[i], poly[i+1]); d < best {
best = d
}
}
if len(poly) == 1 {
best = Meters(p, poly[0])
}
return best
}
+34
View File
@@ -0,0 +1,34 @@
package geo
import "testing"
func TestMeters(t *testing.T) {
// NYC → Boston ≈ 305 km
d := Meters(Point{Lat: 40.7128, Lon: -74.006}, Point{Lat: 42.3601, Lon: -71.0589})
if d < 300_000 || d > 320_000 {
t.Errorf("NYC-Boston = %.0f m, want ~305km", d)
}
}
func TestDistToPolyline(t *testing.T) {
poly := []Point{{Lat: 0, Lon: 0}, {Lat: 10, Lon: 0}} // north-south at lon 0
// 1 deg lon at equator ≈ 111.3 km
d := DistToPolylineMeters(Point{Lat: 5, Lon: 1}, poly)
if d < 110_000 || d > 115_000 {
t.Errorf("distance = %.0f m, want ~111km", d)
}
// on the line
if d := DistToPolylineMeters(Point{Lat: 5, Lon: 0}, poly); d > 100 {
t.Errorf("on-line distance = %.0f m, want ~0", d)
}
// past the end: distance to endpoint
if d := DistToPolylineMeters(Point{Lat: 12, Lon: 0}, poly); d < 200_000 || d > 240_000 {
t.Errorf("past-end distance = %.0f m, want ~222km", d)
}
}
func TestMinAt(t *testing.T) {
if m := MinAt(4600, 4.6); m != 60 {
t.Errorf("MinAt(4600m, 4.6kmh) = %d, want 60", m)
}
}
+69
View File
@@ -0,0 +1,69 @@
package plan
import (
"maps/router/internal/geo"
"maps/router/internal/route"
)
// Corridor is the spatial constraint for "along the route" search
// (DESIGN.md R2). It is a buffer band around the routed polyline.
//
// Quality depends on the router: local OSRM returns full geometry
// (exact corridor); hosted Valhalla does not, so we fall back to a
// band around the great-circle chord (coarse, flagged).
type Corridor struct {
Polyline []geo.Point // may be nil → chord fallback
Origin geo.Point
Dest geo.Point
BufferM float64 // band half-width
FromRoute *route.Route
}
// NewCorridor wraps a computed route. BufferM is the corridor half-width.
func NewCorridor(r *route.Route, bufferM float64) *Corridor {
c := &Corridor{
Polyline: r.Geometry,
BufferM: bufferM,
FromRoute: r,
}
if len(r.Legs) > 0 {
// endpoints aren't in the Route struct; caller sets them
}
return c
}
// SetEndpoints records A and C (needed for the chord fallback).
func (c *Corridor) SetEndpoints(a, dst geo.Point) {
c.Origin = a
c.Dest = dst
}
// Exact reports whether the corridor is built on the true route
// geometry (vs the chord fallback).
func (c *Corridor) Exact() bool { return len(c.Polyline) >= 2 }
// Contains reports whether p lies within the corridor band.
func (c *Corridor) Contains(p geo.Point) bool {
if c.Exact() {
return geo.DistToPolylineMeters(p, c.Polyline) <= c.BufferM
}
// Chord fallback: distance to the A→C great-circle chord.
return geo.DistToPolylineMeters(p, []geo.Point{c.Origin, c.Dest}) <= c.BufferM
}
// ChordSample returns a sampled chord polyline (for map drawing when
// the router gave no geometry).
func (c *Corridor) ChordSample(n int) []geo.Point {
if c.Exact() {
return c.Polyline
}
poly := make([]geo.Point, 0, n+1)
for i := 0; i <= n; i++ {
t := float64(i) / float64(n)
poly = append(poly, geo.Point{
Lat: c.Origin.Lat + t*(c.Dest.Lat-c.Origin.Lat),
Lon: c.Origin.Lon + t*(c.Dest.Lon-c.Origin.Lon),
})
}
return poly
}
+57
View File
@@ -0,0 +1,57 @@
package plan
import (
"testing"
"maps/router/internal/geo"
"maps/router/internal/route"
)
func TestCorridorExact(t *testing.T) {
// route along a vertical line at lon=0, lat 0..10, buffer 100 km
r := &route.Route{Geometry: []geo.Point{
{Lat: 0, Lon: 0},
{Lat: 5, Lon: 0},
{Lat: 10, Lon: 0},
}}
c := NewCorridor(r, 100_000)
if !c.Exact() {
t.Fatal("expected exact corridor")
}
// 50 km off the line: ~0.45 deg lon at equator
if !c.Contains(geo.Point{Lat: 5, Lon: 0.45}) {
t.Error("point 50km off line should be inside 100km buffer")
}
// 150 km off: ~1.35 deg
if c.Contains(geo.Point{Lat: 5, Lon: 1.35}) {
t.Error("point 150km off line should be outside 100km buffer")
}
// 200 km north of the end
if c.Contains(geo.Point{Lat: 12, Lon: 0}) {
t.Error("point 200km past endpoint should be outside")
}
}
func TestCorridorChordFallback(t *testing.T) {
r := &route.Route{} // no geometry
c := NewCorridor(r, 200_000)
c.SetEndpoints(geo.Point{Lat: 44, Lon: -71.65}, geo.Point{Lat: 40.7, Lon: -73.97})
if c.Exact() {
t.Fatal("expected chord fallback")
}
// midpoint of the chord is inside
mid := geo.Point{Lat: 42.35, Lon: -72.81}
if !c.Contains(mid) {
t.Error("chord midpoint should be inside band")
}
// Boston (42.36,-71.06) is ~150km east of the chord midpoint...
// distance from Boston to the chord: chord at lat 42.36 → t≈0.498, lon ≈ -72.81
// Boston lon -71.06 → Δlon 1.75 deg ≈ 148 km at cos(42.36) → inside 200km?
// Let's just assert a clearly-far point is outside: NYC (40.7,-74.0) is the endpoint.
far := geo.Point{Lat: 44.0, Lon: -70.0} // 150km NE of origin
if c.Contains(far) {
// distance to chord endpoint is sqrt? origin is (44,-71.65): Δlon 1.65 deg ≈ 132km,
// distance to segment ~132km < 200km → inside. This is expected behavior.
t.Log("far point inside chord band (expected: chord band is coarse)")
}
}
+110
View File
@@ -0,0 +1,110 @@
//go:build integration
// Integration tests hit a live router (hosted Valhalla by default, or a
// local OSRM via ROUTER_URL for the osrm backend). They verify the
// client plumbing and the stop_cost end-to-end on the real road network.
//
// Run: go test -tags integration ./...
package plan
import (
"context"
"os"
"testing"
"time"
"maps/router/internal/geo"
"maps/router/internal/route"
)
func liveRouter(t *testing.T) route.Router {
backend := os.Getenv("ROUTER_BACKEND")
switch backend {
case "osrm":
return route.NewOSRM(os.Getenv("ROUTER_URL"))
default:
return route.NewValhalla("https://valhalla1.openstreetmap.de")
}
}
var (
lincoln = geo.Point{Lat: 44.054, Lon: -71.650}
queens = geo.Point{Lat: 40.729, Lon: -73.966}
)
func TestLiveDirectRoute(t *testing.T) {
t.Parallel()
r := liveRouter(t)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
rt, err := r.Route(ctx, route.ProfileDrive, []geo.Point{lincoln, queens})
if err != nil {
t.Fatalf("route: %v", err)
}
// Lincoln NH -> Queens NY is a 5.25-5.75h drive (I-93/90/495/290).
// Anything outside this band means the backend or the dataset is wrong.
mins := rt.Duration / 60
if mins < 300 || mins > 400 {
t.Errorf("direct time = %.0f min, expected in [300, 400]", mins)
}
if rt.Distance < 480_000 || rt.Distance > 600_000 {
t.Errorf("distance = %.0f m, expected in [480km, 600km]", rt.Distance)
}
t.Logf("%s: %d min, %.0f km", r.Name(), int(mins), rt.Distance/1000)
}
// TestLiveRouteAvoidsBoston is the regression test for the user's
// "the router, not the model, knows the route" finding: the fastest
// Lincoln->Queens drive goes via I-90/I-495/I-290 (Worcester corridor),
// NOT through Boston.
func TestLiveRouteAvoidsBoston(t *testing.T) {
t.Parallel()
r := liveRouter(t)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
rt, err := r.Route(ctx, route.ProfileDrive, []geo.Point{lincoln, queens})
if err != nil {
t.Fatalf("route: %v", err)
}
boston := geo.Point{Lat: 42.36, Lon: -71.06}
var dist float64
if len(rt.Geometry) >= 2 {
dist = geo.DistToPolylineMeters(boston, rt.Geometry)
} else if !rt.BBox.Empty() {
dist = rt.BBox.DistMeters(boston)
t.Logf("using bbox distance (no geometry from backend)")
} else {
t.Skip("no geometry or bbox available")
}
if dist < 15_000 {
t.Errorf("route comes within %.1f km of Boston; expected the I-495/I-290 corridor (>= 15 km)", dist/1000)
}
t.Logf("Boston clearance: %.1f km", dist/1000)
}
// TestLiveStopCost exercises the full stop_cost pipeline on the real
// network: Cascade Falls (Worcester) sits on the I-495 corridor and
// must have a small detour; Mount Major (Alton NH) is far off it.
func TestLiveStopCost(t *testing.T) {
t.Parallel()
r := liveRouter(t)
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
defer cancel()
cascade := geo.Point{Lat: 42.2767, Lon: -71.806}
mtmajor := geo.Point{Lat: 43.642, Lon: -71.156}
pts := []geo.Point{cascade, mtmajor, lincoln, queens}
m, err := route.BuildMatrix(ctx, r, route.ProfileDrive, pts, 200*time.Millisecond)
if err != nil {
t.Fatalf("matrix: %v", err)
}
cascadeCost := StopCost(m, 0, Stop{ID: "cascade", DwellMin: 60})
majorCost := StopCost(m, 1, Stop{ID: "mtmajor", DwellMin: 120})
t.Logf("cascade detour = %d min; mtmajor detour = %d min", cascadeCost.DetourMin, majorCost.DetourMin)
if cascadeCost.DetourMin > 20 {
t.Errorf("Cascade Falls (on I-495 corridor) detour = %d min, want <= 20", cascadeCost.DetourMin)
}
if majorCost.DetourMin < 40 {
t.Errorf("Mount Major (off corridor) detour = %d min, want >= 40", majorCost.DetourMin)
}
}
+189
View File
@@ -0,0 +1,189 @@
package plan
import "maps/router/internal/route"
// OptimizeResult is the best order of k stops.
type OptimizeResult struct {
Order []int // indices into the stops slice
DetourMin int
TotalMin int
Exhaustive bool // true when the optimum came from full search
Feasible bool // true when TotalMin <= budgetMin (when a budget was given)
Relaxed bool // true when we fell back to fewer than k stops
}
// OptimizeStops picks the best ordered subset of k stops minimizing
// SeqCost, subject to TotalMin <= budgetMin when budgetMin > 0.
// m must be the (n+2)-layout matrix for stops.
//
// Selection semantics (k is the user's request, "give me 2 hikes"):
// 1. best feasible exactly-k
// 2. else best feasible with fewer stops (Relaxed)
// 3. else best exactly-k ignoring the budget (Feasible=false)
//
// n <= 10: full enumeration (this is also the ground truth for evals).
// n > 10: greedy best-insertion (exact for k=1).
func OptimizeStops(m route.Matrix, stops []Stop, k, budgetMin int) OptimizeResult {
n := len(stops)
if k < 0 || k > n {
k = n
}
if k == 0 {
return OptimizeResult{Feasible: true, Exhaustive: true}
}
if n <= 10 {
return optimizeExhaustive(m, stops, k, budgetMin)
}
return optimizeGreedy(m, stops, k, budgetMin)
}
type cand struct {
order []int
total int
detour int
}
func feas(c cand, budgetMin int) bool { return budgetMin <= 0 || c.total <= budgetMin }
func lowerCost(a, b cand) bool {
if a.total != b.total {
return a.total < b.total
}
return a.detour < b.detour
}
func pickBest(cands []cand, budgetMin, wantSize int) (cand, bool) {
var best cand
found := false
for _, c := range cands {
if wantSize >= 0 && len(c.order) != wantSize {
continue
}
if !feas(c, budgetMin) {
continue
}
if !found || lowerCost(c, best) {
best, found = c, true
}
}
return best, found
}
func optimizeExhaustive(m route.Matrix, stops []Stop, k, budgetMin int) OptimizeResult {
n := len(stops)
// Enumerate ALL permutations of every subset of size k.
var all []cand
var rec func(order []int, used []bool)
rec = func(order []int, used []bool) {
if len(order) == k {
detour, total := SeqCost(m, order, stops)
if total >= 0 {
all = append(all, cand{order: append([]int(nil), order...), total: total, detour: detour})
}
return
}
for i := 0; i < n; i++ {
if !used[i] {
used[i] = true
rec(append(order, i), used)
used[i] = false
}
}
}
rec(nil, make([]bool, n))
// 1. feasible exactly-k
if c, ok := pickBest(all, budgetMin, k); ok {
return OptimizeResult{Order: c.order, DetourMin: c.detour, TotalMin: c.total, Exhaustive: true, Feasible: true}
}
// 2. feasible with fewer: re-enumerate smaller sizes
if budgetMin > 0 {
var less []cand
var rec2 func(start, size int, order []int, used []bool)
rec2 = func(start, size int, order []int, used []bool) {
if len(order) == size {
detour, total := SeqCost(m, order, stops)
if total >= 0 && feas(cand{total: total}, budgetMin) {
less = append(less, cand{order: append([]int(nil), order...), total: total, detour: detour})
}
return
}
for i := start; i < n; i++ {
if !used[i] {
used[i] = true
rec2(i+1, size, append(order, i), used)
used[i] = false
}
}
}
for size := 1; size < k; size++ {
rec2(0, size, nil, make([]bool, n))
}
// best among feasible smaller (larger size preferred on tie? no — just lowest total)
if c, ok := pickBest(less, budgetMin, -1); ok {
return OptimizeResult{Order: c.order, DetourMin: c.detour, TotalMin: c.total, Exhaustive: true, Feasible: true, Relaxed: true}
}
}
// 3. best exactly-k ignoring budget
var bestK cand
found := false
for _, c := range all {
if !found || lowerCost(c, bestK) {
bestK, found = c, true
}
}
if !found {
return OptimizeResult{DetourMin: -1, TotalMin: -1, Exhaustive: true}
}
return OptimizeResult{Order: bestK.order, DetourMin: bestK.detour, TotalMin: bestK.total, Exhaustive: true, Feasible: budgetMin <= 0}
}
func optimizeGreedy(m route.Matrix, stops []Stop, k, budgetMin int) OptimizeResult {
n := len(stops)
order := []int{}
used := make([]bool, n)
for len(order) < k {
_, curTotal := SeqCost(m, order, stops)
if curTotal < 0 {
break
}
bestTotal := int(^uint(0) >> 1)
bestStop, bestPos := -1, -1
for s := 0; s < n; s++ {
if used[s] {
continue
}
for pos := 0; pos <= len(order); pos++ {
tri := make([]int, 0, len(order)+1)
tri = append(tri, order[:pos]...)
tri = append(tri, s)
tri = append(tri, order[pos:]...)
_, total := SeqCost(m, tri, stops)
if total < 0 {
continue
}
if budgetMin > 0 && total > budgetMin {
continue
}
if total < bestTotal {
bestTotal = total
bestStop, bestPos = s, pos
}
}
}
if bestStop < 0 {
break
}
used[bestStop] = true
order = append(order[:bestPos], append([]int{bestStop}, order[bestPos:]...)...)
}
detour, total := SeqCost(m, order, stops)
res := OptimizeResult{Order: order, DetourMin: detour, TotalMin: total, Exhaustive: false}
if len(order) < k {
res.Relaxed = true
}
if total >= 0 {
res.Feasible = budgetMin <= 0 || total <= budgetMin
}
return res
}
+145
View File
@@ -0,0 +1,145 @@
package plan
import (
"testing"
"maps/router/internal/route"
)
// synthMatrix builds a (n+2)-layout matrix from a full (n+2)² symmetric
// matrix in seconds.
func synthMatrix(vals [][]float64) route.Matrix {
m := make(route.Matrix, len(vals))
for i := range m {
m[i] = append([]float64(nil), vals[i]...)
}
return m
}
// 3 stops, A=3, C=4.
// Travel times (seconds):
//
// A→C direct: 3600 (60 min)
// A→S0 600, S0→C 3600 → detour 600 (10 min)
// A→S1 1200, S1→C 3600 → detour 1200 (20 min)
// A→S2 1800, S2→C 3600 → detour 1800 (30 min)
// S0→S1 600, S1→S2 600, S0→S2 1200
func testMatrix() route.Matrix {
return synthMatrix([][]float64{
{0, 600, 1200, 600, 3600}, // S0
{600, 0, 600, 1200, 3600}, // S1
{1200, 600, 0, 1800, 3600}, // S2
{600, 1200, 1800, 0, 3600}, // A
{3600, 3600, 3600, 3600, 0}, // C
})
}
var testStops = []Stop{
{ID: "s0", Name: "S0", DwellMin: 30},
{ID: "s1", Name: "S1", DwellMin: 30},
{ID: "s2", Name: "S2", DwellMin: 30},
}
func TestStopCost(t *testing.T) {
m := testMatrix()
c := StopCost(m, 0, testStops[0])
if c.DetourMin != 10 {
t.Errorf("S0 detour = %d, want 10", c.DetourMin)
}
if c.DirectMin != 60 {
t.Errorf("direct = %d, want 60", c.DirectMin)
}
if c.TotalMin != 10+30+10 {
t.Errorf("total = %d, want 50", c.TotalMin)
}
c2 := StopCost(m, 2, testStops[2])
if c2.DetourMin != 30 {
t.Errorf("S2 detour = %d, want 30", c2.DetourMin)
}
}
func TestSeqCostOrderMatters(t *testing.T) {
m := testMatrix()
// A→S0→S1→C: 600+600+3600 = 4800 vs 3600 → detour 1200 s = 20 min
d, total := SeqCost(m, []int{0, 1}, testStops)
if d != 20 {
t.Errorf("detour = %d, want 20", d)
}
if total != 20+30+10+30+10 {
t.Errorf("total = %d, want 100", total)
}
}
func TestOptimizeExhaustivePicksmm(t *testing.T) {
m := testMatrix()
// k=1: best single stop is S0 (detour 10 + dwell 30 + ovh 10 = 50)
r := OptimizeStops(m, testStops, 1, 0)
if len(r.Order) != 1 || r.Order[0] != 0 {
t.Fatalf("k=1 order = %v, want [0]", r.Order)
}
if r.TotalMin != 50 {
t.Errorf("k=1 total = %d, want 50", r.TotalMin)
}
// k=2: best pair: [0,1]: detour 20, total 20+80 = 100
// [0,2]: A→S0(600)+S0→S2(1200)+S2→C(3600)=5400 → detour 30 min, total 30+80=110
// [1,2]: 1200+600+3600=5400 → detour 30, total 110
r2 := OptimizeStops(m, testStops, 2, 0)
if len(r2.Order) != 2 || r2.Order[0] != 0 || r2.Order[1] != 1 {
t.Fatalf("k=2 order = %v, want [0 1]", r2.Order)
}
if r2.TotalMin != 100 {
t.Errorf("k=2 total = %d, want 100", r2.TotalMin)
}
}
func TestOptimizeBudgetFeasibilityFirst(t *testing.T) {
m := testMatrix()
// budget 55 min: k=1 → S0 (50) feasible; k=2 → [0,1] (100) infeasible,
// so best feasible is k=1 S0 (50).
r := OptimizeStops(m, testStops, 2, 55)
if len(r.Order) != 1 || r.Order[0] != 0 {
t.Fatalf("budget 55: order = %v, want [0]", r.Order)
}
if r.TotalMin != 50 {
t.Errorf("total = %d, want 50", r.TotalMin)
}
}
// TestOptimizeGreedyMatchesExhaustive checks the greedy fallback
// (n > 10) against the exhaustive optimum on a small-ish case forced
// through both code paths.
func TestOptimizeGreedyMatchesExhaustive(t *testing.T) {
// 12 stops on a line: A→C 60 min, stops evenly placed, dwell 20 each.
n := 12
vals := make([][]float64, n+2)
// place on a line: position 0..13; A at 0, C at 13, stops at 1..12.
pos := make([]float64, n+2)
for i := 0; i < n; i++ {
pos[i] = float64(i + 1)
}
pos[n] = 0
pos[n+1] = 13
for i := 0; i < n+2; i++ {
vals[i] = make([]float64, n+2)
for j := 0; j < n+2; j++ {
d := pos[i] - pos[j]
if d < 0 {
d = -d
}
vals[i][j] = d * 600 // 10 min per unit
}
}
m := synthMatrix(vals)
stops := make([]Stop, n)
for i := range stops {
stops[i] = Stop{ID: string(rune('a' + i)), DwellMin: 20}
}
k := 3
exp := optimizeExhaustive(m, stops, k, 0)
// force greedy by calling with n > exhaustiveMax
got := optimizeGreedy(m, stops, k, 0)
if exp.TotalMin != got.TotalMin {
t.Errorf("greedy total %d != exhaustive total %d (order %v vs %v)",
got.TotalMin, exp.TotalMin, got.Order, exp.Order)
}
}
+110
View File
@@ -0,0 +1,110 @@
// Package plan implements the route-aware planning primitives from
// DESIGN.md "Driving trips": stop_cost, optimize_stops, and the
// corridor. All numbers here are router arithmetic (computed
// provenance) — the LLM is never allowed to substitute estimates.
//
// Matrix convention used throughout: for n stops the matrix has n+2
// rows/cols: indices 0..n-1 are the stops (in slice order), index n is
// the origin A, index n+1 is the destination C.
package plan
import (
"maps/router/internal/geo"
"maps/router/internal/route"
)
// Stop is a candidate stop with a location and a dwell budget.
type Stop struct {
ID string
Name string
At geo.Point
DwellMin int // expected time spent at the stop (user-set or sourced)
OverheadMin int // park/walk-to-entrance/leave; WithDefaults fills 10
}
// WithDefaults applies the DESIGN.md default overhead (10 min) when unset.
func (s Stop) WithDefaults() Stop {
if s.OverheadMin == 0 {
s.OverheadMin = 10
}
return s
}
// Cost is the stop_cost result: pure router arithmetic.
//
// detour = route(A,C via B) − route(A,C)
// total = detour + dwell + overhead
//
// A stop is "free" along the corridor iff detour ≈ 0.
type Cost struct {
Stop Stop
DetourMin int // extra travel time vs direct A→C, minutes
DwellMin int
OverheadMin int
TotalMin int // DetourMin + DwellMin + OverheadMin
DirectMin int // direct A→C duration in minutes (context)
}
// StopCost computes the cost of inserting one stop between A and C.
// m is the (n+2)-layout matrix; i is the stop's index.
func StopCost(m route.Matrix, i int, s Stop) Cost {
s = s.WithDefaults()
n := len(m) - 2
aIdx, cIdx := n, n+1
direct := m[aIdx][cIdx]
via := m[aIdx][i] + m[i][cIdx]
detour := 0.0
if direct > 0 && via > 0 {
detour = via - direct
if detour < 0 && detour > -30 { // router noise, seconds
detour = 0
}
}
dm := int(0.5 + detour/60)
if dm < 0 {
dm = 0
}
return Cost{
Stop: s,
DetourMin: dm,
DwellMin: s.DwellMin,
OverheadMin: s.OverheadMin,
TotalMin: dm + s.DwellMin + s.OverheadMin,
DirectMin: int(0.5 + direct/60),
}
}
// SeqCost computes (detourMin, totalMin) for an ordered subset of stops
// between A and C. Returns (-1, -1) when any leg is unroutable.
func SeqCost(m route.Matrix, order []int, stops []Stop) (detourMin, totalMin int) {
n := len(m) - 2
aIdx, cIdx := n, n+1
direct := m[aIdx][cIdx]
if direct < 0 {
return -1, -1
}
via := 0.0
prev := aIdx
for _, si := range order {
d := m[prev][si]
if d < 0 {
return -1, -1
}
via += d
prev = si
}
if d := m[prev][cIdx]; d < 0 {
return -1, -1
}
via += m[prev][cIdx]
detour := int(0.5 + (via-direct)/60)
if detour < 0 {
detour = 0
}
total := detour
for _, si := range order {
s := stops[si].WithDefaults()
total += s.DwellMin + s.OverheadMin
}
return detour, total
}
+136
View File
@@ -0,0 +1,136 @@
package route
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"maps/router/internal/geo"
)
// OSRM is a client for a local OSRM backend (osrm-routed), e.g.
// http://localhost:5000. Returns full route geometry.
type OSRM struct {
BaseURL string
HTTP *http.Client
profile string
name string
}
func NewOSRM(baseURL string) *OSRM {
return &OSRM{
BaseURL: baseURL,
HTTP: &http.Client{Timeout: 60 * time.Second},
profile: "driving",
name: "osrm(" + baseURL + ")",
}
}
func (o *OSRM) Name() string { return o.name }
func (o *OSRM) osrmProfile(p Profile) string {
if p == ProfileWalk {
return "walking"
}
return "driving"
}
type osrmRoute struct {
Code string `json:"code"`
Distance float64 `json:"distance"`
Duration float64 `json:"duration"`
Legs []struct {
Distance float64 `json:"distance"`
Duration float64 `json:"duration"`
} `json:"legs"`
Geometry string `json:"geometry"`
}
func (o *OSRM) Route(ctx context.Context, profile Profile, pts []geo.Point) (*Route, error) {
if len(pts) < 2 {
return nil, fmt.Errorf("osrm: need >= 2 points, got %d", len(pts))
}
var coords []string
for _, p := range pts {
coords = append(coords, fmt.Sprintf("%.6f,%.6f", p.Lon, p.Lat))
}
u := fmt.Sprintf("%s/route/v1/%s/%s?overview=false&alternatives=false&geometries=geojson",
o.BaseURL, o.osrmProfile(profile), strings.Join(coords, ";"))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
}
resp, err := o.HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var or osrmRoute
if err := json.NewDecoder(resp.Body).Decode(&or); err != nil {
return nil, fmt.Errorf("osrm: bad response: %w", err)
}
if or.Code != "Ok" {
return nil, fmt.Errorf("osrm: %s", or.Code)
}
out := &Route{Duration: or.Duration, Distance: or.Distance}
for _, l := range or.Legs {
out.Legs = append(out.Legs, Leg{Duration: l.Duration, Distance: l.Distance})
}
// OSRM geometries=geojson returns a GeoJSON LineString.
var gj struct {
Geometry struct {
Coords [][]float64 `json:"coordinates"`
} `json:"geometry"`
}
if or.Geometry != "" && json.Unmarshal([]byte(or.Geometry), &gj) == nil {
for _, c := range gj.Geometry.Coords {
out.Geometry = append(out.Geometry, geo.Point{Lat: c[1], Lon: c[0]})
}
}
return out, nil
}
// OSRMTable builds a matrix via the OSRM table service (one call) when
// available; the generic BuildMatrix (pairwise) works on any backend.
func (o *OSRM) Table(ctx context.Context, profile Profile, pts []geo.Point) (Matrix, error) {
var coords []string
for _, p := range pts {
coords = append(coords, fmt.Sprintf("%.6f,%.6f", p.Lon, p.Lat))
}
u := fmt.Sprintf("%s/table/v1/%s/%s?annotations=duration",
o.BaseURL, o.osrmProfile(profile), strings.Join(coords, ";"))
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
resp, err := o.HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var tr struct {
Code string `json:"code"`
Durations [][]float64 `json:"durations"`
}
if err := json.NewDecoder(resp.Body).Decode(&tr); err != nil {
return nil, err
}
if tr.Code != "Ok" {
return nil, fmt.Errorf("osrm table: %s", tr.Code)
}
m := make(Matrix, len(pts))
for i := range m {
m[i] = make([]float64, len(pts))
for j := range m[i] {
if tr.Durations[i][j] > 0 {
m[i][j] = tr.Durations[i][j]
} else {
m[i][j] = -1
}
}
}
return m, nil
}
var _ = url.Values{} // keep net/url import for future query building
+126
View File
@@ -0,0 +1,126 @@
// Package route defines the Router interface and the two backends:
// a hosted Valhalla (works today, no geometry) and local OSRM
// (full geometry, self-hosted — see scripts/setup-osrm.sh).
//
// Design rule (DESIGN.md R1/R4): the route is computed, never narrated.
// Every Duration/Distance value returned here is `computed` provenance.
package route
import (
"context"
"math"
"time"
"maps/router/internal/geo"
)
// Profile is the routing profile.
type Profile string
const (
ProfileDrive Profile = "drive"
ProfileWalk Profile = "walk"
)
// Route is the result of routing through an ordered set of points.
type Route struct {
// Duration is total travel time in seconds (computed by the router).
Duration float64
// Distance is total path length in meters.
Distance float64
// BBox is the bounding box of the routed path (from the router's
// summary). Zero values if the backend doesn't provide one.
BBox BBox
// Geometry is the routed polyline. May be nil for backends that
// don't return it (hosted Valhalla) — callers must degrade
// gracefully (chord corridor, flagged low-confidence).
Geometry []geo.Point
// Legs holds per-segment durations for multi-point routes.
// len(Legs) == len(points)-1 when present.
Legs []Leg
}
// Leg is one segment between consecutive waypoints.
type Leg struct {
Duration float64 // seconds
Distance float64 // meters
}
// BBox is a latitude/longitude bounding box in degrees.
type BBox struct {
MinLat, MaxLat, MinLon, MaxLon float64
}
// Empty reports whether the box is unset.
func (b BBox) Empty() bool { return b == BBox{} }
// DistMeters is the minimum distance from p to the box (0 if inside).
func (b BBox) DistMeters(p geo.Point) float64 {
dLat, dLon := 0.0, 0.0
if p.Lat < b.MinLat {
dLat = b.MinLat - p.Lat
} else if p.Lat > b.MaxLat {
dLat = p.Lat - b.MaxLat
}
if p.Lon < b.MinLon {
dLon = b.MinLon - p.Lon
} else if p.Lon > b.MaxLon {
dLon = p.Lon - b.MaxLon
}
if dLat == 0 && dLon == 0 {
return 0
}
mLat := dLat * 111190.0
mLon := dLon * 111190.0 * math.Cos(rad(p.Lat))
return math.Hypot(mLat, mLon)
}
func rad(d float64) float64 { return d * math.Pi / 180 }
// Router is the backend interface.
type Router interface {
// Route routes through pts in order and returns the combined trip.
Route(ctx context.Context, profile Profile, pts []geo.Point) (*Route, error)
// Name identifies the backend in reports ("valhalla-hosted", "osrm-local").
Name() string
}
// Matrix builds a full origin-destination matrix over pts using the
// router. m[i][j] is seconds; -1 means unroutable. Built with pairwise
// two-point Route calls — the single code path that works on both
// backends (Valhalla's sources_to_targets is capped at 150 km).
type Matrix [][]float64
func (m Matrix) From(i, j int) float64 { return m[i][j] }
// BuildMatrix computes the matrix with a small politeness delay between
// calls when polite > 0 (hosted endpoints).
func BuildMatrix(ctx context.Context, r Router, profile Profile, pts []geo.Point, polite time.Duration) (Matrix, error) {
n := len(pts)
m := make(Matrix, n)
for i := range m {
m[i] = make([]float64, n)
m[i][i] = 0
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i == j {
continue
}
if polite > 0 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(polite):
}
}
rr, err := r.Route(ctx, profile, []geo.Point{pts[i], pts[j]})
if err != nil {
m[i][j] = -1
continue
}
m[i][j] = rr.Duration
}
}
return m, nil
}
+183
View File
@@ -0,0 +1,183 @@
package route
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"maps/router/internal/geo"
)
// Valhalla is a client for a Valhalla routing API
// (e.g. the hosted https://valhalla1.openstreetmap.de or a self-hosted
// valhalla instance). Note: hosted instances strip route geometry, so
// Route.Geometry will be nil.
type Valhalla struct {
BaseURL string
HTTP *http.Client
name string
}
func NewValhalla(baseURL string) *Valhalla {
return &Valhalla{
BaseURL: baseURL,
HTTP: &http.Client{Timeout: 60 * time.Second},
name: "valhalla(" + baseURL + ")",
}
}
func (v *Valhalla) Name() string { return v.name }
func (v *Valhalla) costing(p Profile) string {
if p == ProfileWalk {
return "pedestrian"
}
return "auto"
}
type vLocation struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
type vRouteReq struct {
Locations []vLocation `json:"locations"`
Costing string `json:"costing"`
Polyline bool `json:"polyline"`
}
type vLeg struct {
Summary struct {
Time float64 `json:"time"`
Length float64 `json:"length"` // km
} `json:"summary"`
}
type vTrip struct {
Summary struct {
Time float64 `json:"time"`
Length float64 `json:"length"` // km
MinLat float64 `json:"min_lat"`
MaxLat float64 `json:"max_lat"`
MinLon float64 `json:"min_lon"`
MaxLon float64 `json:"max_lon"`
} `json:"summary"`
Legs []vLeg `json:"legs"`
}
type vResp struct {
Trip vTrip `json:"trip"`
Message string `json:"message"`
Error string `json:"error"`
}
func (v *Valhalla) Route(ctx context.Context, profile Profile, pts []geo.Point) (*Route, error) {
if len(pts) < 2 {
return nil, fmt.Errorf("route: need >= 2 points, got %d", len(pts))
}
req := vRouteReq{Costing: v.costing(profile), Polyline: true}
for _, p := range pts {
req.Locations = append(req.Locations, vLocation{p.Lat, p.Lon})
}
body, _ := json.Marshal(req)
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, v.BaseURL+"/route", bytes.NewReader(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := v.HTTP.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 20<<20))
if err != nil {
return nil, err
}
var vr vResp
if err := json.Unmarshal(raw, &vr); err != nil {
return nil, fmt.Errorf("valhalla: bad response (%s): %q", resp.Status, string(raw[:min(len(raw), 200)]))
}
if vr.Message != "" {
return nil, fmt.Errorf("valhalla: %s", vr.Message)
}
if vr.Error != "" {
return nil, fmt.Errorf("valhalla: %s", vr.Error)
}
out := &Route{
Duration: vr.Trip.Summary.Time,
Distance: vr.Trip.Summary.Length * 1000,
BBox: BBox{
MinLat: vr.Trip.Summary.MinLat, MaxLat: vr.Trip.Summary.MaxLat,
MinLon: vr.Trip.Summary.MinLon, MaxLon: vr.Trip.Summary.MaxLon,
},
}
for _, l := range vr.Trip.Legs {
out.Legs = append(out.Legs, Leg{Duration: l.Summary.Time, Distance: l.Summary.Length * 1000})
}
// Geometry: decode encoded polyline if the instance returns it.
if pl, ok := decodePolylineField(raw); ok {
out.Geometry = pl
}
return out, nil
}
// decodePolylineField checks for trip.polyline (encoded polyline v0) —
// hosted instances omit it; self-hosted valhalla with "polyline":true
// returns it.
func decodePolylineField(raw []byte) ([]geo.Point, bool) {
var probe struct {
Trip struct {
Polyline string `json:"polyline"`
} `json:"trip"`
}
if err := json.Unmarshal(raw, &probe); err != nil || probe.Trip.Polyline == "" {
return nil, false
}
return decodePolyline(probe.Trip.Polyline), true
}
// decodePolyline decodes a Google encoded polyline (precision 1e-5 or 1e-6).
func decodePolyline(s string) []geo.Point {
var pts []geo.Point
lat, lon := 0, 0
i := 0
for i < len(s) {
var dlat, dlon int
shift := 0
for {
b := int(s[i]) - 63
i++
dlat |= (b & 0x1f) << shift
if b&0x20 == 0 {
break
}
shift += 5
}
shift = 0
for {
b := int(s[i]) - 63
i++
dlon |= (b & 0x1f) << shift
if b&0x20 == 0 {
break
}
shift += 5
}
lat += dlat&1 ^ dlat>>1
lon += dlon&1 ^ dlon>>1
pts = append(pts, geo.Point{Lat: float64(lat) / 1e5, Lon: float64(lon) / 1e5})
}
return pts
}
func min(a, b int) int {
if a < b {
return a
}
return b
}