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:
@@ -0,0 +1,114 @@
|
||||
# maps/router — route-aware planning primitives
|
||||
|
||||
The Go backend for the "search along the route" capability
|
||||
([DESIGN.md](../DESIGN.md), "Driving trips" section). Everything the LLM
|
||||
would otherwise *guess* about a trip — route shape, travel times, detour
|
||||
costs — is computed here and returned with provenance.
|
||||
|
||||
## What's in here
|
||||
|
||||
```
|
||||
internal/geo/ dependency-free geodesy (haversine, point-to-line)
|
||||
internal/route/ Router interface + backends
|
||||
- valhalla.go: hosted/self-hosted Valhalla (works today;
|
||||
no geometry on the hosted instance → chord fallback)
|
||||
- osrm.go: local OSRM (full geometry; scripts/setup-osrm.sh)
|
||||
internal/plan/ the primitives:
|
||||
- stopcost.go: stop_cost = route(A,C via B) − route(A,C)
|
||||
- optimize.go: optimize_stops (exhaustive ≤10 stops, greedy above)
|
||||
- corridor.go: corridor = buffer band around the route
|
||||
cmd/routectl/ manual CLI: route | stopcost | optimize
|
||||
cmd/bench/ benchmark runner (bench/tasks.json)
|
||||
bench/tasks.json 5 real NE-corridor tasks with recorded goldens
|
||||
scripts/setup-osrm.sh self-host OSRM over the NH+MA+CT+NY extract
|
||||
```
|
||||
|
||||
Zero third-party Go dependencies (stdlib only).
|
||||
|
||||
## Try it (hosted Valhalla, no setup)
|
||||
|
||||
```sh
|
||||
go run ./cmd/routectl route --from 44.054,-71.650 --to 40.729,-73.966
|
||||
# Lincoln NH → Queens NY: ~5h32m, 531 km, I-93/90/495/290 (NOT via Boston)
|
||||
|
||||
go run ./cmd/routectl stopcost --from 44.054,-71.650 --to 40.729,-73.966 \
|
||||
--stop 42.2767,-71.806:60:cascade \
|
||||
--stop 43.507,-71.548:50:ladd \
|
||||
--stop 43.642,-71.156:120:mtmajor
|
||||
# cascade detour= 6 min (on the I-495 corridor)
|
||||
# ladd detour=17 min
|
||||
# mtmajor detour=80 min (off-corridor)
|
||||
|
||||
go run ./cmd/routectl optimize --from 44.054,-71.650 --to 40.729,-73.966 --k 2 \
|
||||
--stop 42.2767,-71.806:60:cascade --stop 43.507,-71.548:50:ladd \
|
||||
--stop 43.902,-71.64:60:plymouth --stop 42.425,-71.68:60:brewsters
|
||||
# order: ladd -> cascade detour: 23 min
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
go test ./... # unit tests, offline, fast
|
||||
go test -tags integration ./... # live router (Valhalla by default)
|
||||
ROUTER_BACKEND=osrm ROUTER_URL=http://localhost:5000 \
|
||||
go test -tags integration ./... # against local OSRM
|
||||
```
|
||||
|
||||
The integration tests encode the key regression: the fastest
|
||||
Lincoln→Queens drive stays ≥15 km from Boston (it goes via Worcester,
|
||||
I-90/I-495/I-290). That is exactly the fact an LLM confidently gets wrong.
|
||||
|
||||
## Benchmark
|
||||
|
||||
```sh
|
||||
go run ./cmd/bench # run all tasks, assert goldens + corridor checks
|
||||
go run ./cmd/bench --record # re-record goldens (after a backend/extract change)
|
||||
```
|
||||
|
||||
Tasks are real OD pairs across NH/MA/CT/NY with real POI candidates and
|
||||
dwell times. Check types:
|
||||
|
||||
| type | meaning |
|
||||
|---|---|
|
||||
| `golden_route_min` | direct route time within a recorded band (±10%) |
|
||||
| `route_avoids` | route stays ≥ N km from a point (geometry, or bbox when the backend has none) |
|
||||
| `stop_free` / `stop_detour_at_least` / `stop_detour_band` | computed detour of a candidate vs an expected band |
|
||||
| `optimize_order` | the exhaustive optimum matches the recorded order |
|
||||
| `crosscheck` | single multi-waypoint route ≈ matrix-summed prediction (≤ maxPct drift) |
|
||||
|
||||
Current state: **26 PASS / 0 FAIL** against hosted Valhalla.
|
||||
|
||||
## Self-hosted OSRM (full geometry, exact corridors)
|
||||
|
||||
`scripts/setup-osrm.sh` builds OSRM 26.4.1 from source (Boost header-only),
|
||||
extracts the 4-state PBFs (pre-downloaded in `../osm/`), partitions,
|
||||
customizes, and serves on `:5000`. Then:
|
||||
|
||||
```sh
|
||||
go run ./cmd/routectl route --backend osrm --from 44.054,-71.650 --to 40.729,-73.966
|
||||
```
|
||||
|
||||
With OSRM, `Route.Geometry` is populated, so the corridor is exact
|
||||
(distances to the actual routed polyline) instead of the chord fallback
|
||||
used with the hosted Valhalla. This is what makes
|
||||
`search_along_route`'s spatial pre-filter (PostGIS `ST_DWithin` on the
|
||||
corridor polygon in the v1 design) sound.
|
||||
|
||||
## Design notes
|
||||
|
||||
- **The route is computed, never narrated.** No function in this module
|
||||
returns a time estimate from model knowledge; every number is router
|
||||
output (`computed` provenance per DESIGN.md R4).
|
||||
- **Matrix via pairwise route calls.** Valhalla's
|
||||
`sources_to_targets` caps at 150 km, so the common path is
|
||||
`BuildMatrix` (pairwise `/route`). OSRM's `Table` service is available
|
||||
for the local backend when a single-call matrix matters.
|
||||
- **optimize_stops semantics**: the user asked for *k* stops ("two
|
||||
hikes"), so the objective minimizes total = detour + dwell + overhead
|
||||
over ordered subsets of **exactly k**, with fallback (a) to the best
|
||||
feasible smaller set when a time budget is given, then (b) to the best
|
||||
exactly-k ignoring the budget, flagged `Feasible=false`.
|
||||
"At most k" without a budget degenerates (zero stops always wins).
|
||||
- **Stop coordinates are POI centroids.** The router snaps to the
|
||||
network; a 200 m centroid error moves a 531 km route's detour by
|
||||
seconds, not minutes.
|
||||
@@ -0,0 +1,385 @@
|
||||
// bench runs the corridor stop-optimization benchmark (bench/tasks.json)
|
||||
// against a router backend. It is the acceptance test for the
|
||||
// "search along the route" primitives: route, stop_cost, optimize_stops.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// bench [--tasks bench/tasks.json] [--record]
|
||||
//
|
||||
// --record writes observed golden values (direct route minutes and
|
||||
// optimized orders) back into the tasks file for regression use.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"maps/router/internal/geo"
|
||||
"maps/router/internal/plan"
|
||||
"maps/router/internal/route"
|
||||
)
|
||||
|
||||
type Place struct {
|
||||
Name string `json:"name"`
|
||||
Lat float64 `json:"lat"`
|
||||
Lon float64 `json:"lon"`
|
||||
}
|
||||
|
||||
func (p Place) Point() geo.Point { return geo.Point{Lat: p.Lat, Lon: p.Lon} }
|
||||
|
||||
type Candidate struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Lat float64 `json:"lat"`
|
||||
Lon float64 `json:"lon"`
|
||||
DwellMin int `json:"dwellMin"`
|
||||
}
|
||||
|
||||
type Check struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Lat, Lon float64 `json:",omitempty"`
|
||||
MinDistKm float64 `json:"minDistKm,omitempty"`
|
||||
Candidate string `json:"candidate,omitempty"`
|
||||
MaxDetourMin int `json:"maxDetourMin,omitempty"`
|
||||
MinDetourMin int `json:"minDetourMin,omitempty"`
|
||||
MaxPct float64 `json:"maxPct,omitempty"`
|
||||
GoldMin float64 `json:"goldMin,omitempty"`
|
||||
GoldMax float64 `json:"goldMax,omitempty"`
|
||||
Want []string `json:"want,omitempty"`
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
ID string `json:"id"`
|
||||
Desc string `json:"desc"`
|
||||
Origin Place `json:"origin"`
|
||||
Dest Place `json:"dest"`
|
||||
K int `json:"k"`
|
||||
BudgetMin int `json:"budgetMin"`
|
||||
Candidates []Candidate `json:"candidates"`
|
||||
Checks []Check `json:"checks"`
|
||||
}
|
||||
|
||||
type BenchFile struct {
|
||||
Backend string `json:"backend"`
|
||||
ValhallaURL string `json:"valhalla_url"`
|
||||
Tasks []Task `json:"tasks"`
|
||||
}
|
||||
|
||||
type result struct {
|
||||
check string
|
||||
status string // PASS FAIL RECORD
|
||||
detail string
|
||||
}
|
||||
|
||||
func main() {
|
||||
tasksPath := flag.String("tasks", "bench/tasks.json", "path to tasks.json")
|
||||
record := flag.Bool("record", false, "record golden values into the tasks file")
|
||||
flag.Parse()
|
||||
|
||||
raw, err := os.ReadFile(*tasksPath)
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
var bf BenchFile
|
||||
if err := json.Unmarshal(raw, &bf); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
var r route.Router
|
||||
switch bf.Backend {
|
||||
case "valhalla":
|
||||
r = route.NewValhalla(bf.ValhallaURL)
|
||||
case "osrm":
|
||||
r = route.NewOSRM("http://localhost:5000")
|
||||
default:
|
||||
fatal(fmt.Errorf("unknown backend %q", bf.Backend))
|
||||
}
|
||||
ctx := context.Background()
|
||||
delay := 150 * time.Millisecond
|
||||
if _, ok := r.(*route.OSRM); ok {
|
||||
delay = 0
|
||||
}
|
||||
|
||||
failures := 0
|
||||
for ti := range bf.Tasks {
|
||||
t := &bf.Tasks[ti]
|
||||
fmt.Printf("=== %s: %s -> %s (k=%d)\n", t.ID, t.Origin.Name, t.Dest.Name, t.K)
|
||||
fmt.Printf(" %s\n", t.Desc)
|
||||
|
||||
// Direct route (golden + corridor source).
|
||||
direct, err := r.Route(ctx, route.ProfileDrive, []geo.Point{t.Origin.Point(), t.Dest.Point()})
|
||||
if err != nil {
|
||||
fatal(fmt.Errorf("task %s: direct route: %w", t.ID, err))
|
||||
}
|
||||
fmt.Printf(" direct: %s (%.1f km)\n", fmtDur(direct.Duration), direct.Distance/1000)
|
||||
|
||||
// Matrix over [candidates..., origin, dest].
|
||||
pts := make([]geo.Point, 0, len(t.Candidates)+2)
|
||||
for _, c := range t.Candidates {
|
||||
pts = append(pts, geo.Point{Lat: c.Lat, Lon: c.Lon})
|
||||
}
|
||||
pts = append(pts, t.Origin.Point(), t.Dest.Point())
|
||||
fmt.Printf(" building %dx%d matrix (%d calls)...\n", len(pts), len(pts), len(pts)*(len(pts)-1))
|
||||
t0 := time.Now()
|
||||
m, err := route.BuildMatrix(ctx, r, route.ProfileDrive, pts, delay)
|
||||
if err != nil {
|
||||
fatal(fmt.Errorf("task %s: matrix: %w", t.ID, err))
|
||||
}
|
||||
fmt.Printf(" matrix done in %s\n", time.Since(t0).Round(time.Second))
|
||||
|
||||
stops := make([]plan.Stop, len(t.Candidates))
|
||||
for i, c := range t.Candidates {
|
||||
stops[i] = plan.Stop{ID: c.ID, Name: c.Name, At: geo.Point{Lat: c.Lat, Lon: c.Lon}, DwellMin: c.DwellMin}
|
||||
}
|
||||
|
||||
candByID := map[string]plan.Stop{}
|
||||
for _, s := range stops {
|
||||
candByID[s.ID] = s
|
||||
}
|
||||
|
||||
opt := plan.OptimizeStops(m, stops, t.K, t.BudgetMin)
|
||||
optNames := make([]string, len(opt.Order))
|
||||
for i, si := range opt.Order {
|
||||
optNames[i] = stops[si].ID
|
||||
}
|
||||
fmt.Printf(" optimized: %s (detour %d min, total %d min, exhaustive=%v)\n",
|
||||
strings.Join(optNames, " -> "), opt.DetourMin, opt.TotalMin, opt.Exhaustive)
|
||||
|
||||
for ci := range t.Checks {
|
||||
ck := &t.Checks[ci]
|
||||
res := runCheck(ctx, r, t, m, stops, direct, opt, *ck)
|
||||
if res.status == "FAIL" {
|
||||
failures++
|
||||
}
|
||||
fmt.Printf(" [%s] %-22s %s\n", res.status, ck.ID, res.detail)
|
||||
if *record {
|
||||
applyRecord(ck, direct, optNames)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if *record {
|
||||
out, _ := json.MarshalIndent(bf, "", " ")
|
||||
if err := os.WriteFile(*tasksPath, out, 0o644); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
fmt.Printf("\nrecorded goldens into %s\n", *tasksPath)
|
||||
}
|
||||
fmt.Printf("\n%s (%d failures)\n", outcome(failures), failures)
|
||||
if failures > 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func runCheck(ctx context.Context, r route.Router, t *Task, m route.Matrix, stops []plan.Stop,
|
||||
direct *route.Route, opt plan.OptimizeResult, ck Check) result {
|
||||
res := result{check: ck.ID}
|
||||
switch ck.Type {
|
||||
case "golden_route_min":
|
||||
mins := direct.Duration / 60
|
||||
if ck.GoldMin == 0 && ck.GoldMax == 0 {
|
||||
res.status = "RECORD"
|
||||
res.detail = fmt.Sprintf("direct = %.0f min (no golden yet, run --record)", mins)
|
||||
return res
|
||||
}
|
||||
lo, hi := ck.GoldMin, ck.GoldMax
|
||||
if lo == 0 {
|
||||
lo = mins - math.Inf(1)
|
||||
}
|
||||
if hi == 0 {
|
||||
hi = math.Inf(1)
|
||||
}
|
||||
if mins < lo || mins > hi {
|
||||
res.status = "FAIL"
|
||||
res.detail = fmt.Sprintf("direct = %.0f min, golden [%v, %v]", mins, lo, hi)
|
||||
} else {
|
||||
res.status = "PASS"
|
||||
res.detail = fmt.Sprintf("direct = %.0f min in [%v, %v]", mins, lo, hi)
|
||||
}
|
||||
|
||||
case "route_avoids":
|
||||
p := geo.Point{Lat: ck.Lat, Lon: ck.Lon}
|
||||
dist := distFromRoute(direct, p)
|
||||
if dist < ck.MinDistKm*1000 {
|
||||
res.status = "FAIL"
|
||||
res.detail = fmt.Sprintf("%s: route comes within %.1f km (< %.0f km)", ck.Name, dist/1000, ck.MinDistKm)
|
||||
} else {
|
||||
res.status = "PASS"
|
||||
res.detail = fmt.Sprintf("%s: route stays %.0f km away (min %.0f)", ck.Name, dist/1000, ck.MinDistKm)
|
||||
}
|
||||
|
||||
case "stop_free":
|
||||
c, ok := stopIdx(stops, ck.Candidate)
|
||||
if !ok {
|
||||
res.status, res.detail = "FAIL", "unknown candidate"
|
||||
return res
|
||||
}
|
||||
cost := plan.StopCost(m, c, stops[c])
|
||||
if cost.DetourMin > ck.MaxDetourMin {
|
||||
res.status = "FAIL"
|
||||
res.detail = fmt.Sprintf("detour = %d min > %d min cap", cost.DetourMin, ck.MaxDetourMin)
|
||||
} else {
|
||||
res.status = "PASS"
|
||||
res.detail = fmt.Sprintf("detour = %d min <= %d min", cost.DetourMin, ck.MaxDetourMin)
|
||||
}
|
||||
|
||||
case "stop_detour_at_least":
|
||||
c, ok := stopIdx(stops, ck.Candidate)
|
||||
if !ok {
|
||||
res.status, res.detail = "FAIL", "unknown candidate"
|
||||
return res
|
||||
}
|
||||
cost := plan.StopCost(m, c, stops[c])
|
||||
if cost.DetourMin < ck.MinDetourMin {
|
||||
res.status = "FAIL"
|
||||
res.detail = fmt.Sprintf("detour = %d min < %d min floor", cost.DetourMin, ck.MinDetourMin)
|
||||
} else {
|
||||
res.status = "PASS"
|
||||
res.detail = fmt.Sprintf("detour = %d min >= %d min", cost.DetourMin, ck.MinDetourMin)
|
||||
}
|
||||
|
||||
case "stop_detour_band":
|
||||
// The computed detour must fall in [min, max] — a regression
|
||||
// guard on corridor shape (router/extract changes would show here).
|
||||
c, ok := stopIdx(stops, ck.Candidate)
|
||||
if !ok {
|
||||
res.status, res.detail = "FAIL", "unknown candidate"
|
||||
return res
|
||||
}
|
||||
cost := plan.StopCost(m, c, stops[c])
|
||||
if cost.DetourMin < ck.MinDetourMin || cost.DetourMin > ck.MaxDetourMin {
|
||||
res.status = "FAIL"
|
||||
res.detail = fmt.Sprintf("detour = %d min outside [%d, %d]", cost.DetourMin, ck.MinDetourMin, ck.MaxDetourMin)
|
||||
} else {
|
||||
res.status = "PASS"
|
||||
res.detail = fmt.Sprintf("detour = %d min in [%d, %d]", cost.DetourMin, ck.MinDetourMin, ck.MaxDetourMin)
|
||||
}
|
||||
|
||||
case "optimize_order":
|
||||
got := make([]string, len(opt.Order))
|
||||
for i, si := range opt.Order {
|
||||
got[i] = stops[si].ID
|
||||
}
|
||||
if ck.Want == nil {
|
||||
res.status = "RECORD"
|
||||
res.detail = fmt.Sprintf("order = %s (no golden yet)", strings.Join(got, " -> "))
|
||||
return res
|
||||
}
|
||||
if !sameSeq(got, ck.Want) {
|
||||
res.status = "FAIL"
|
||||
res.detail = fmt.Sprintf("got %s, want %s", strings.Join(got, " -> "), strings.Join(ck.Want, " -> "))
|
||||
} else {
|
||||
res.status = "PASS"
|
||||
res.detail = fmt.Sprintf("order = %s", strings.Join(got, " -> "))
|
||||
}
|
||||
|
||||
case "crosscheck":
|
||||
// Re-route in the optimized order as a single call; compare
|
||||
// travel time against the matrix-summed prediction.
|
||||
if len(opt.Order) == 0 {
|
||||
res.status, res.detail = "PASS", "no stops, nothing to cross-check"
|
||||
return res
|
||||
}
|
||||
pts := []geo.Point{t.Origin.Point()}
|
||||
for _, si := range opt.Order {
|
||||
pts = append(pts, stops[si].At)
|
||||
}
|
||||
pts = append(pts, t.Dest.Point())
|
||||
rr, err := r.Route(ctx, route.ProfileDrive, pts)
|
||||
if err != nil {
|
||||
res.status, res.detail = "FAIL", "cross-check route: "+err.Error()
|
||||
return res
|
||||
}
|
||||
// matrix-predicted travel time (no dwell): sum legs
|
||||
n := len(stops)
|
||||
via := 0.0
|
||||
prev := n // origin index in matrix
|
||||
for _, si := range opt.Order {
|
||||
via += m[prev][si]
|
||||
prev = si
|
||||
}
|
||||
via += m[prev][n+1]
|
||||
diffPct := math.Abs(via-rr.Duration) / rr.Duration * 100
|
||||
if diffPct > ck.MaxPct {
|
||||
res.status = "FAIL"
|
||||
res.detail = fmt.Sprintf("matrix %.0f s vs route %.0f s (%.1f%% drift > %.0f%%)", via, rr.Duration, diffPct, ck.MaxPct)
|
||||
} else {
|
||||
res.status = "PASS"
|
||||
res.detail = fmt.Sprintf("matrix %.0f s vs route %.0f s (%.1f%% drift)", via, rr.Duration, diffPct)
|
||||
}
|
||||
|
||||
default:
|
||||
res.status, res.detail = "FAIL", "unknown check type "+ck.Type
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// applyRecord fills in goldens.
|
||||
func applyRecord(ck *Check, direct *route.Route, optNames []string) {
|
||||
mins := direct.Duration / 60
|
||||
switch ck.Type {
|
||||
case "golden_route_min":
|
||||
// +/- 10% tolerance band around the observed value.
|
||||
ck.GoldMin = math.Floor(mins*0.9/5) * 5
|
||||
ck.GoldMax = math.Ceil(mins*1.1/5) * 5
|
||||
case "optimize_order":
|
||||
ck.Want = append([]string(nil), optNames...)
|
||||
}
|
||||
}
|
||||
|
||||
// distFromRoute returns the min distance from p to the route: geometry
|
||||
// if available, else bbox (conservative: inside bbox => 0).
|
||||
func distFromRoute(r *route.Route, p geo.Point) float64 {
|
||||
if len(r.Geometry) >= 2 {
|
||||
return geo.DistToPolylineMeters(p, r.Geometry)
|
||||
}
|
||||
if !r.BBox.Empty() {
|
||||
return r.BBox.DistMeters(p)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func stopIdx(stops []plan.Stop, id string) (int, bool) {
|
||||
for i, s := range stops {
|
||||
if s.ID == id {
|
||||
return i, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func sameSeq(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func fmtDur(sec float64) string {
|
||||
m := int(0.5 + sec/60)
|
||||
return fmt.Sprintf("%dh%02dm", m/60, m%60)
|
||||
}
|
||||
|
||||
func outcome(failures int) string {
|
||||
if failures == 0 {
|
||||
return "BENCH PASS"
|
||||
}
|
||||
return "BENCH FAIL"
|
||||
}
|
||||
|
||||
func fatal(err error) {
|
||||
fmt.Fprintln(os.Stderr, "bench error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// routectl is the manual/CI front end for the router + plan primitives.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// routectl route --backend valhalla --from 44.054,-71.650 --to 40.729,-73.966
|
||||
// routectl stopcost --backend valhalla --from A --to C --stop 42.277,-71.806:60:CascadeFalls
|
||||
// routectl optimize --backend valhalla --from A --to C --k 2 \
|
||||
// --stop 42.277,-71.806:60:CascadeFalls --stop 43.507,-71.548:50:Ladd
|
||||
//
|
||||
// stop format: lat,lon[:dwellMin[:name]]
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"maps/router/internal/geo"
|
||||
"maps/router/internal/plan"
|
||||
"maps/router/internal/route"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
usage()
|
||||
}
|
||||
var err error
|
||||
switch os.Args[1] {
|
||||
case "route":
|
||||
err = cmdRoute(os.Args[2:])
|
||||
case "stopcost":
|
||||
err = cmdStopCost(os.Args[2:])
|
||||
case "optimize":
|
||||
err = cmdOptimize(os.Args[2:])
|
||||
default:
|
||||
usage()
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "error:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Fprintln(os.Stderr, "usage: routectl {route|stopcost|optimize} [flags]")
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
type common struct {
|
||||
backend string
|
||||
from, to string
|
||||
}
|
||||
|
||||
func (c *common) parse(fs *flag.FlagSet) {
|
||||
fs.StringVar(&c.backend, "backend", "valhalla", "valhalla|osrm")
|
||||
fs.StringVar(&c.from, "from", "", "lat,lon origin")
|
||||
fs.StringVar(&c.to, "to", "", "lat,lon destination")
|
||||
}
|
||||
|
||||
func (c *common) router() route.Router {
|
||||
switch c.backend {
|
||||
case "valhalla":
|
||||
return route.NewValhalla("https://valhalla1.openstreetmap.de")
|
||||
case "osrm":
|
||||
return route.NewOSRM("http://localhost:5000")
|
||||
default:
|
||||
panic("bad backend " + c.backend)
|
||||
}
|
||||
}
|
||||
|
||||
func parsePt(s string) (lat, lon float64) {
|
||||
parts := strings.Split(s, ",")
|
||||
lat, _ = strconv.ParseFloat(strings.TrimSpace(parts[0]), 64)
|
||||
lon, _ = strconv.ParseFloat(strings.TrimSpace(parts[1]), 64)
|
||||
return
|
||||
}
|
||||
|
||||
func point(s string) geo.Point {
|
||||
lat, lon := parsePt(s)
|
||||
return geo.Point{Lat: lat, Lon: lon}
|
||||
}
|
||||
|
||||
func parseStops(args []string) []plan.Stop {
|
||||
var stops []plan.Stop
|
||||
for _, a := range args {
|
||||
parts := strings.Split(a, ":")
|
||||
lat, lon := parsePt(parts[0])
|
||||
s := plan.Stop{At: geo.Point{Lat: lat, Lon: lon}, ID: parts[0]}
|
||||
if len(parts) > 1 && parts[1] != "" {
|
||||
s.DwellMin, _ = strconv.Atoi(parts[1])
|
||||
}
|
||||
if len(parts) > 2 && parts[2] != "" {
|
||||
s.Name = parts[2]
|
||||
s.ID = parts[2]
|
||||
}
|
||||
stops = append(stops, s)
|
||||
}
|
||||
return stops
|
||||
}
|
||||
|
||||
func fmtDur(sec float64) string {
|
||||
m := int(0.5 + sec/60)
|
||||
return fmt.Sprintf("%dh%02dm", m/60, m%60)
|
||||
}
|
||||
|
||||
// ---- commands -------------------------------------------------------
|
||||
|
||||
func cmdRoute(args []string) error {
|
||||
fs := flag.NewFlagSet("route", flag.ExitOnError)
|
||||
var c common
|
||||
c.parse(fs)
|
||||
var walk bool
|
||||
fs.BoolVar(&walk, "walk", false, "walking profile")
|
||||
fs.Parse(args)
|
||||
if c.from == "" || c.to == "" {
|
||||
return fmt.Errorf("--from and --to required")
|
||||
}
|
||||
r, err := c.router().Route(context.Background(), prof(walk), []geo.Point{point(c.from), point(c.to)})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("backend: %s\n", c.router().Name())
|
||||
fmt.Printf("time: %s (%.0f s)\n", fmtDur(r.Duration), r.Duration)
|
||||
fmt.Printf("distance: %.1f km\n", r.Distance/1000)
|
||||
if len(r.Geometry) > 0 {
|
||||
fmt.Printf("geometry: %d points (exact corridor available)\n", len(r.Geometry))
|
||||
} else {
|
||||
fmt.Printf("geometry: none (chord-corridor fallback, low confidence)\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cmdStopCost(args []string) error {
|
||||
fs := flag.NewFlagSet("stopcost", flag.ExitOnError)
|
||||
var c common
|
||||
c.parse(fs)
|
||||
var stopArgs []string
|
||||
fs.Func("stop", "stop lat,lon[:dwellMin[:name]]", func(v string) error {
|
||||
stopArgs = append(stopArgs, v)
|
||||
return nil
|
||||
})
|
||||
fs.Parse(args)
|
||||
if c.from == "" || c.to == "" || len(stopArgs) == 0 {
|
||||
return fmt.Errorf("--from, --to, and --stop required")
|
||||
}
|
||||
stops := parseStops(stopArgs)
|
||||
m, err := buildMatrix(c.router(), c.from, c.to, stops)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i, s := range stops {
|
||||
cost := plan.StopCost(m, i, s)
|
||||
fmt.Printf("%-18s detour=%3d min dwell=%3d min overhead=%2d min total=%3d min (direct %d min)\n",
|
||||
s.ID, cost.DetourMin, cost.DwellMin, cost.OverheadMin, cost.TotalMin, cost.DirectMin)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cmdOptimize(args []string) error {
|
||||
fs := flag.NewFlagSet("optimize", flag.ExitOnError)
|
||||
var c common
|
||||
c.parse(fs)
|
||||
var stopArgs []string
|
||||
var k, budget int
|
||||
fs.Func("stop", "stop lat,lon[:dwellMin[:name]]", func(v string) error {
|
||||
stopArgs = append(stopArgs, v)
|
||||
return nil
|
||||
})
|
||||
fs.IntVar(&k, "k", 2, "number of stops")
|
||||
fs.IntVar(&budget, "budget", 0, "max total minutes (0 = none)")
|
||||
fs.Parse(args)
|
||||
if c.from == "" || c.to == "" || len(stopArgs) == 0 {
|
||||
return fmt.Errorf("--from, --to, and --stop required")
|
||||
}
|
||||
stops := parseStops(stopArgs)
|
||||
m, err := buildMatrix(c.router(), c.from, c.to, stops)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res := plan.OptimizeStops(m, stops, k, budget)
|
||||
names := make([]string, len(res.Order))
|
||||
for i, si := range res.Order {
|
||||
names[i] = stops[si].ID
|
||||
}
|
||||
fmt.Printf("order: %s\n", strings.Join(names, " -> "))
|
||||
fmt.Printf("detour: %d min\n", res.DetourMin)
|
||||
fmt.Printf("total: %d min (budget %d, feasible=%v, relaxed=%v, exhaustive=%v)\n",
|
||||
res.TotalMin, budget, res.Feasible, res.Relaxed, res.Exhaustive)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- helpers --------------------------------------------------------
|
||||
|
||||
func prof(walk bool) route.Profile {
|
||||
if walk {
|
||||
return route.ProfileWalk
|
||||
}
|
||||
return route.ProfileDrive
|
||||
}
|
||||
|
||||
// buildMatrix builds the (n+2)-layout matrix: stops, then A, then C.
|
||||
func buildMatrix(r route.Router, fromS, toS string, stops []plan.Stop) (route.Matrix, error) {
|
||||
pts := make([]geo.Point, 0, len(stops)+2)
|
||||
for _, s := range stops {
|
||||
pts = append(pts, s.At)
|
||||
}
|
||||
pts = append(pts, point(fromS), point(toS))
|
||||
// Politeness delay for hosted backends.
|
||||
delay := 150 * time.Millisecond
|
||||
if _, ok := r.(*route.OSRM); ok {
|
||||
delay = 0
|
||||
}
|
||||
return route.BuildMatrix(context.Background(), r, route.ProfileDrive, pts, delay)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module maps/router
|
||||
|
||||
go 1.27
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# Self-host the OSRM router over the NH+MA+CT+NY extract.
|
||||
# Prereqs: cmake, g++, make, >=12GB RAM for extract, >=10GB disk.
|
||||
#
|
||||
# The PBFs are pre-downloaded in ../osm/ (us-new-hampshire, us-connecticut,
|
||||
# us-massachusetts, us-new-york .osm.pbf, from the geofabrik mirror on
|
||||
# HuggingFace: NoeFlandre/osm-geofabrik-raw-pbf-extracts).
|
||||
#
|
||||
# Artifacts go to ../osm/build/. Router ends up on http://localhost:5000.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
OSM_DIR="$(pwd)/osm"
|
||||
BUILD_DIR="$OSM_DIR/build"
|
||||
DATA_DIR="$BUILD_DIR/data"
|
||||
OSRM_BIN="$BUILD_DIR/osrm-backend-26.4.1/build"
|
||||
mkdir -p "$DATA_DIR"
|
||||
|
||||
step() { echo; echo "=== $1"; }
|
||||
|
||||
step "1/5 OSRM binaries"
|
||||
if [ ! -x "$OSRM_BIN/osrm-extract" ]; then
|
||||
if [ ! -d "$BUILD_DIR/osrm-backend-26.4.1" ]; then
|
||||
curl -sL -o "$BUILD_DIR/osrm.tar.gz" https://github.com/Project-OSRM/osrm-backend/archive/refs/tags/v26.4.1.tar.gz
|
||||
tar -C "$BUILD_DIR" -xzf "$BUILD_DIR/osrm.tar.gz"
|
||||
fi
|
||||
# Boost is header-usage only for OSRM; point BOOST_ROOT at a source tree.
|
||||
if [ ! -d "$BUILD_DIR/boost_1_84_0" ]; then
|
||||
curl -sL -o "$BUILD_DIR/boost.tgz" https://archives.boost.io/release/1.84.0/source/boost_1_84_0.tar.gz
|
||||
tar -C "$BUILD_DIR" -xzf "$BUILD_DIR/boost.tgz"
|
||||
fi
|
||||
cmake -S "$BUILD_DIR/osrm-backend-26.4.1" -B "$OSRM_BIN" \
|
||||
-DCMAKE_BUILD_TYPE=Release -DWITH_TESTS=OFF -DWITH_EXAMPLES=OFF \
|
||||
-DBOOST_ROOT="$BUILD_DIR/boost_1_84_0"
|
||||
cmake --build "$OSRM_BIN" -j"$(nproc)"
|
||||
fi
|
||||
ls -la "$OSRM_BIN"/osrm-extract "$OSRM_BIN"/osrm-routed
|
||||
|
||||
step "2/5 OSM PBFs"
|
||||
for f in us-new-hampshire us-connecticut us-massachusetts us-new-york; do
|
||||
if [ ! -s "$OSM_DIR/$f.osm.pbf" ]; then
|
||||
curl -sL -o "$OSM_DIR/$f.osm.pbf" \
|
||||
"https://huggingface.co/datasets/NoeFlandre/osm-geofabrik-raw-pbf-extracts/resolve/main/$f-latest.osm.pbf"
|
||||
fi
|
||||
done
|
||||
ls -la "$OSM_DIR"/us-*.osm.pbf
|
||||
|
||||
step "3/5 extract (needs ~12GB RAM; this is the slow part)"
|
||||
touch "$DATA_DIR/timestamp"
|
||||
if [ ! -s "$DATA_DIR/northeast.osrm" ] || [ ! -s "$DATA_DIR/northeast.osrm.tile" ]; then
|
||||
"$OSRM_BIN/osrm-extract" \
|
||||
"$OSM_DIR/us-new-hampshire.osm.pbf" \
|
||||
"$OSM_DIR/us-connecticut.osm.pbf" \
|
||||
"$OSM_DIR/us-massachusetts.osm.pbf" \
|
||||
"$OSM_DIR/us-new-york.osm.pbf" \
|
||||
--profile-file "$OSRM_BIN/../profiles/driving.lua" \
|
||||
--timestamp-file "$DATA_DIR/timestamp" \
|
||||
--output-location "$DATA_DIR/northeast" \
|
||||
--ignore-waterway --ignore-tunnels 2>&1 | tail -5
|
||||
fi
|
||||
|
||||
step "4/5 partition + customize"
|
||||
"$OSRM_BIN/osrm-partition" --input-location "$DATA_DIR/northeast"
|
||||
"$OSRM_BIN/osrm-customize" --input-location "$DATA_DIR/northeast" --profile-file "$OSRM_BIN/../profiles/driving.lua"
|
||||
|
||||
step "5/5 serve"
|
||||
echo "Starting osrm-routed on :5000 (Ctrl-C to stop)"
|
||||
exec "$OSRM_BIN/osrm-routed" --algorithm mld --port 5000 "$DATA_DIR/northeast.osrm"
|
||||
Reference in New Issue
Block a user