Repository Public BSD-3-Clause
1# ORIXRouting23The embedded routing engine of ORIX Maps: routes for cars, bicycles and pedestrians are computed on the phone from a4memory-mapped graph file (`routing.orixgraph`, one per region package). No server, no network call.56- Platforms: iOS 18, macOS 15. Depends only on `ORIXGeoCore`. No third-party code.7- The graph file is produced by `Infrastructure/routing-builder` (`orix-routing-build`) from an OpenStreetMap extract.8- Format specification: [`docs/ORIXGRAPH_FORMAT.md`](docs/ORIXGRAPH_FORMAT.md). Reader **and** writer live here.910## Public API1112```swift13// Open a graph (memory-mapped, validated, immutable, Sendable).14let graph = try RoutingGraph(url: packageURL.appending(path: "routing.orixgraph")) // validation: .full (default) | .structure15graph.metadata // GraphMetadata: regionID, boundingBox, osmTimestamp, buildDate, attribution, counts, buildCounters16graph.nearestRoad(to: Coordinate, mode: TravelMode, options: SnapOptions) throws(RoutingError) -> RoutingGraph.RoadLocation17graph.edge(at:) / geometry(ofEdge:) / coordinate(ofNode:) / flags(ofNode:) / directedEdges(leaving:) // inspection18graph.componentRank(ofNode:mode:) / componentNodeCount(rank:mode:)1920// Route.21let router = Router(graph: graph) // value type, no shared state22let response = try await router.route(request) // async throws(RoutingError), cooperative cancellation23let response = try router.compute(request) // same, synchronous (tools, tests)2425RouteRequest(from: Coordinate, to: Coordinate, profile: RoutingProfile = .car, alternatives: Int = 0)26RouteRequest(waypoints: [RouteWaypoint], profile:, alternatives: 0…2, maxSnapDistanceMeters: 500,27 algorithm: .aStar | .dijkstra, alternativeMaxCostRatio: 1.4, alternativeMaxSharedFraction: 0.7)28RouteWaypoint(_ coordinate: Coordinate, heading: Double? = nil, headingTolerance: Double = 60)2930RoutingProfile.car / .bicycle / .pedestrian / .standard(for:) // value types, every speed and penalty is a property31profile.avoiding(RouteAvoidance(tolls:ferries:motorways:unpaved:))3233RouteResponse { route: Route; alternatives: [Route]; routes; statistics: RouteStatistics; regionID; attribution; osmTimestamp }34Route { geometry: [Coordinate]; distanceMeters; durationSeconds; cost; legs: [RouteLeg]; maneuvers: [Maneuver];35 segments: [RouteSegment]; boundingBox; warnings: [RouteWarning]; assumedSpeedDistanceMeters;36 elevationProfile: [ElevationSample]? /* always nil */; waypoints: [SnappedWaypoint]; mode; profileName }37RouteLeg { fromWaypointIndex; toWaypointIndex; distanceMeters; durationSeconds; geometryRange; maneuverRange }38Maneuver { type: ManeuverType; modifier: ManeuverModifier?; roundaboutExit: Int?; waypointIndex: Int?; location;39 bearingBefore; bearingAfter; name; ref; roadClass; distanceMeters; durationSeconds; geometryRange; legIndex }40RouteSegment { geometryRange; distanceMeters; durationSeconds; roadClass; surface; isToll; isFerry; isTunnel; isBridge;41 isLink; isRoundabout; isRestrictedAccess; usesAssumedSpeed; name; ref }42RouteWarning { kind: .ferry | .toll | .unpaved | .restrictedAccess | .assumedSpeeds; distanceMeters; share }43RouteStatistics{ settledStates; searches; peakSearchMemoryBytes; computeSeconds }4445enum RoutingError: Error, Codable { // typed failure reasons46 case invalidRequest(String)47 case pointOutsideCoverage(waypointIndex: Int)48 case pointTooFarFromRoad(waypointIndex: Int, maxDistanceMeters: Double)49 case noConnection(fromWaypointIndex: Int, toWaypointIndex: Int, differentComponents: Bool)50 case cancelled51}5253// Text (separate from the typed maneuvers; the app may build its own strings).54let text = InstructionFormatter(language: .english | .french, units: .metric | .imperial)55text.instruction(for: maneuver) // "Turn left onto Rue Sherbrooke Ouest" / "Tournez à gauche sur la rue Sherbrooke Ouest"56text.announcement(for: maneuver, distanceAheadMeters: 300) // "In 300 metres, turn left onto…" / "Dans 300 mètres, tournez à gauche sur…"57text.distance(1234, style: .written | .spoken) // "1.2 km" / "1,2 km" / "1.2 kilometres" / "0.8 mi" / "350 pi"58text.duration(9900) // "2 h 45 min"59text.roadName(for: maneuver) // "Autoroute Jean-Lesage (20)" / "l'autoroute Jean-Lesage (20)"6061// Writing a graph (used by the builder and by tests).62var writer = RoutingGraphWriter(options: .init(regionID: "ca-qc", osmTimestamp:, boundingBox:, reorderSpatially: true))63let a = try writer.addNode(coordinate, flags: [.trafficSignal])64let e = try writer.addEdge(from: a, to: b, shape: [Coordinate], attributes: .init(roadClass:access:surface:flags:speedKmh:name:ref:wayID:))65try writer.addRestriction(from: e1, via: node, to: e2, kind: .prohibitive | .mandatory, modes: [.car, .bicycle])66let (data, summary) = try writer.build() // or writer.write(to: url)67```6869Every public type is `Sendable`; requests, responses, routes, profiles and errors are `Codable` (a planned route can70be stored and exported). There is no singleton and no global state.7172`ManeuverType`: `depart`, `arrive`, `waypoint`, `turn`, `continue`, `fork` (keep left / right), `merge`, `onRamp`,73`offRamp`, `roundabout` (with `roundaboutExit`), `exitRoundabout`, `uTurn`, `ferry`.74`ManeuverModifier`: `straight`, `slightLeft`, `left`, `sharpLeft`, `slightRight`, `right`, `sharpRight`, `uTurn`75(on `arrive` / `waypoint`: `left` / `right` = side of the road of the requested point, nil when it is on the road).7677## How it works7879**Graph.** Topology is reduced to intersections; each undirected edge carries length, shape reference, road class,80speed (with a *tagged / assumed* bit), per-mode and per-direction access bits, surface, toll / ferry / tunnel / bridge /81roundabout / link flags, a way record (OSM way id, name, ref) and quantized bearings at both ends. Turn restrictions,82connected components per mode and a grid spatial index are separate sections. See the format document.8384**Search.** Unidirectional A* over *directed edges* (edge-based state), which makes turn restrictions, U-turn rules85and turn costs exact without special cases. The heuristic is great-circle distance ÷ the fastest speed the profile can86reach on this graph; it is consistent because edge lengths are never shorter than the great circle and every cost is87≥ length ÷ that speed. Costs are integer milliseconds rounded up, so A* and Dijkstra return exactly the same cost88(`RouteAlgorithm.dijkstra` is the reference, same code with a zero heuristic). Bidirectional search was not89implemented: the measured times are within the targets without it (see below).9091Search state is proportional to the explored area: labels (cost + parent, 8 bytes per directed edge) and heuristic92values live in pages of 2 048 entries allocated on first touch; the builder numbers nodes and edges along a Morton93curve so that a local search touches few pages. Nothing proportional to the graph is allocated per query except the94page table (one pointer per 2 048 states: 19 kB for the province).9596**Costs.** Edge cost = travel time × preference (≥ 1). Car speed = `maxspeed` × a per-class factor when tagged,97otherwise an assumed speed per class. Bicycles and pedestrians move at their own speed per class. Transitions add:98left / right turn delay at real junctions (not while staying on a roundabout), traffic-signal delay (signal on the99node or along the edge), U-turn delay (always possible at a dead end; at junctions and mid-block according to the100profile — the car may turn round at a junction but not mid-block), ferry boarding time, and a cost-only penalty when101entering destination / private / customers access from an open road (such roads end up used only to leave the origin102or reach the destination). A barrier node the mode cannot pass is never crossed.103104**Duration.** Sum of travel times and real delays; preferences and the restricted-access penalty are not time. There105is no traffic. `assumedSpeedDistanceMeters`, the `assumedSpeeds` warning and `RouteSegment.usesAssumedSpeed` say which106part of the trip relies on assumed speeds so that the UI can present the ETA as an estimate. Ferries use their107`duration` tag when present, else 15 km/h (reported as assumed), plus 15 min of boarding.108109**Avoid options** (`tolls`, `ferries`, `motorways`, `unpaved`) exclude the feature from the search, except on the110two edges the origin and destination are snapped to. If nothing else connects the points the result is111`noConnection(differentComponents: false)`; the app can then offer the route without the option.112113**Snapping.** Nearest edge usable by the mode within `maxSnapDistanceMeters` (grid lookup, growing radius). Ferries114are never snapped to. A road of the main network is preferred to a closer isolated or one-way-trapped road when it115is at most 40 m farther. Errors: `pointOutsideCoverage` (outside the graph's bounding box grown by the snap116distance), `pointTooFarFromRoad`.117118**Connectivity.** If the two snapped positions are in different ranked weak components for the mode, the router119answers `noConnection(differentComponents: true)` without searching. Otherwise the search decides (a failed search on120the province graph costs one full Dijkstra, about 0.3 s on the Mac used here).121122**Waypoints.** Each leg is an independent search; the route chains them. A `heading` on the first waypoint selects the123side of the road to leave from (for rerouting while moving).124125**Alternatives** (two-waypoint requests only): penalty method. The edges of the routes found so far are made 1.7×126more expensive and the search is repeated (up to 2 × wanted + 1 times); a candidate is kept when its real cost is at127most `alternativeMaxCostRatio` × the best and it shares at most `alternativeMaxSharedFraction` of its length with every128route already kept. Fewer alternatives than requested (or none) are returned when no candidate qualifies.129130**Maneuvers.** Derived from the path, the junction geometry (bearings measured 18 m before and after the node) and131the other exits available to the mode. Noise is collapsed: no instruction at a node without a choice, none when132following the same road through a bend or past side streets, none for a name change when going straight; two turns133less than 30 m apart are merged (a left-right jog disappears, a link across a divided road becomes one U-turn).134Roundabout exits are counted from the exits passed.135136**Elevation.** There is no elevation data. `Route.elevationProfile` is always nil; nothing is estimated.137138## Tests139140```sh141cd Packages/ORIXRouting142swift test # 48 tests run, 6 real-data tests skipped143ORIX_ROUTING_DATA_DIR="$PWD/../../data/build/routing" swift test # 54 tests, needs montreal.orixgraph and quebec.orixgraph144```145146Result on 2026-11-25 (Swift 6.4.2, macOS 27, Mac with 18 cores / 48 GB): **54 passed, 0 failed** with the real-data147directory; 48 passed, 6 skipped without it.148149| Suite | Tests | What |150|---|---:|---|151| `FormatTests` | 8 | round-trip of every field, spatial reordering, magic / version rejection, every truncation length, out-of-range indices, 1 500 random corruptions × 2 validation modes (open → typed error, or use the graph without crashing), writer input errors, empty graph |152| `RoutingTests` | 22 | shortest path, same edge / same point, one-ways, access per mode, `no_*` and `only_*` restrictions, per-mode restrictions, U-turn policy and `no_u_turn`, heading, barriers, disconnected components, one-way trap, snapping (mode, ferry, too far, outside coverage, main-network preference), waypoints, alternatives, avoid options, ferry timing, assumed speeds, turn and signal delays, restricted access, cancellation, Codable |153| `EquivalenceTests` | 2 (25 cases) | A* = Dijkstra = an independent label-correcting reference on 24 random graphs × 40 random queries with random profiles and avoid options; every path checked by code independent of the search (continuity, access direction, barriers, restrictions); public API on 8 more graphs with three waypoints |154| `ManeuverTests` | 9 | turns at a cross, slight / sharp, collapsed name changes and bends, fork, motorway fork, on-ramp / merge / off-ramp, roundabout exit numbers, short-edge collapsing, ferry, arrival side |155| `InstructionTests` | 7 | English and French sentences for every maneuver type, French articles, ordinals, metric / imperial, written / spoken, announcements |156| `RealDataTests` (opt-in) | 6 | see "Plausibility" below |157158Not covered by a deterministic test: cancellation *during* a search (the test cancels a long search after 2 ms and159accepts "cancelled" or "finished"; cancellation before the search starts is tested deterministically).160161The library also compiles for iOS (`swift build --triple arm64-apple-ios18.0 --sdk "$(xcrun --sdk iphoneos --show-sdk-path)"`,162checked on 2026-11-25). It has **not** been run on a device or in a simulator.163164## Measured numbers165166Machine: Mac, 18 cores, 48 GB, macOS 27.0, Swift 6.4.2, release builds. Other jobs were running on the machine during167the measurements (load average 10–15); times are the median of 5 runs per pair, the best of 5 is in the raw tables.168Commands are run from the repository root with `B=Infrastructure/routing-builder/.build/release/orix-routing-build`.169170### Graph files (2026-11-25, extracts dated 2026-11-24)171172| Region | Extract | Nodes | Edges | Restrictions | File | Bytes / edge | gzip -6 | lzfse |173|---|---:|---:|---:|---:|---:|---:|---:|---:|174| Greater Montréal | 97 MB | 1 042 942 | 1 395 361 | 8 663 | 95 408 384 B (91.0 MB) | 68.4 | 35.9 MB | 41.2 MB |175| Québec City | 22 MB | 106 300 | 144 333 | 751 | 10 661 432 B (10.2 MB) | 73.9 | 4.6 MB | 5.0 MB |176| Province of Québec | 1 169 MB | 1 900 684 | 2 467 372 | 12 699 | 193 564 512 B (184.6 MB) | 78.4 | 84.7 MB | 94.8 MB |177178Province, by section: EDGE 65.9 MB, NODE 29.0, GEOM 23.1, WAY 19.1, ADJ 18.8, GRDI 12.5, NCMP 10.9, GRDK 3.7,179strings 1.2, the rest < 1 MB. Build times and memory are in the builder's README.180181Opening the province graph with full validation: 0.05 s (file in the page cache; `$B info --graph …`).182183### Routing times (`$B bench --graph … --set … --verify --repeat 5`)184185Fixed origin–destination list in `Infrastructure/routing-builder/Sources/ORIXRoutingBuildKit/Places.swift`.186"Settled" = directed-edge states settled; "search memory" = labels + heuristic cache + queue of the largest search.187188Greater Montréal graph (`data/build/routing/montreal.orixgraph`, `--set montreal`), 94 pairs:189190| Mode | Category | Pairs | p50 | p95 | max | Max settled | Max search memory |191|---|---|---:|---:|---:|---:|---:|---:|192| car | urban (1–8 km) | 16 | 1.5 ms | 11.1 ms | 11.1 ms | | |193| car | cross-city (8–77 km) | 16 | 35.0 ms | 136.7 ms | 136.7 ms | 893 181 | 22.0 MB |194| bicycle | urban | 16 | 0.7 ms | 2.7 ms | 2.7 ms | | |195| bicycle | cross-city | 16 | 26.9 ms | 146.1 ms | 146.1 ms | 1 148 650 | 19.2 MB |196| pedestrian | urban | 16 | 1.9 ms | 6.8 ms | 6.8 ms | | |197| pedestrian | cross-city | 14 | 20.9 ms | 66.8 ms | 66.8 ms | 715 429 | 8.7 MB |198199Process peak resident memory for the whole run: 127.7 MB (`/usr/bin/time -l`; includes the 91 MB mapped file, which200the Dijkstra comparison touches almost entirely); peak memory footprint (dirty memory, excludes the mapping): 32.3 MB.201202Province graph (`data/build/routing/quebec.orixgraph`, `--set province`), 114 pairs:203204| Mode | Category | Pairs | p50 | p95 | max | Max settled | Max search memory |205|---|---|---:|---:|---:|---:|---:|---:|206| car | urban | 16 | 1.5 ms | 10.6 ms | 10.6 ms | | |207| car | cross-city | 16 | 32.0 ms | 132.9 ms | 132.9 ms | | |208| car | long (12–1 396 km) | 20 | 26.4 ms | 406.0 ms | 483.6 ms | 2 868 633 | 44.4 MB |209| bicycle | all | 32 | 1.6 ms | 239.4 ms | 280.4 ms | 2 377 623 | 33.9 MB |210| pedestrian | all | 30 | 2.9 ms | 79.3 ms | 367.4 ms | 3 471 185 | 35.8 MB |211212Process peak resident memory: 243.2 MB (includes the 185 MB mapped file); peak memory footprint: 54.2 MB.213214Selected car routes on the province graph:215216| Route | Distance | Duration | Compute (median) | Settled | Search memory |217|---|---:|---:|---:|---:|---:|218| Montréal (McGill) → Québec City (Parliament) | 253.9 km | 2 h 51 | 183 ms | 1 301 023 | 28.7 MB |219| Montréal → Gatineau | 207.6 km | 2 h 15 | 182 ms | 1 294 646 | 26.9 MB |220| Québec City → Saguenay | 211.0 km | 2 h 24 | 20 ms | 199 765 | 3.5 MB |221| Gaspé → Montréal | 917.1 km | 11 h 12 | 132 ms | 1 019 275 | 24.5 MB |222| Gaspé → Gatineau | 1 111.5 km | 13 h 04 | 308 ms | 2 105 595 | 37.7 MB |223| Montréal → Radisson | 1 395.8 km | 17 h 37 | 406 ms | 2 868 633 | 44.4 MB |224225Targets of the brief: Gaspé → Gatineau by car under 1.5 s — **met** (308 ms); urban trips under 150 ms — **met**226(urban max 11 ms; the longest trips across the metropolitan area, up to 77 km, max 137 ms). Because the targets are227met by plain A*, no speed-up structure (bidirectional search, landmarks, contraction) was added.228229Variability: in an earlier run of the same benchmark while other builds were saturating the machine (load average230≈ 29), the province maximum was 1 279 ms (Gatineau → Sept-Îles) instead of 484 ms. The numbers above are from the231calmer run; none was measured on a phone.232233Alternatives cost extra searches: Montréal → Québec City with 2 alternatives requested ran 6 searches in 2.1 s and234returned one alternative (north shore, 274.5 km, 3 h 03 against 253.9 km, 2 h 51); YUL → Olympic Stadium returned two235alternatives in 0.32 s.236237### A* against Dijkstra on real pairs238239`--verify` recomputes every pair with Dijkstra and compares the cost: **208 pairs compared (94 + 114), 0 mismatch**.240`RealDataTests.longRoutesMatchDijkstra` repeats it for three pairs inside the test suite.241242## Plausibility — what was verified and how243244All checks are in `RealDataTests` (run with `ORIX_ROUTING_DATA_DIR`), on the graphs built from the 2026-11-24 extracts.245246| Fact | Check | Result |247|---|---|---|248| Montréal ↔ Québec City ≈ 250–260 km by A-20 / A-40, about 2 h 45 | distance in 245–265 km, duration in 2.4–3.1 h, > 85 % on motorways, refs include 20 or 40 | 253.9 km, 2 h 51, 241.1 km of motorway (A-20, south shore) |249| Pedestrians are never on autoroutes | every motorway carriageway edge of the Montréal graph has no pedestrian access bit; 3 pedestrian routes contain no motorway segment; walking speed 4–5 km/h | 0 carriageway edge open; **15 short ramp edges (`motorway_link`) are open to pedestrians because OpenStreetMap tags them `foot=yes`** — kept as tagged |250| A car respects the one-way streets of the Plateau | every edge named Boulevard Saint-Laurent between Sherbrooke and Mont-Royal is one-way for cars, towards the north-west; the route up the street stays on it (> 90 %), the route down uses less than 35 % of it and is longer; the direction bits of every edge of 5 car paths are checked by code independent of the search | passed |251| A route across the St. Lawrence uses a real crossing | Montréal ↔ Longueuil (car, bicycle, pedestrian) and Québec ↔ Lévis (car, pedestrian): more than 800 m on bridge / tunnel / ferry segments, one uninterrupted structure longer than 500 m, and around Montréal the name of a known crossing | passed (car and pedestrian Montréal → Longueuil by Pont Jacques-Cartier; car Québec → Lévis by the A-73 bridge, 29.3 km; pedestrian Québec → Lévis by the ferry, 3.8 km) |252| Gaspé → Gatineau ≈ 1 100 km | distance in 1 000–1 250 km, same cost as Dijkstra | 1 111.5 km |253| Îles-de-la-Madeleine are not connected by road inside the extract | immediate `noConnection(differentComponents: true)`; Toronto → `pointOutsideCoverage` | passed |254255Looked at by hand only (CLI `route`): instruction lists of a dozen routes in both languages, the Tadoussac –256Baie-Sainte-Catherine ferry ("Take the ferry Tadoussac–Baie-Sainte-Catherine"), avoid motorways + tolls on257Montréal → Québec (288 km, 4 h 47, no motorway).258259Durations that are **not** verified against a reference: everything except Montréal → Québec City. Routes with a large260share of untagged roads are visibly pessimistic (Val-d'Or → Chibougamau: 409 km in 6 h 09, mostly assumed 60 km/h on261rural primary roads) and long ferries without a `duration` tag use 15 km/h (Matane → Baie-Comeau: 3 h 47 for a262crossing that takes about 2 h 20). Both cases carry the `assumedSpeeds` warning.263264## Known limits265266- **Via-way turn restrictions are not applied.** They are counted by the builder (`restrictionsViaWaySkipped`:267 2 884 of 16 903 restriction relations in the province, mostly `no_u_turn` across divided roads).268- Conditional restrictions (`restriction:conditional`, day / hour tags) are ignored and counted (757 in the province).269- Connectivity data ignores turn restrictions and is node-based: `differentComponents: true` is a proof, but two270 points in the same component can still be unconnected (the search then says so after exhausting the network).271- Only 13 % of routable ways carry a usable `maxspeed` in the province (161 925 of 1 252 493): outside motorways and272 main urban streets, durations rely on assumed speeds. There is no urban / rural distinction for the assumptions.273- No traffic, no time-dependent access (`access:conditional`, seasonal closures, opening hours of gates, ferry274 timetables). Winter and ice roads are dropped by the builder.275- `bicycle=dismount` is treated as allowed at cycling speed. Direction-specific access tags (`vehicle:backward=no`…)276 and `maxspeed:forward/backward` are ignored.277- Barrier defaults follow common practice (a bare `barrier=gate` lets cars through, a bollard does not); a locked gate278 without `locked=yes` or an access tag is not known to be closed.279- Pedestrian instructions are noisy where sidewalks and crossings are mapped as separate unnamed footways (many280 "Turn left" without a street name).281- Motorway exit numbers and destination signs are not stored: "Take the exit on the right" has no number.282- Mini-roundabouts (node tag) are ordinary junctions. Lane guidance does not exist.283- Turn angles for cost purposes use the bearing of the first segment of each edge (1.4° resolution): a junction284 drawn with a short curved segment can be mis-read as a turn or as straight.285- Alternatives are only offered for two-waypoint requests and multiply the compute time (see above).286- A failed search (no route inside one component) explores the whole reachable network: about 0.3 s on the province287 graph on this Mac; not measured on a phone.288- File size: 78 bytes per edge for the province. Known remaining slack, not done: the `ADJ ` list of the A side is289 implied by the edge order (−4 bytes / edge), way records could shrink to 12 bytes, node flags could move into `NCMP`.290291## Not done292293- No measurement on an iPhone (time, memory, cold `mmap` page-in). All numbers are from a Mac.294- No bidirectional A*, landmarks or contraction hierarchy (not needed for the targets on this machine).295- No wheelchair / accessibility profile: the data needed (kerbs, slopes, surface quality) is not verified.296- No elevation: no profile, no slope-aware cycling or walking speeds.297- No truck, motorcycle or transit profile; no "shortest distance" or "avoid highways partially" preference beyond the298 four avoid options.299- No via-way restrictions, no conditional restrictions, no time-dependent routing.300- No isochrones, no distance matrix, no map-matching of a GPS trace (the navigation module can use301 `RoutingGraph.nearestRoad` and `RouteWaypoint.heading` for rerouting).302- No incremental update of a graph file: a region is rebuilt and replaced as a whole.303- No checksum inside the file (the region package layer is expected to verify the download).304