Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Infrastructure/routing-builder/Sources/orix-routing-build/main.swift10// Module : orix-routing-build11// Repository : https://git.spboucher.ai/orix-maps12// Created : 2026-11-2513// Last Modified : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import ORIXGeoCore90import ORIXRouting91import ORIXRoutingBuildKit9293// orix-routing-build — builds and inspects ORIX routing graphs. See README.md for the commands.9495func fail(_ message: String, code: Int32 = 1) -> Never {96 FileHandle.standardError.write(Data("error: \(message)\n".utf8))97 exit(code)98}99100let usage = """101usage:102 orix-routing-build --pbf <file.osm.pbf> --region <id> --out <routing.orixgraph> [--bbox minLon,minLat,maxLon,maxLat] [--simplify metres] [--report <file.json>]103 orix-routing-build info --graph <file>104 orix-routing-build route --graph <file> --from lat,lon --to lat,lon [--via lat,lon]… [--mode car|bicycle|pedestrian]105 [--avoid tolls,ferries,motorways,unpaved] [--alternatives 0…2] [--lang en|fr] [--units metric|imperial]106 [--dijkstra] [--heading degrees] [--geojson <file>] [--json <file>]107 orix-routing-build bench --graph <file> --set montreal|province [--modes car,bicycle,pedestrian] [--verify] [--repeat n]108"""109110struct Arguments {111 var values: [String: [String]] = [:]112 var flags: Set<String> = []113114 init(_ args: [String], flags flagNames: Set<String>) {115 var i = 0116 while i < args.count {117 let a = args[i]118 guard a.hasPrefix("--") else { fail("unexpected argument \(a)\n\(usage)", code: 2) }119 let key = String(a.dropFirst(2))120 if flagNames.contains(key) { flags.insert(key); i += 1; continue }121 guard i + 1 < args.count else { fail("missing value for \(a)\n\(usage)", code: 2) }122 values[key, default: []].append(args[i + 1])123 i += 2124 }125 }126127 func one(_ key: String) -> String? { values[key]?.last }128 func required(_ key: String) -> String {129 guard let v = one(key) else { fail("missing --\(key)\n\(usage)", code: 2) }130 return v131 }132}133134func parseCoordinate(_ text: String) -> Coordinate {135 let parts = text.split(separator: ",").map { Double($0.trimmingCharacters(in: .whitespaces)) }136 guard parts.count == 2, let lat = parts[0], let lon = parts[1], Coordinate(latitude: lat, longitude: lon).isValid else {137 fail("invalid coordinate '\(text)' (expected lat,lon)", code: 2)138 }139 return Coordinate(latitude: lat, longitude: lon)140}141142func parseMode(_ text: String) -> TravelMode {143 switch text {144 case "car": return .car145 case "bicycle", "bike": return .bicycle146 case "pedestrian", "foot", "walk": return .pedestrian147 default: fail("unknown mode '\(text)'", code: 2)148 }149}150151func peakRSS() -> Int {152 var usage = rusage()153 getrusage(RUSAGE_SELF, &usage)154 return Int(usage.ru_maxrss)155}156157func megabytes(_ bytes: Int) -> String { String(format: "%.1f MB", Double(bytes) / 1_048_576) }158159func openGraph(_ path: String) -> RoutingGraph {160 do {161 return try RoutingGraph(url: URL(fileURLWithPath: path))162 } catch {163 fail("\(error)")164 }165}166167// MARK: build168169func runBuild(_ args: Arguments) {170 let pbf = args.required("pbf"), region = args.required("region"), out = args.required("out")171 var box: BoundingBox?172 if let b = args.one("bbox") {173 let p = b.split(separator: ",").map { Double($0) }174 guard p.count == 4, let minLon = p[0], let minLat = p[1], let maxLon = p[2], let maxLat = p[3] else { fail("invalid --bbox", code: 2) }175 box = BoundingBox(minLat: minLat, minLon: minLon, maxLat: maxLat, maxLon: maxLon)176 }177 let started = Date()178 var configuration = GraphExtractor.Configuration(regionID: region, boundingBox: box, log: { print($0) })179 if let s = args.one("simplify") {180 guard let tolerance = Double(s), tolerance >= 0, tolerance <= 50 else { fail("invalid --simplify", code: 2) }181 configuration.simplifyToleranceMeters = tolerance182 }183 let extractor = GraphExtractor(configuration: configuration)184 do {185 let report = try extractor.build(pbf: URL(fileURLWithPath: pbf), output: URL(fileURLWithPath: out))186 let s = report.summary187 print("wrote \(out)")188 print(" nodes \(s.nodeCount) edges \(s.edgeCount) ways \(s.wayCount) restrictions \(s.restrictionCount) strings \(s.stringCount)")189 print(" file \(s.fileBytes) bytes (\(megabytes(s.fileBytes))) \(String(format: "%.1f", s.bytesPerEdge)) bytes per edge")190 print(" sections: " + s.sectionBytes.sorted { $0.value > $1.value }.map { "\($0.key) \(megabytes($0.value))" }.joined(separator: ", "))191 print(" counters: " + report.counters.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: " "))192 print(" osm timestamp: \(report.osmTimestamp.map { ISO8601DateFormatter().string(from: $0) } ?? "unknown")")193 print(String(format: " total %.1f s, peak memory %@", Date().timeIntervalSince(started), megabytes(peakRSS())))194 if let path = args.one("report") {195 let encoder = JSONEncoder()196 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]197 encoder.dateEncodingStrategy = .iso8601198 try encoder.encode(report).write(to: URL(fileURLWithPath: path))199 }200 } catch {201 fail("\(error)")202 }203}204205// MARK: info206207func runInfo(_ args: Arguments) {208 let started = Date()209 let graph = openGraph(args.required("graph"))210 let m = graph.metadata211 print("region \(m.regionID) format \(m.formatMajor).\(m.formatMinor) generator \(m.generator)")212 print("file \(graph.fileSize) bytes nodes \(m.nodeCount) edges \(m.edgeCount) ways \(m.wayCount) restrictions \(m.restrictionCount) strings \(m.stringCount)")213 print("bbox \(m.boundingBox.minLon),\(m.boundingBox.minLat),\(m.boundingBox.maxLon),\(m.boundingBox.maxLat)")214 print("osm timestamp \(m.osmTimestamp.map { ISO8601DateFormatter().string(from: $0) } ?? "unknown") built \(ISO8601DateFormatter().string(from: m.buildDate))")215 print("attribution \(m.attribution)")216 print("max tagged speed \(m.maxTaggedSpeedKmh) km/h ferry edges \(m.ferryEdgeCount) max ferry speed \(m.maxFerrySpeedKmh) km/h")217 for mode in TravelMode.allCases {218 let largest = graph.componentNodeCount(rank: 1, mode: mode) ?? 0219 print("components \(mode): \(m.rankedComponentCounts[Int(mode.rawValue)]) ranked, largest \(largest) nodes")220 }221 print("counters: " + m.buildCounters.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: " "))222 print(String(format: "opened and fully validated in %.3f s", Date().timeIntervalSince(started)))223}224225// MARK: route226227func profile(mode: TravelMode, avoid: String?) -> RoutingProfile {228 var p = RoutingProfile.standard(for: mode)229 for a in (avoid ?? "").split(separator: ",") {230 switch a {231 case "tolls": p.avoid.tolls = true232 case "ferries": p.avoid.ferries = true233 case "motorways": p.avoid.motorways = true234 case "unpaved": p.avoid.unpaved = true235 default: fail("unknown avoid option '\(a)'", code: 2)236 }237 }238 return p239}240241func describe(_ route: Route, title: String, formatter: InstructionFormatter) {242 print("\(title): \(formatter.distance(route.distanceMeters)) (\(String(format: "%.1f", route.distanceMeters / 1000)) km), \(formatter.duration(route.durationSeconds)), cost \(String(format: "%.0f", route.cost)) s, \(route.geometry.count) points")243 var byClass: [RoadClass: Double] = [:]244 for s in route.segments { byClass[s.roadClass, default: 0] += s.distanceMeters }245 print(" road classes: " + byClass.sorted { $0.value > $1.value }.map { "\($0.key) \(String(format: "%.1f", $0.value / 1000)) km" }.joined(separator: ", "))246 if route.warnings.isEmpty { print(" warnings: none") }247 for w in route.warnings { print(" warning: \(w.kind.rawValue) on \(String(format: "%.1f", w.distanceMeters / 1000)) km (\(String(format: "%.0f", w.share * 100)) %)") }248 for w in route.waypoints { print(" waypoint snapped \(String(format: "%.0f", w.distanceMeters)) m to \(w.name ?? "unnamed road")") }249}250251func runRoute(_ args: Arguments) {252 let graph = openGraph(args.required("graph"))253 let mode = parseMode(args.one("mode") ?? "car")254 var points = [parseCoordinate(args.required("from"))]255 points += (args.values["via"] ?? []).map(parseCoordinate)256 points.append(parseCoordinate(args.required("to")))257 var waypoints = points.map { RouteWaypoint($0) }258 if let h = args.one("heading"), let heading = Double(h) { waypoints[0].heading = heading }259 var request = RouteRequest(waypoints: waypoints, profile: profile(mode: mode, avoid: args.one("avoid")),260 alternatives: Int(args.one("alternatives") ?? "0") ?? 0)261 if args.flags.contains("dijkstra") { request.algorithm = .dijkstra }262 if let s = args.one("snap"), let d = Double(s) { request.maxSnapDistanceMeters = d }263 let formatter = InstructionFormatter(language: args.one("lang") == "fr" ? .french : .english,264 units: args.one("units") == "imperial" ? .imperial : .metric)265 do {266 let response = try Router(graph: graph).compute(request)267 describe(response.route, title: "route", formatter: formatter)268 for (i, m) in response.route.maneuvers.enumerated() {269 let d = m.type == .arrive ? "" : " [\(formatter.distance(m.distanceMeters))]"270 print(String(format: "%3d. ", i + 1) + formatter.instruction(for: m) + d)271 }272 for (i, alternative) in response.alternatives.enumerated() { describe(alternative, title: "alternative \(i + 1)", formatter: formatter) }273 let s = response.statistics274 print(String(format: "computed in %.1f ms, %d states settled in %d search(es), search memory %@, process peak %@",275 s.computeSeconds * 1000, s.settledStates, s.searches, megabytes(s.peakSearchMemoryBytes), megabytes(peakRSS())))276 print("data: \(response.attribution), \(response.osmTimestamp.map { ISO8601DateFormatter().string(from: $0) } ?? "date unknown")")277 if let path = args.one("geojson") {278 var features: [String] = []279 for (i, r) in response.routes.enumerated() {280 let coordinates = r.geometry.map { String(format: "[%.6f,%.6f]", $0.longitude, $0.latitude) }.joined(separator: ",")281 features.append("{\"type\":\"Feature\",\"properties\":{\"index\":\(i),\"distance\":\(Int(r.distanceMeters)),\"duration\":\(Int(r.durationSeconds))},\"geometry\":{\"type\":\"LineString\",\"coordinates\":[\(coordinates)]}}")282 }283 try Data("{\"type\":\"FeatureCollection\",\"features\":[\(features.joined(separator: ","))]}".utf8).write(to: URL(fileURLWithPath: path))284 }285 if let path = args.one("json") {286 let encoder = JSONEncoder()287 encoder.dateEncodingStrategy = .iso8601288 try encoder.encode(response).write(to: URL(fileURLWithPath: path))289 }290 } catch let error as RoutingError {291 fail("\(error)")292 } catch {293 fail("\(error)")294 }295}296297// MARK: bench298299func percentile(_ sorted: [Double], _ p: Double) -> Double {300 guard !sorted.isEmpty else { return 0 }301 let rank = Int((p * Double(sorted.count)).rounded(.up)) - 1302 return sorted[min(sorted.count - 1, max(0, rank))]303}304305func runBench(_ args: Arguments) {306 let graph = openGraph(args.required("graph"))307 let set = args.required("set")308 let modes = (args.one("modes") ?? "car,bicycle,pedestrian").split(separator: ",").map { parseMode(String($0)) }309 let verify = args.flags.contains("verify")310 let repeats = max(1, Int(args.one("repeat") ?? "3") ?? 3)311 let router = Router(graph: graph)312 let formatter = InstructionFormatter()313 var mismatches = 0, verified = 0314 for mode in modes {315 let pairs: [BenchmarkPlaces.Pair]316 switch set {317 case "montreal": pairs = BenchmarkPlaces.montreal(mode)318 case "province": pairs = BenchmarkPlaces.province(mode)319 default: fail("unknown set '\(set)'", code: 2)320 }321 print("\n## \(mode) — \(pairs.count) pairs (\(set))\n")322 print("| from → to | category | km | duration | ms (median of \(repeats)) | ms (best) | settled states | search memory | Dijkstra |")323 print("|---|---|---:|---:|---:|---:|---:|---:|---|")324 var times: [String: [Double]] = [:], bestTimes: [String: [Double]] = [:]325 var allTimes: [Double] = [], allBest: [Double] = [], settledAll: [Double] = [], memoryAll: [Double] = []326 var failures = 0327 for pair in pairs {328 guard let a = BenchmarkPlaces.places[pair.from], let b = BenchmarkPlaces.places[pair.to] else { fail("unknown place in \(pair)") }329 let request = RouteRequest(from: a, to: b, profile: .standard(for: mode))330 var samples: [Double] = []331 var response: RouteResponse?332 var failure: String?333 for _ in 0..<repeats {334 do {335 let r = try router.compute(request)336 samples.append(r.statistics.computeSeconds * 1000)337 response = r338 } catch {339 failure = "\(error)"340 break341 }342 }343 guard let response, failure == nil else {344 failures += 1345 print("| \(pair.from) → \(pair.to) | \(pair.category) | — | — | — | — | — | — | \(failure ?? "failed") |")346 continue347 }348 samples.sort()349 let ms = samples[samples.count / 2]350 var check = "not run"351 if verify {352 var reference = request353 reference.algorithm = .dijkstra354 do {355 let d = try router.compute(reference)356 verified += 1357 if d.route.cost == response.route.cost {358 check = "same cost (\(d.statistics.settledStates) settled, \(String(format: "%.0f", d.statistics.computeSeconds * 1000)) ms)"359 } else {360 mismatches += 1361 check = "MISMATCH \(d.route.cost) vs \(response.route.cost)"362 }363 } catch {364 mismatches += 1365 check = "Dijkstra failed: \(error)"366 }367 }368 let r = response.route369 print("| \(pair.from) → \(pair.to) | \(pair.category) | \(String(format: "%.1f", r.distanceMeters / 1000)) | \(formatter.duration(r.durationSeconds)) | \(String(format: "%.1f", ms)) | \(String(format: "%.1f", samples[0])) | \(response.statistics.settledStates) | \(megabytes(response.statistics.peakSearchMemoryBytes)) | \(check) |")370 times[pair.category, default: []].append(ms)371 bestTimes[pair.category, default: []].append(samples[0])372 allTimes.append(ms)373 allBest.append(samples[0])374 settledAll.append(Double(response.statistics.settledStates))375 memoryAll.append(Double(response.statistics.peakSearchMemoryBytes))376 }377 print("")378 for (category, values) in times.sorted(by: { $0.key < $1.key }) {379 let v = values.sorted(), b = (bestTimes[category] ?? []).sorted()380 print("- \(mode) \(category): n=\(v.count) median-of-\(repeats): p50 \(String(format: "%.1f", percentile(v, 0.5))) ms p95 \(String(format: "%.1f", percentile(v, 0.95))) ms max \(String(format: "%.1f", v.last ?? 0)) ms | best-of-\(repeats): p50 \(String(format: "%.1f", percentile(b, 0.5))) ms p95 \(String(format: "%.1f", percentile(b, 0.95))) ms max \(String(format: "%.1f", b.last ?? 0)) ms")381 }382 let v = allTimes.sorted(), b = allBest.sorted()383 print("- \(mode) all: n=\(v.count) median-of-\(repeats): p50 \(String(format: "%.1f", percentile(v, 0.5))) ms p95 \(String(format: "%.1f", percentile(v, 0.95))) ms max \(String(format: "%.1f", v.last ?? 0)) ms | best-of-\(repeats): p50 \(String(format: "%.1f", percentile(b, 0.5))) ms p95 \(String(format: "%.1f", percentile(b, 0.95))) ms max \(String(format: "%.1f", b.last ?? 0)) ms | max settled \(Int(settledAll.max() ?? 0)) max search memory \(megabytes(Int(memoryAll.max() ?? 0))) failures \(failures)")384 }385 print("\nprocess peak memory (resident, includes the mapped graph pages touched): \(megabytes(peakRSS()))")386 if verify { print("Dijkstra comparison: \(verified) pairs compared, \(mismatches) mismatches") }387 if mismatches > 0 { exit(3) }388}389390// MARK: entry391392var arguments = Array(CommandLine.arguments.dropFirst())393guard !arguments.isEmpty else { fail(usage, code: 2) }394switch arguments[0] {395case "info":396 runInfo(Arguments(Array(arguments.dropFirst()), flags: []))397case "route":398 runRoute(Arguments(Array(arguments.dropFirst()), flags: ["dijkstra"]))399case "bench":400 runBench(Arguments(Array(arguments.dropFirst()), flags: ["verify"]))401case "build":402 runBuild(Arguments(Array(arguments.dropFirst()), flags: []))403case "--help", "-h", "help":404 print(usage)405default:406 runBuild(Arguments(arguments, flags: []))407}408