SPB Git

Repository Public BSD-3-Clause

ExtractorTests.swift 9.6 KB 190 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Infrastructure/routing-builder/Tests/ORIXRoutingBuildKitTests/ExtractorTests.swift10// Module           : ORIXRoutingBuildKitTests11// 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 ORIXRouting92import Testing93@testable import ORIXRoutingBuildKit9495/// The Monaco extract shipped as a fixture of the ORIXOSM package (read in place, never modified).96private let monacoURL = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()97    .deletingLastPathComponent().appendingPathComponent("ingestion/ORIXOSM/Tests/ORIXOSMTests/Fixtures/monaco.osm.pbf")98private let monacoAvailable = FileManager.default.fileExists(atPath: monacoURL.path)99100@Suite(.enabled(if: monacoAvailable, "the Monaco fixture of ORIXOSM is missing"))101struct ExtractorTests {102    static let casino = Coordinate(latitude: 43.7396, longitude: 7.4276)103    static let palace = Coordinate(latitude: 43.7314, longitude: 7.4203)104    static let buildDate = Date(timeIntervalSince1970: 1_800_000_000)105106    static func build(box: BoundingBox? = nil, simplify: Double = 0.5) throws -> (Data, GraphExtractor.Report) {107        let extractor = GraphExtractor(configuration: .init(regionID: "mc", boundingBox: box, buildDate: buildDate, simplifyToleranceMeters: simplify))108        return try extractor.buildData(reader: OSMPBFReader(url: monacoURL))109    }110111    @Test func buildsAValidGraphFromARealExtract() throws {112        let (data, report) = try Self.build()113        let graph = try RoutingGraph(data: data)   // full validation114        #expect(graph.metadata.regionID == "mc")115        #expect(graph.metadata.buildDate == Self.buildDate)116        #expect(graph.metadata.attribution.contains("OpenStreetMap"))117        #expect(graph.metadata.generator == "orix-routing-build")118        #expect(graph.nodeCount > 1000 && graph.edgeCount > 1000)119        #expect(report.summary.edgeCount == graph.edgeCount && report.summary.fileBytes == data.count)120        #expect(report.counters["routableWays"] ?? 0 > 500)121        #expect(graph.metadata.buildCounters["routableWays"] == report.counters["routableWays"])122        #expect(graph.metadata.boundingBox.contains(Self.casino))123        // Intersections only: far fewer graph nodes than nodes on routable ways.124        #expect(graph.nodeCount < (report.counters["nodesOnRoutableWays"] ?? 0))125        // Every restriction relation is accounted for: applied or counted under a reason.126        let relations = report.counters["restrictionRelations"] ?? 0127        let applied = report.counters["restrictionsApplied"] ?? 0128        let skipped = (report.counters["restrictionsOutsideGraph"] ?? 0) + (report.counters["restrictionsAmbiguousSkipped"] ?? 0)129        #expect(relations == applied + skipped)130        #expect(graph.restrictionCount == report.counters["restrictionRecords"] ?? 0)131        // No edge starts and ends at the same node, and every edge is usable by somebody.132        for e in 0..<UInt32(graph.edgeCount) {133            let edge = try #require(graph.edge(at: e))134            #expect(edge.nodeA != edge.nodeB)135            #expect(!edge.access.isEmpty)136            #expect(edge.lengthMeters + 0.11 >= Geodesy.distance(graph.coordinate(ofNode: edge.nodeA)!, graph.coordinate(ofNode: edge.nodeB)!))137        }138    }139140    @Test func routesInMonaco() throws {141        let graph = try RoutingGraph(data: Self.build().0)142        let router = Router(graph: graph)143        var distances: [TravelMode: Double] = [:]144        for mode in TravelMode.allCases {145            let request = RouteRequest(from: Self.casino, to: Self.palace, profile: .standard(for: mode))146            let response = try router.compute(request)147            let route = response.route148            distances[mode] = route.distanceMeters149            // The two landmarks are 1.1 km apart as the crow flies; streets wind around the harbour and the rock.150            #expect(route.distanceMeters > 1000 && route.distanceMeters < 6000, "\(mode): \(route.distanceMeters) m")151            #expect(route.durationSeconds > 60)152            #expect(abs(Geodesy.length(of: route.geometry) - route.distanceMeters) < 5 + route.distanceMeters * 0.002)153            #expect(route.maneuvers.first?.type == .depart && route.maneuvers.last?.type == .arrive)154            #expect(route.maneuvers.count >= 3)155            var reference = request156            reference.algorithm = .dijkstra157            #expect(try router.compute(reference).route.cost == route.cost)158            let formatter = InstructionFormatter(language: .french)159            #expect(route.maneuvers.allSatisfy { !formatter.instruction(for: $0).isEmpty })160        }161        // Pedestrians take stairs and footpaths: never longer than the car route here.162        #expect(distances[.pedestrian]! <= distances[.car]! + 1)163    }164165    @Test func buildsAreDeterministicAndSimplificationOnlyDropsShapePoints() throws {166        let a = try Self.build().0, b = try Self.build().0167        #expect(a == b)168        let (full, fullReport) = try Self.build(simplify: 0)169        let (simple, simpleReport) = try Self.build(simplify: 2)170        #expect(simple.count < full.count)171        #expect(fullReport.summary.edgeCount == simpleReport.summary.edgeCount && fullReport.summary.nodeCount == simpleReport.summary.nodeCount)172        #expect(fullReport.counters["shapePointsDropped"] == nil && (simpleReport.counters["shapePointsDropped"] ?? 0) > 0)173    }174175    @Test func boundingBoxClipsTheGraph() throws {176        let whole = try RoutingGraph(data: Self.build().0)177        let box = BoundingBox(minLat: 43.735, minLon: 7.415, maxLat: 43.745, maxLon: 7.435)178        let clipped = try RoutingGraph(data: Self.build(box: box).0)179        #expect(clipped.edgeCount > 100 && clipped.edgeCount < whole.edgeCount)180        #expect(clipped.metadata.boundingBox == box)181        for n in 0..<UInt32(clipped.nodeCount) { #expect(box.contains(clipped.coordinate(ofNode: n)!)) }182        #expect(throws: RoutingError.pointOutsideCoverage(waypointIndex: 1)) {183            try Router(graph: clipped).compute(RouteRequest(from: Self.casino, to: Coordinate(latitude: 43.70, longitude: 7.40)))184        }185        #expect(throws: GraphExtractorError.self) {186            try Self.build(box: BoundingBox(minLat: 10, minLon: 10, maxLat: 11, maxLon: 11))187        }188    }189}190
Files main
Menu

Theme