SPB Git

Repository Public BSD-3-Clause

README.md 23.4 KB

# ORIXRouting

The embedded routing engine of ORIX Maps: routes for cars, bicycles and pedestrians are computed on the phone from a memory-mapped graph file (routing.orixgraph, one per region package). No server, no network call.

  • Platforms: iOS 18, macOS 15. Depends only on ORIXGeoCore. No third-party code.
  • The graph file is produced by Infrastructure/routing-builder (orix-routing-build) from an OpenStreetMap extract.
  • Format specification: docs/ORIXGRAPH_FORMAT.md. Reader and writer live here.

# Public API

swift
// Open a graph (memory-mapped, validated, immutable, Sendable).
let graph = try RoutingGraph(url: packageURL.appending(path: "routing.orixgraph"))   // validation: .full (default) | .structure
graph.metadata            // GraphMetadata: regionID, boundingBox, osmTimestamp, buildDate, attribution, counts, buildCounters
graph.nearestRoad(to: Coordinate, mode: TravelMode, options: SnapOptions) throws(RoutingError) -> RoutingGraph.RoadLocation
graph.edge(at:) / geometry(ofEdge:) / coordinate(ofNode:) / flags(ofNode:) / directedEdges(leaving:)   // inspection
graph.componentRank(ofNode:mode:) / componentNodeCount(rank:mode:)

// Route.
let router = Router(graph: graph)                                  // value type, no shared state
let response = try await router.route(request)                     // async throws(RoutingError), cooperative cancellation
let response = try router.compute(request)                         // same, synchronous (tools, tests)

RouteRequest(from: Coordinate, to: Coordinate, profile: RoutingProfile = .car, alternatives: Int = 0)
RouteRequest(waypoints: [RouteWaypoint], profile:, alternatives: 0…2, maxSnapDistanceMeters: 500,
             algorithm: .aStar | .dijkstra, alternativeMaxCostRatio: 1.4, alternativeMaxSharedFraction: 0.7)
RouteWaypoint(_ coordinate: Coordinate, heading: Double? = nil, headingTolerance: Double = 60)

RoutingProfile.car / .bicycle / .pedestrian / .standard(for:)      // value types, every speed and penalty is a property
profile.avoiding(RouteAvoidance(tolls:ferries:motorways:unpaved:))

RouteResponse  { route: Route; alternatives: [Route]; routes; statistics: RouteStatistics; regionID; attribution; osmTimestamp }
Route          { geometry: [Coordinate]; distanceMeters; durationSeconds; cost; legs: [RouteLeg]; maneuvers: [Maneuver];
                 segments: [RouteSegment]; boundingBox; warnings: [RouteWarning]; assumedSpeedDistanceMeters;
                 elevationProfile: [ElevationSample]? /* always nil */; waypoints: [SnappedWaypoint]; mode; profileName }
RouteLeg       { fromWaypointIndex; toWaypointIndex; distanceMeters; durationSeconds; geometryRange; maneuverRange }
Maneuver       { type: ManeuverType; modifier: ManeuverModifier?; roundaboutExit: Int?; waypointIndex: Int?; location;
                 bearingBefore; bearingAfter; name; ref; roadClass; distanceMeters; durationSeconds; geometryRange; legIndex }
RouteSegment   { geometryRange; distanceMeters; durationSeconds; roadClass; surface; isToll; isFerry; isTunnel; isBridge;
                 isLink; isRoundabout; isRestrictedAccess; usesAssumedSpeed; name; ref }
RouteWarning   { kind: .ferry | .toll | .unpaved | .restrictedAccess | .assumedSpeeds; distanceMeters; share }
RouteStatistics{ settledStates; searches; peakSearchMemoryBytes; computeSeconds }

enum RoutingError: Error, Codable {          // typed failure reasons
    case invalidRequest(String)
    case pointOutsideCoverage(waypointIndex: Int)
    case pointTooFarFromRoad(waypointIndex: Int, maxDistanceMeters: Double)
    case noConnection(fromWaypointIndex: Int, toWaypointIndex: Int, differentComponents: Bool)
    case cancelled
}

// Text (separate from the typed maneuvers; the app may build its own strings).
let text = InstructionFormatter(language: .english | .french, units: .metric | .imperial)
text.instruction(for: maneuver)                              // "Turn left onto Rue Sherbrooke Ouest" / "Tournez à gauche sur la rue Sherbrooke Ouest"
text.announcement(for: maneuver, distanceAheadMeters: 300)   // "In 300 metres, turn left onto…" / "Dans 300 mètres, tournez à gauche sur…"
text.distance(1234, style: .written | .spoken)               // "1.2 km" / "1,2 km" / "1.2 kilometres" / "0.8 mi" / "350 pi"
text.duration(9900)                                          // "2 h 45 min"
text.roadName(for: maneuver)                                 // "Autoroute Jean-Lesage (20)" / "l'autoroute Jean-Lesage (20)"

// Writing a graph (used by the builder and by tests).
var writer = RoutingGraphWriter(options: .init(regionID: "ca-qc", osmTimestamp:, boundingBox:, reorderSpatially: true))
let a = try writer.addNode(coordinate, flags: [.trafficSignal])
let e = try writer.addEdge(from: a, to: b, shape: [Coordinate], attributes: .init(roadClass:access:surface:flags:speedKmh:name:ref:wayID:))
try writer.addRestriction(from: e1, via: node, to: e2, kind: .prohibitive | .mandatory, modes: [.car, .bicycle])
let (data, summary) = try writer.build()        // or writer.write(to: url)

Every public type is Sendable; requests, responses, routes, profiles and errors are Codable (a planned route can be stored and exported). There is no singleton and no global state.

ManeuverType: depart, arrive, waypoint, turn, continue, fork (keep left / right), merge, onRamp, offRamp, roundabout (with roundaboutExit), exitRoundabout, uTurn, ferry. ManeuverModifier: straight, slightLeft, left, sharpLeft, slightRight, right, sharpRight, uTurn (on arrive / waypoint: left / right = side of the road of the requested point, nil when it is on the road).

# How it works

Graph. Topology is reduced to intersections; each undirected edge carries length, shape reference, road class, speed (with a tagged / assumed bit), per-mode and per-direction access bits, surface, toll / ferry / tunnel / bridge / roundabout / link flags, a way record (OSM way id, name, ref) and quantized bearings at both ends. Turn restrictions, connected components per mode and a grid spatial index are separate sections. See the format document.

Search. Unidirectional A* over directed edges (edge-based state), which makes turn restrictions, U-turn rules and turn costs exact without special cases. The heuristic is great-circle distance ÷ the fastest speed the profile can reach on this graph; it is consistent because edge lengths are never shorter than the great circle and every cost is ≥ length ÷ that speed. Costs are integer milliseconds rounded up, so A* and Dijkstra return exactly the same cost (RouteAlgorithm.dijkstra is the reference, same code with a zero heuristic). Bidirectional search was not implemented: the measured times are within the targets without it (see below).

Search state is proportional to the explored area: labels (cost + parent, 8 bytes per directed edge) and heuristic values live in pages of 2 048 entries allocated on first touch; the builder numbers nodes and edges along a Morton curve so that a local search touches few pages. Nothing proportional to the graph is allocated per query except the page table (one pointer per 2 048 states: 19 kB for the province).

Costs. Edge cost = travel time × preference (≥ 1). Car speed = maxspeed × a per-class factor when tagged, otherwise an assumed speed per class. Bicycles and pedestrians move at their own speed per class. Transitions add: left / right turn delay at real junctions (not while staying on a roundabout), traffic-signal delay (signal on the node or along the edge), U-turn delay (always possible at a dead end; at junctions and mid-block according to the profile — the car may turn round at a junction but not mid-block), ferry boarding time, and a cost-only penalty when entering destination / private / customers access from an open road (such roads end up used only to leave the origin or reach the destination). A barrier node the mode cannot pass is never crossed.

Duration. Sum of travel times and real delays; preferences and the restricted-access penalty are not time. There is no traffic. assumedSpeedDistanceMeters, the assumedSpeeds warning and RouteSegment.usesAssumedSpeed say which part of the trip relies on assumed speeds so that the UI can present the ETA as an estimate. Ferries use their duration tag when present, else 15 km/h (reported as assumed), plus 15 min of boarding.

Avoid options (tolls, ferries, motorways, unpaved) exclude the feature from the search, except on the two edges the origin and destination are snapped to. If nothing else connects the points the result is noConnection(differentComponents: false); the app can then offer the route without the option.

Snapping. Nearest edge usable by the mode within maxSnapDistanceMeters (grid lookup, growing radius). Ferries are never snapped to. A road of the main network is preferred to a closer isolated or one-way-trapped road when it is at most 40 m farther. Errors: pointOutsideCoverage (outside the graph's bounding box grown by the snap distance), pointTooFarFromRoad.

Connectivity. If the two snapped positions are in different ranked weak components for the mode, the router answers noConnection(differentComponents: true) without searching. Otherwise the search decides (a failed search on the province graph costs one full Dijkstra, about 0.3 s on the Mac used here).

Waypoints. Each leg is an independent search; the route chains them. A heading on the first waypoint selects the side of the road to leave from (for rerouting while moving).

Alternatives (two-waypoint requests only): penalty method. The edges of the routes found so far are made 1.7× more expensive and the search is repeated (up to 2 × wanted + 1 times); a candidate is kept when its real cost is at most alternativeMaxCostRatio × the best and it shares at most alternativeMaxSharedFraction of its length with every route already kept. Fewer alternatives than requested (or none) are returned when no candidate qualifies.

Maneuvers. Derived from the path, the junction geometry (bearings measured 18 m before and after the node) and the other exits available to the mode. Noise is collapsed: no instruction at a node without a choice, none when following the same road through a bend or past side streets, none for a name change when going straight; two turns less than 30 m apart are merged (a left-right jog disappears, a link across a divided road becomes one U-turn). Roundabout exits are counted from the exits passed.

Elevation. There is no elevation data. Route.elevationProfile is always nil; nothing is estimated.

# Tests

sh
cd Packages/ORIXRouting
swift test                                   # 48 tests run, 6 real-data tests skipped
ORIX_ROUTING_DATA_DIR="$PWD/../../data/build/routing" swift test    # 54 tests, needs montreal.orixgraph and quebec.orixgraph

Result on 2026-11-25 (Swift 6.4.2, macOS 27, Mac with 18 cores / 48 GB): 54 passed, 0 failed with the real-data directory; 48 passed, 6 skipped without it.

Suite Tests What
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
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
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
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
InstructionTests 7 English and French sentences for every maneuver type, French articles, ordinals, metric / imperial, written / spoken, announcements
RealDataTests (opt-in) 6 see "Plausibility" below

Not covered by a deterministic test: cancellation during a search (the test cancels a long search after 2 ms and accepts "cancelled" or "finished"; cancellation before the search starts is tested deterministically).

The library also compiles for iOS (swift build --triple arm64-apple-ios18.0 --sdk "$(xcrun --sdk iphoneos --show-sdk-path)", checked on 2026-11-25). It has not been run on a device or in a simulator.

# Measured numbers

Machine: Mac, 18 cores, 48 GB, macOS 27.0, Swift 6.4.2, release builds. Other jobs were running on the machine during the measurements (load average 10–15); times are the median of 5 runs per pair, the best of 5 is in the raw tables. Commands are run from the repository root with B=Infrastructure/routing-builder/.build/release/orix-routing-build.

# Graph files (2026-11-25, extracts dated 2026-11-24)

Region Extract Nodes Edges Restrictions File Bytes / edge gzip -6 lzfse
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
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
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

Province, 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, strings 1.2, the rest < 1 MB. Build times and memory are in the builder's README.

Opening the province graph with full validation: 0.05 s (file in the page cache; $B info --graph …).

# Routing times ($B bench --graph … --set … --verify --repeat 5)

Fixed origin–destination list in Infrastructure/routing-builder/Sources/ORIXRoutingBuildKit/Places.swift. "Settled" = directed-edge states settled; "search memory" = labels + heuristic cache + queue of the largest search.

Greater Montréal graph (data/build/routing/montreal.orixgraph, --set montreal), 94 pairs:

Mode Category Pairs p50 p95 max Max settled Max search memory
car urban (1–8 km) 16 1.5 ms 11.1 ms 11.1 ms
car cross-city (8–77 km) 16 35.0 ms 136.7 ms 136.7 ms 893 181 22.0 MB
bicycle urban 16 0.7 ms 2.7 ms 2.7 ms
bicycle cross-city 16 26.9 ms 146.1 ms 146.1 ms 1 148 650 19.2 MB
pedestrian urban 16 1.9 ms 6.8 ms 6.8 ms
pedestrian cross-city 14 20.9 ms 66.8 ms 66.8 ms 715 429 8.7 MB

Process peak resident memory for the whole run: 127.7 MB (/usr/bin/time -l; includes the 91 MB mapped file, which the Dijkstra comparison touches almost entirely); peak memory footprint (dirty memory, excludes the mapping): 32.3 MB.

Province graph (data/build/routing/quebec.orixgraph, --set province), 114 pairs:

Mode Category Pairs p50 p95 max Max settled Max search memory
car urban 16 1.5 ms 10.6 ms 10.6 ms
car cross-city 16 32.0 ms 132.9 ms 132.9 ms
car long (12–1 396 km) 20 26.4 ms 406.0 ms 483.6 ms 2 868 633 44.4 MB
bicycle all 32 1.6 ms 239.4 ms 280.4 ms 2 377 623 33.9 MB
pedestrian all 30 2.9 ms 79.3 ms 367.4 ms 3 471 185 35.8 MB

Process peak resident memory: 243.2 MB (includes the 185 MB mapped file); peak memory footprint: 54.2 MB.

Selected car routes on the province graph:

Route Distance Duration Compute (median) Settled Search memory
Montréal (McGill) → Québec City (Parliament) 253.9 km 2 h 51 183 ms 1 301 023 28.7 MB
Montréal → Gatineau 207.6 km 2 h 15 182 ms 1 294 646 26.9 MB
Québec City → Saguenay 211.0 km 2 h 24 20 ms 199 765 3.5 MB
Gaspé → Montréal 917.1 km 11 h 12 132 ms 1 019 275 24.5 MB
Gaspé → Gatineau 1 111.5 km 13 h 04 308 ms 2 105 595 37.7 MB
Montréal → Radisson 1 395.8 km 17 h 37 406 ms 2 868 633 44.4 MB

Targets of the brief: Gaspé → Gatineau by car under 1.5 s — met (308 ms); urban trips under 150 ms — met (urban max 11 ms; the longest trips across the metropolitan area, up to 77 km, max 137 ms). Because the targets are met by plain A*, no speed-up structure (bidirectional search, landmarks, contraction) was added.

Variability: in an earlier run of the same benchmark while other builds were saturating the machine (load average ≈ 29), the province maximum was 1 279 ms (Gatineau → Sept-Îles) instead of 484 ms. The numbers above are from the calmer run; none was measured on a phone.

Alternatives cost extra searches: Montréal → Québec City with 2 alternatives requested ran 6 searches in 2.1 s and returned one alternative (north shore, 274.5 km, 3 h 03 against 253.9 km, 2 h 51); YUL → Olympic Stadium returned two alternatives in 0.32 s.

# A* against Dijkstra on real pairs

--verify recomputes every pair with Dijkstra and compares the cost: 208 pairs compared (94 + 114), 0 mismatch. RealDataTests.longRoutesMatchDijkstra repeats it for three pairs inside the test suite.

# Plausibility — what was verified and how

All checks are in RealDataTests (run with ORIX_ROUTING_DATA_DIR), on the graphs built from the 2026-11-24 extracts.

Fact Check Result
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)
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
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
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)
Gaspé → Gatineau ≈ 1 100 km distance in 1 000–1 250 km, same cost as Dijkstra 1 111.5 km
Îles-de-la-Madeleine are not connected by road inside the extract immediate noConnection(differentComponents: true); Toronto → pointOutsideCoverage passed

Looked at by hand only (CLI route): instruction lists of a dozen routes in both languages, the Tadoussac – Baie-Sainte-Catherine ferry ("Take the ferry Tadoussac–Baie-Sainte-Catherine"), avoid motorways + tolls on Montréal → Québec (288 km, 4 h 47, no motorway).

Durations that are not verified against a reference: everything except Montréal → Québec City. Routes with a large share of untagged roads are visibly pessimistic (Val-d'Or → Chibougamau: 409 km in 6 h 09, mostly assumed 60 km/h on rural primary roads) and long ferries without a duration tag use 15 km/h (Matane → Baie-Comeau: 3 h 47 for a crossing that takes about 2 h 20). Both cases carry the assumedSpeeds warning.

# Known limits

  • Via-way turn restrictions are not applied. They are counted by the builder (restrictionsViaWaySkipped: 2 884 of 16 903 restriction relations in the province, mostly no_u_turn across divided roads).
  • Conditional restrictions (restriction:conditional, day / hour tags) are ignored and counted (757 in the province).
  • Connectivity data ignores turn restrictions and is node-based: differentComponents: true is a proof, but two points in the same component can still be unconnected (the search then says so after exhausting the network).
  • Only 13 % of routable ways carry a usable maxspeed in the province (161 925 of 1 252 493): outside motorways and main urban streets, durations rely on assumed speeds. There is no urban / rural distinction for the assumptions.
  • No traffic, no time-dependent access (access:conditional, seasonal closures, opening hours of gates, ferry timetables). Winter and ice roads are dropped by the builder.
  • bicycle=dismount is treated as allowed at cycling speed. Direction-specific access tags (vehicle:backward=no…) and maxspeed:forward/backward are ignored.
  • Barrier defaults follow common practice (a bare barrier=gate lets cars through, a bollard does not); a locked gate without locked=yes or an access tag is not known to be closed.
  • Pedestrian instructions are noisy where sidewalks and crossings are mapped as separate unnamed footways (many "Turn left" without a street name).
  • Motorway exit numbers and destination signs are not stored: "Take the exit on the right" has no number.
  • Mini-roundabouts (node tag) are ordinary junctions. Lane guidance does not exist.
  • Turn angles for cost purposes use the bearing of the first segment of each edge (1.4° resolution): a junction drawn with a short curved segment can be mis-read as a turn or as straight.
  • Alternatives are only offered for two-waypoint requests and multiply the compute time (see above).
  • A failed search (no route inside one component) explores the whole reachable network: about 0.3 s on the province graph on this Mac; not measured on a phone.
  • File size: 78 bytes per edge for the province. Known remaining slack, not done: the ADJ list of the A side is implied by the edge order (−4 bytes / edge), way records could shrink to 12 bytes, node flags could move into NCMP.

# Not done

  • No measurement on an iPhone (time, memory, cold mmap page-in). All numbers are from a Mac.
  • No bidirectional A*, landmarks or contraction hierarchy (not needed for the targets on this machine).
  • No wheelchair / accessibility profile: the data needed (kerbs, slopes, surface quality) is not verified.
  • No elevation: no profile, no slope-aware cycling or walking speeds.
  • No truck, motorcycle or transit profile; no "shortest distance" or "avoid highways partially" preference beyond the four avoid options.
  • No via-way restrictions, no conditional restrictions, no time-dependent routing.
  • No isochrones, no distance matrix, no map-matching of a GPS trace (the navigation module can use RoutingGraph.nearestRoad and RouteWaypoint.heading for rerouting).
  • No incremental update of a graph file: a region is rebuilt and replaced as a whole.
  • No checksum inside the file (the region package layer is expected to verify the download).
Files main
Menu

Theme