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/ORIXRoutingBuildKit/GraphExtractor.swift10// Module : ORIXRoutingBuildKit11// 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 ORIXOSM91import ORIXRouting9293public enum GraphExtractorError: Error, CustomStringConvertible {94 case noRoutableWay95 case invalidBoundingBox9697 public var description: String {98 switch self {99 case .noRoutableWay: "the extract contains no routable way"100 case .invalidBoundingBox: "invalid bounding box"101 }102 }103}104105/// Reads an `.osm.pbf` extract in two passes and feeds a `RoutingGraphWriter`.106///107/// Pass 1 (ways, relations): keeps routable ways and turn restrictions. Pass 2 (nodes): keeps the coordinates and the108/// barrier / signal tags of the nodes those ways use, nothing else (the province has 139 M nodes, about 15 % are on roads).109public struct GraphExtractor {110 public struct Configuration: Sendable {111 public var regionID: String112 /// Keeps only road segments whose two ends are inside the box.113 public var boundingBox: BoundingBox?114 public var buildDate: Date115 /// Douglas–Peucker tolerance applied to the intermediate points of each edge, in metres (0 = keep every point).116 public var simplifyToleranceMeters: Double117 public var log: (@Sendable (String) -> Void)?118119 public init(regionID: String, boundingBox: BoundingBox? = nil, buildDate: Date = Date(), simplifyToleranceMeters: Double = 0.5,120 log: (@Sendable (String) -> Void)? = nil) {121 self.regionID = regionID122 self.boundingBox = boundingBox123 self.buildDate = buildDate124 self.simplifyToleranceMeters = simplifyToleranceMeters125 self.log = log126 }127 }128129 public struct Report: Sendable, Codable {130 public var counters: [String: Int]131 public var summary: RoutingGraphWriter.Summary132 public var secondsPass1: Double133 public var secondsPass2: Double134 public var secondsGraph: Double135 public var secondsWrite: Double136 public var osmTimestamp: Date?137 }138139 public let configuration: Configuration140141 public init(configuration: Configuration) { self.configuration = configuration }142143 private struct KeptWay {144 var id: Int64145 var attributes: WayAttributes146 var firstRef: Int147 var refCount: Int148 }149150 public func build(pbf: URL, output: URL) throws -> Report {151 let (data, report) = try buildData(reader: OSMPBFReader(url: pbf))152 let start = Date()153 try data.write(to: output, options: .atomic)154 var r = report155 r.secondsWrite += Date().timeIntervalSince(start)156 return r157 }158159 public func buildData(reader: OSMPBFReader) throws -> (Data, Report) {160 let log = configuration.log ?? { _ in }161 if let box = configuration.boundingBox, !box.isValid || box.crossesAntimeridian { throw GraphExtractorError.invalidBoundingBox }162 var counters: [String: Int] = [:]163 func count(_ key: String, _ n: Int = 1) { counters[key, default: 0] += n }164 let header = try reader.header()165 let osmTimestamp = header.replicationTimestamp.flatMap { $0 > 0 ? Date(timeIntervalSince1970: TimeInterval($0)) : nil }166167 // Pass 1: ways and relations.168 var t0 = Date()169 var ways: [KeptWay] = []170 var refs: [Int64] = []171 var restrictions: [ParsedRestriction] = []172 try reader.read([.ways, .relations]) { block in173 for w in block.ways {174 count("osmWays")175 guard w.nodeRefs.count >= 2, let attributes = TagInterpreter.interpret(way: w.tags) else { continue }176 ways.append(KeptWay(id: w.id, attributes: attributes, firstRef: refs.count, refCount: w.nodeRefs.count))177 refs.append(contentsOf: w.nodeRefs)178 }179 for r in block.relations {180 switch TagInterpreter.interpret(restriction: r) {181 case .notARestriction: break182 case .restriction(let p): restrictions.append(p); count("restrictionRelations")183 case .conditional: count("restrictionsConditionalIgnored")184 case .viaWay: count("restrictionsViaWaySkipped")185 case .otherVehicles: count("restrictionsOtherVehiclesIgnored")186 case .invalid: count("restrictionsInvalid")187 }188 }189 }190 guard !ways.isEmpty else { throw GraphExtractorError.noRoutableWay }191 count("routableWays", ways.count)192 let secondsPass1 = Date().timeIntervalSince(t0)193 log("pass 1: \(ways.count) routable ways, \(refs.count) node references, \(restrictions.count) restrictions (\(String(format: "%.1f", secondsPass1)) s)")194195 // Dense indices for the nodes used by routable ways.196 t0 = Date()197 var unique = refs198 unique.sort()199 var write = 0200 for i in 0..<unique.count where i == 0 || unique[i] != unique[i - 1] { unique[write] = unique[i]; write += 1 }201 unique.removeSubrange(write...)202 func lowerBound(_ id: Int64) -> Int {203 var lo = 0, hi = unique.count204 while lo < hi {205 let mid = (lo + hi) >> 1206 if unique[mid] < id { lo = mid + 1 } else { hi = mid }207 }208 return lo209 }210 var refIndex = [UInt32](repeating: 0, count: refs.count)211 for i in 0..<refs.count { refIndex[i] = UInt32(lowerBound(refs[i])) }212 refs = []213 let usedCount = unique.count214 count("nodesOnRoutableWays", usedCount)215216 // Pass 2: coordinates and tags of those nodes.217 var lat = [Int32](repeating: Int32.min, count: usedCount)218 var lon = [Int32](repeating: 0, count: usedCount)219 var nodeFlags = [UInt8](repeating: 0, count: usedCount)220 var cursor = 0221 var previousID = Int64.min222 try reader.read(.nodes) { block in223 for n in block.nodes {224 count("osmNodes")225 if n.id < previousID { cursor = lowerBound(n.id) }226 previousID = n.id227 while cursor < usedCount, unique[cursor] < n.id { cursor += 1 }228 guard cursor < usedCount, unique[cursor] == n.id else { continue }229 let c = Coordinate(latitude: n.latitude, longitude: n.longitude)230 guard c.isValid else { continue }231 let e7 = c.e7232 lat[cursor] = e7.lat; lon[cursor] = e7.lon233 if !n.tags.isEmpty { nodeFlags[cursor] = UInt8(truncatingIfNeeded: TagInterpreter.interpret(node: n.tags).rawValue) }234 }235 }236 let secondsPass2 = Date().timeIntervalSince(t0)237 log("pass 2: \(usedCount) nodes on routable ways (\(String(format: "%.1f", secondsPass2)) s)")238239 // Which nodes can be used (present in the extract, inside the box).240 t0 = Date()241 var usable = [Bool](repeating: false, count: usedCount)242 let box = configuration.boundingBox243 for i in 0..<usedCount where lat[i] != Int32.min {244 if let box {245 usable[i] = box.contains(Coordinate(latE7: lat[i], lonE7: lon[i]))246 } else {247 usable[i] = true248 }249 }250 count("nodesMissingOrOutside", usable.count(where: { !$0 }))251252 // Graph nodes: junctions, way ends, barriers, via nodes of restrictions.253 var uses = [UInt8](repeating: 0, count: usedCount)254 var isGraphNode = [Bool](repeating: false, count: usedCount)255 let blockMask = UInt8(truncatingIfNeeded: NodeFlags.blocksCar.rawValue | NodeFlags.blocksBicycle.rawValue | NodeFlags.blocksPedestrian.rawValue)256 for w in ways {257 var previousUsable = false258 for k in 0..<w.refCount {259 let i = Int(refIndex[w.firstRef + k])260 let ok = usable[i]261 if ok {262 if uses[i] < 255 { uses[i] += 1 }263 let nextUsable = k + 1 < w.refCount && usable[Int(refIndex[w.firstRef + k + 1])]264 if !previousUsable || !nextUsable { isGraphNode[i] = true } // end of a run265 }266 previousUsable = ok267 }268 }269 for i in 0..<usedCount where usable[i] && (uses[i] >= 2 || nodeFlags[i] & blockMask != 0) { isGraphNode[i] = true }270 var viaNodeIndex: [Int: [(way: Int64, edge: UInt32)]] = [:]271 for r in restrictions {272 let i = lowerBound(r.viaNode)273 if i < usedCount, unique[i] == r.viaNode, usable[i] { isGraphNode[i] = true; viaNodeIndex[i] = [] }274 }275276 // Edges.277 var writer = RoutingGraphWriter(options: .init(regionID: configuration.regionID))278 let none = UInt32.max279 var graphNode = [UInt32](repeating: none, count: usedCount)280 func node(_ i: Int, _ writer: inout RoutingGraphWriter) throws -> UInt32 {281 if graphNode[i] != none { return graphNode[i] }282 let flags = NodeFlags(rawValue: UInt32(nodeFlags[i]))283 let index = try writer.addNode(latE7: lat[i], lonE7: lon[i], flags: flags)284 graphNode[i] = index285 return index286 }287 let signalBit = UInt8(truncatingIfNeeded: NodeFlags.trafficSignal.rawValue)288 let tolerance = max(0, configuration.simplifyToleranceMeters)289 var shapeLat: [Int32] = [], shapeLon: [Int32] = [], run: [Int] = []290 for w in ways {291 var attributes = RoutingGraphWriter.EdgeAttributes(292 roadClass: w.attributes.roadClass, access: w.attributes.access, surface: w.attributes.surface, flags: w.attributes.flags,293 speedKmh: w.attributes.speedKmh, name: w.attributes.name, ref: w.attributes.ref, wayID: w.id)294 if w.attributes.roadClass == .ferry {295 count("ferryWays")296 if let duration = w.attributes.ferryDurationSeconds {297 // Speed over the whole way as mapped, even when the extract holds only a part of it.298 var length = 0.0299 var complete = true300 for k in 1..<w.refCount {301 let a = Int(refIndex[w.firstRef + k - 1]), b = Int(refIndex[w.firstRef + k])302 guard lat[a] != Int32.min, lat[b] != Int32.min else { complete = false; break }303 length += Geodesy.distance(Coordinate(latE7: lat[a], lonE7: lon[a]), Coordinate(latE7: lat[b], lonE7: lon[b]))304 }305 let kmh = length / duration * 3.6306 if complete, kmh >= 2, kmh <= 80 { attributes.speedKmh = kmh; count("ferryWaysWithDuration") }307 else { count("ferryDurationsRejected") }308 }309 }310 if attributes.speedKmh != nil, w.attributes.roadClass != .ferry { count("waysWithMaxspeed") }311312 // Walk the way, cutting at graph nodes and at unusable nodes.313 run.removeAll(keepingCapacity: true)314 func flush(_ writer: inout RoutingGraphWriter) throws {315 defer { run.removeAll(keepingCapacity: true) }316 guard run.count >= 2 else { return }317 var segmentStart = 0318 for k in 1..<run.count where isGraphNode[run[k]] {319 try emit(Array(run[segmentStart...k]), &writer)320 segmentStart = k321 }322 }323 func emit(_ nodes: [Int], _ writer: inout RoutingGraphWriter) throws {324 guard nodes.count >= 2 else { return }325 if nodes.first == nodes.last {326 // A loop back to the same junction: cut it in two so that no edge starts and ends at one node.327 guard nodes.count >= 4 else { count("degenerateLoopsDropped"); return }328 let middle = nodes.count / 2329 try emit(Array(nodes[0...middle]), &writer)330 try emit(Array(nodes[middle...]), &writer)331 return332 }333 shapeLat.removeAll(keepingCapacity: true); shapeLon.removeAll(keepingCapacity: true)334 var edgeAttributes = attributes335 for i in nodes[1..<(nodes.count - 1)] where nodeFlags[i] & signalBit != 0 { edgeAttributes.flags.insert(.trafficSignal) }336 if tolerance > 0, nodes.count > 2 {337 let line = Geodesy.simplify(nodes.map { Coordinate(latE7: lat[$0], lonE7: lon[$0]) }, toleranceMeters: tolerance)338 count("shapePointsDropped", nodes.count - line.count)339 for c in line[1..<(line.count - 1)] { let e7 = c.e7; shapeLat.append(e7.lat); shapeLon.append(e7.lon) }340 } else {341 for i in nodes[1..<(nodes.count - 1)] { shapeLat.append(lat[i]); shapeLon.append(lon[i]) }342 }343 count("shapePoints", shapeLat.count)344 let a = try node(nodes[0], &writer), b = try node(nodes[nodes.count - 1], &writer)345 let edge = try writer.addEdge(from: a, to: b, shapeLatE7: shapeLat, shapeLonE7: shapeLon, attributes: edgeAttributes)346 if viaNodeIndex[nodes[0]] != nil { viaNodeIndex[nodes[0]]!.append((w.id, edge)) }347 if viaNodeIndex[nodes[nodes.count - 1]] != nil { viaNodeIndex[nodes[nodes.count - 1]]!.append((w.id, edge)) }348 }349 for k in 0..<w.refCount {350 let i = Int(refIndex[w.firstRef + k])351 if usable[i] {352 if let last = run.last, last == i { continue } // repeated node353 run.append(i)354 } else {355 try flush(&writer)356 }357 }358 try flush(&writer)359 }360 guard writer.edgeCount > 0 else { throw GraphExtractorError.noRoutableWay }361362 // Turn restrictions.363 for r in restrictions {364 let i = lowerBound(r.viaNode)365 guard i < usedCount, unique[i] == r.viaNode, let incident = viaNodeIndex[i], graphNode[i] != none else {366 count("restrictionsOutsideGraph"); continue367 }368 var added = false, ambiguous = false369 for fromWay in r.fromWays {370 let fromEdges = incident.filter { $0.way == fromWay }371 for toWay in r.toWays {372 let toEdges = incident.filter { $0.way == toWay }373 guard !fromEdges.isEmpty, !toEdges.isEmpty else { continue }374 // The way must end at the via node: with two edges of the same way there, the member is ambiguous.375 guard fromEdges.count == 1, toEdges.count == 1 else { ambiguous = true; continue }376 try writer.addRestriction(from: fromEdges[0].edge, via: graphNode[i], to: toEdges[0].edge, kind: r.kind, modes: r.modes)377 added = true378 count("restrictionRecords")379 }380 }381 if added { count("restrictionsApplied") } else if ambiguous { count("restrictionsAmbiguousSkipped") } else { count("restrictionsOutsideGraph") }382 }383 let secondsGraph = Date().timeIntervalSince(t0)384 log("graph: \(writer.nodeCount) nodes, \(writer.edgeCount) edges (\(String(format: "%.1f", secondsGraph)) s)")385386 // Release what the writer no longer needs, then serialize.387 unique = []; refIndex = []; lat = []; lon = []; nodeFlags = []; usable = []; uses = []; isGraphNode = []; graphNode = []388 ways = []389 t0 = Date()390 var options = RoutingGraphWriter.Options(regionID: configuration.regionID, osmTimestamp: osmTimestamp, buildDate: configuration.buildDate,391 boundingBox: configuration.boundingBox ?? header.bbox.flatMap { b in392 let box = BoundingBox(minLat: b.minLat, minLon: b.minLon, maxLat: b.maxLat, maxLon: b.maxLon)393 return box.isValid && !box.crossesAntimeridian ? box : nil394 },395 reorderSpatially: true, generator: "orix-routing-build")396 options.buildCounters = counters397 writer.options = options398 let (data, summary) = try writer.build()399 let secondsWrite = Date().timeIntervalSince(t0)400 log("serialized: \(summary.fileBytes) bytes, \(String(format: "%.1f", summary.bytesPerEdge)) bytes per edge (\(String(format: "%.1f", secondsWrite)) s)")401 return (data, Report(counters: counters, summary: summary, secondsPass1: secondsPass1, secondsPass2: secondsPass2,402 secondsGraph: secondsGraph, secondsWrite: secondsWrite, osmTimestamp: osmTimestamp))403 }404}405