SPB Git

Repository Public BSD-3-Clause

RealDataTests.swift 15.1 KB 269 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXRouting/Tests/ORIXRoutingTests/RealDataTests.swift10// Module           : ORIXRoutingTests11// 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 Testing91@testable import ORIXRouting9293/// Opt-in checks on real graphs built by `orix-routing-build` (not in the repository):94///95///     ORIX_ROUTING_DATA_DIR=/path/to/data/build/routing swift test --filter RealDataTests96///97/// The directory must contain `montreal.orixgraph` and `quebec.orixgraph`.98private let dataDirectory = ProcessInfo.processInfo.environment["ORIX_ROUTING_DATA_DIR"]99private func graphURL(_ name: String) -> URL { URL(fileURLWithPath: dataDirectory ?? "/nonexistent").appendingPathComponent(name) }100private let realDataAvailable = FileManager.default.fileExists(atPath: graphURL("montreal.orixgraph").path)101    && FileManager.default.fileExists(atPath: graphURL("quebec.orixgraph").path)102103@Suite(.enabled(if: realDataAvailable, "set ORIX_ROUTING_DATA_DIR to a directory holding montreal.orixgraph and quebec.orixgraph"), .serialized)104struct RealDataTests {105    static let mcgill = Coordinate(latitude: 45.5048, longitude: -73.5772)106    static let longueuil = Coordinate(latitude: 45.5250, longitude: -73.5220)107    static let quebec = Coordinate(latitude: 46.8087, longitude: -71.2140)108    static let levis = Coordinate(latitude: 46.8030, longitude: -71.1780)109    static let gatineau = Coordinate(latitude: 45.4280, longitude: -75.7130)110    static let gaspe = Coordinate(latitude: 48.8310, longitude: -64.4830)111    static let stade = Coordinate(latitude: 45.5579, longitude: -73.5515)112    static let yul = Coordinate(latitude: 45.4577, longitude: -73.7497)113114    /// Path of directed edges for one origin–destination pair.115    static func path(_ graph: RoutingGraph, _ a: Coordinate, _ b: Coordinate, _ profile: RoutingProfile) throws -> [UInt32] {116        let compiled = CompiledProfile(profile, graph: graph.metadata)117        let s = try graph.snap(a, mode: profile.mode, options: SnapOptions(), waypointIndex: 0)118        let t = try graph.snap(b, mode: profile.mode, options: SnapOptions(), waypointIndex: 1)119        return try #require(try EdgeSearch(graph: graph, profile: compiled).run(source: s, sourceDirections: [true, true], target: t, useHeuristic: true)).path120    }121122    @Test func montrealToQuebecCityByCar() throws {123        let graph = try RoutingGraph(url: graphURL("quebec.orixgraph"))124        let route = try Router(graph: graph).compute(RouteRequest(from: Self.mcgill, to: Self.quebec)).route125        // Known: about 250–260 km by A-20 or A-40, about 2 h 45.126        #expect(route.distanceMeters > 245_000 && route.distanceMeters < 265_000, "\(route.distanceMeters) m")127        #expect(route.durationSeconds > 2.4 * 3600 && route.durationSeconds < 3.1 * 3600, "\(route.durationSeconds) s")128        let motorway = route.segments.filter { $0.roadClass == .motorway }.map(\.distanceMeters).reduce(0, +)129        #expect(motorway / route.distanceMeters > 0.85)130        let refs = Set(route.segments.compactMap(\.ref).flatMap { $0.split(separator: ";").map(String.init) })131        #expect(refs.contains("20") || refs.contains("40"))132        #expect(graph.metadata.osmTimestamp != nil)133    }134135    @Test func pedestriansAreNeverOnMotorways() throws {136        let graph = try RoutingGraph(url: graphURL("montreal.orixgraph"))137        // No carriageway of an autoroute is open to pedestrians. Ramps (`motorway_link`) can be, but only through an138        // explicit `foot=yes` tag in OpenStreetMap (15 short ramp edges in the November 2026 Montréal extract).139        var carriageways = 0, openCarriageways = 0, openRamps = 0140        for e in 0..<UInt32(graph.edgeCount) {141            let r = graph.edge(e)142            guard r.roadClass == RoadClass.motorway.rawValue else { continue }143            let open = r.access & EdgeAccess.both(.pedestrian).rawValue != 0144            if r.flags & EdgeFlags.link.rawValue != 0 {145                if open { openRamps += 1 }146            } else {147                carriageways += 1148                if open { openCarriageways += 1 }149            }150        }151        #expect(carriageways > 1000)152        #expect(openCarriageways == 0, "\(openCarriageways) of \(carriageways) motorway carriageway edges are open to pedestrians")153        #expect(openRamps < 50, "\(openRamps) ramp edges are open to pedestrians")154        // And in routes, including one whose straight line follows an autoroute.155        let router = Router(graph: graph)156        for (a, b) in [(Self.mcgill, Self.stade), (Self.mcgill, Self.longueuil), (Self.yul, Self.mcgill)] {157            let route = try router.compute(RouteRequest(from: a, to: b, profile: .pedestrian)).route158            #expect(!route.segments.contains { $0.roadClass == .motorway })159            #expect(route.distanceMeters >= Geodesy.distance(a, b) * 0.98)160            // About 5 km/h.161            #expect(route.distanceMeters / route.durationSeconds * 3.6 > 4 && route.distanceMeters / route.durationSeconds * 3.6 <= 5.01)162        }163    }164165    /// Boulevard Saint-Laurent is one-way northbound through the Plateau.166    @Test func plateauOneWayStreetsAreRespected() throws {167        let graph = try RoutingGraph(url: graphURL("montreal.orixgraph"))168        let box = BoundingBox(minLat: 45.5135, minLon: -73.5900, maxLat: 45.5230, maxLon: -73.5700)169        var edges: [GraphEdge] = []170        for e in 0..<UInt32(graph.edgeCount) {171            let r = graph.edge(e)172            guard r.roadClass <= RoadClass.tertiary.rawValue, r.access & EdgeAccess.both(.car).rawValue != 0 else { continue }173            let c = graph.nodeE7(r.nodeA)174            guard box.contains(Coordinate(latE7: c.lat, lonE7: c.lon)), let edge = graph.edge(at: e), edge.name == "Boulevard Saint-Laurent" else { continue }175            edges.append(edge)176        }177        #expect(edges.count >= 5, "found \(edges.count) edges of Boulevard Saint-Laurent in the Plateau")178        for edge in edges {179            let forward = edge.access.contains(.carForward), backward = edge.access.contains(.carBackward)180            #expect(forward != backward, "edge \(edge.index) is not one-way for cars")181            let bearing = forward ? edge.bearingAtA : (edge.bearingAtA + 180).truncatingRemainder(dividingBy: 360)182            // The street runs north-west on the map ("north" in Montréal usage).183            #expect(bearing > 290 || bearing < 20, "edge \(edge.index) allows travel towards \(bearing)°")184        }185        // Southernmost and northernmost points of the stretch.186        let midpoints = edges.map { e -> Coordinate in187            let g = graph.geometry(ofEdge: e.index)188            return Geodesy.interpolate(g[0], g[g.count - 1], t: 0.5)189        }.sorted { $0.latitude < $1.latitude }190        let south = midpoints.first!, north = midpoints.last!191        let router = Router(graph: graph)192        let up = try router.compute(RouteRequest(from: south, to: north)).route193        let down = try router.compute(RouteRequest(from: north, to: south)).route194        func share(_ r: Route) -> Double {195            r.segments.filter { $0.name == "Boulevard Saint-Laurent" }.map(\.distanceMeters).reduce(0, +) / r.distanceMeters196        }197        #expect(share(up) > 0.9, "northbound share \(share(up))")198        #expect(share(down) < 0.35, "southbound share \(share(down))")199        #expect(down.distanceMeters > up.distanceMeters * 1.1)200        // Independent check of every edge direction on several car routes.201        for (a, b) in [(north, south), (south, north), (Self.mcgill, Self.stade), (Self.stade, Self.mcgill), (Self.mcgill, Self.longueuil)] {202            let path = try Self.path(graph, a, b, .car)203            #expect(violation(in: path, graph: graph, mode: .car, restrictions: []) == nil)204        }205    }206207    /// A route across the St. Lawrence uses a real crossing.208    @Test func riverCrossingsUseBridgesTunnelsOrFerries() throws {209        let crossings = ["Pont Jacques-Cartier", "Pont Victoria", "Pont Samuel-De Champlain", "Pont Champlain", "Pont-tunnel Louis-Hippolyte-La Fontaine",210                         "Tunnel Louis-Hippolyte-La Fontaine", "Pont de la Concorde", "Pont Pierre-Laporte", "Pont de Québec"]211        let montreal = try RoutingGraph(url: graphURL("montreal.orixgraph"))212        let quebec = try RoutingGraph(url: graphURL("quebec.orixgraph"))213        let cases: [(RoutingGraph, Coordinate, Coordinate, RoutingProfile)] = [214            (montreal, Self.mcgill, Self.longueuil, .car), (montreal, Self.longueuil, Self.mcgill, .car),215            (montreal, Self.mcgill, Self.longueuil, .bicycle), (montreal, Self.mcgill, Self.longueuil, .pedestrian),216            (quebec, Self.quebec, Self.levis, .car), (quebec, Self.levis, Self.quebec, .car),217            (quebec, Self.quebec, Self.levis, .pedestrian),218        ]219        for (graph, a, b, profile) in cases {220            let route = try Router(graph: graph).compute(RouteRequest(from: a, to: b, profile: profile)).route221            let crossing = route.segments.filter { $0.isBridge || $0.isTunnel || $0.isFerry }222            let length = crossing.map(\.distanceMeters).reduce(0, +)223            // The river is at least 800 m wide at these places.224            #expect(length > 800, "\(profile.name): only \(length) m on bridges, tunnels or ferries")225            // One uninterrupted structure of at least 500 m: overpasses are far shorter, only a river crossing is that long.226            var longest = 0.0, run = 0.0227            for s in route.segments {228                run = s.isBridge || s.isTunnel || s.isFerry ? run + s.distanceMeters : 0229                longest = max(longest, run)230            }231            #expect(longest > 500, "\(profile.name): longest structure \(longest) m")232            if graph === montreal {233                // Around Montréal the crossings carry their name on the road itself.234                let named = crossing.contains { s in crossings.contains { s.name?.contains($0) == true } } || crossing.contains { $0.isFerry }235                #expect(named, "\(profile.name): crossing by \(Set(crossing.compactMap(\.name)))")236            }237            if crossing.contains(where: \.isFerry) { #expect(route.warnings.contains { $0.kind == .ferry }) }238        }239    }240241    @Test func longRoutesMatchDijkstra() throws {242        let graph = try RoutingGraph(url: graphURL("quebec.orixgraph"))243        let router = Router(graph: graph)244        for (a, b) in [(Self.gaspe, Self.gatineau), (Self.mcgill, Self.quebec), (Self.quebec, Self.levis)] {245            var request = RouteRequest(from: a, to: b)246            let fast = try router.compute(request)247            request.algorithm = .dijkstra248            let reference = try router.compute(request)249            #expect(fast.route.cost == reference.route.cost)250            #expect(fast.statistics.settledStates <= reference.statistics.settledStates)251        }252        // Gaspé → Gatineau: about 1 100 km through Québec City and Montréal.253        let long = try router.compute(RouteRequest(from: Self.gaspe, to: Self.gatineau)).route254        #expect(long.distanceMeters > 1_000_000 && long.distanceMeters < 1_250_000)255    }256257    @Test func separateNetworksAnswerImmediately() throws {258        let graph = try RoutingGraph(url: graphURL("quebec.orixgraph"))259        let islands = Coordinate(latitude: 47.3790, longitude: -61.8600)   // Cap-aux-Meules, Îles-de-la-Madeleine260        // The ferry to the islands leaves from Prince Edward Island, outside the province extract.261        #expect(throws: RoutingError.noConnection(fromWaypointIndex: 0, toWaypointIndex: 1, differentComponents: true)) {262            try Router(graph: graph).compute(RouteRequest(from: Self.mcgill, to: islands))263        }264        #expect(throws: RoutingError.pointOutsideCoverage(waypointIndex: 1)) {265            try Router(graph: graph).compute(RouteRequest(from: Self.mcgill, to: Coordinate(latitude: 43.65, longitude: -79.38)))   // Toronto266        }267    }268}269
Files main
Menu

Theme