SPB Git

Repository Public BSD-3-Clause

TestSupport.swift 9.9 KB 205 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/TestSupport.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/// Synthetic graphs laid out in metres around a point in Montréal, built through the public writer API.94struct TestGraph {95    static let origin = Coordinate(latitude: 45.5, longitude: -73.6)9697    var writer = RoutingGraphWriter(options: .init(regionID: "test", buildDate: Date(timeIntervalSince1970: 1_800_000_000)))98    var nodes: [String: UInt32] = [:]99    var edges: [String: UInt32] = [:]100    /// Restrictions as added, for independent path validation: (from edge, via node, to edge, kind, modes).101    var restrictions: [(UInt32, UInt32, UInt32, RestrictionKind, Set<TravelMode>)] = []102103    /// A point `x` metres east and `y` metres north of the origin.104    static func point(_ x: Double, _ y: Double) -> Coordinate {105        Coordinate(latitude: origin.latitude + y / Geodesy.metersPerDegreeLatitude,106                   longitude: origin.longitude + x / (Geodesy.metersPerDegreeLatitude * cos(origin.latitude * .pi / 180)))107    }108109    @discardableResult110    mutating func node(_ name: String, _ x: Double, _ y: Double, flags: NodeFlags = []) -> UInt32 {111        let index = try! writer.addNode(TestGraph.point(x, y), flags: flags)112        nodes[name] = index113        return index114    }115116    /// Adds an edge named "a-b" between two named nodes.117    @discardableResult118    mutating func edge(_ a: String, _ b: String, _ attributes: RoutingGraphWriter.EdgeAttributes = .init(), shape: [(Double, Double)] = []) -> UInt32 {119        let index = try! writer.addEdge(from: nodes[a]!, to: nodes[b]!, shape: shape.map { TestGraph.point($0.0, $0.1) }, attributes: attributes)120        edges["\(a)-\(b)"] = index121        return index122    }123124    mutating func restrict(from: String, via: String, to: String, _ kind: RestrictionKind, modes: Set<TravelMode> = [.car, .bicycle]) {125        try! writer.addRestriction(from: edges[from]!, via: nodes[via]!, to: edges[to]!, kind: kind, modes: modes)126        restrictions.append((edges[from]!, nodes[via]!, edges[to]!, kind, modes))127    }128129    func data() -> Data { try! writer.build().data }130    func graph() -> RoutingGraph { try! RoutingGraph(data: data()) }131    func router() -> Router { Router(graph: graph()) }132}133134extension RoutingGraphWriter.EdgeAttributes {135    static func road(_ name: String? = nil, _ roadClass: RoadClass = .residential, access: EdgeAccess = .all, speed: Double? = nil,136                     flags: EdgeFlags = [], surface: SurfaceClass = .paved, ref: String? = nil, wayID: Int64 = 0) -> Self {137        .init(roadClass: roadClass, access: access, surface: surface, flags: flags, speedKmh: speed, name: name, ref: ref, wayID: wayID)138    }139140    /// Open to every mode in the A → B direction only for cars and bicycles (pedestrians walk both ways).141    static func oneWay(_ name: String? = nil, _ roadClass: RoadClass = .residential, flags: EdgeFlags = []) -> Self {142        .init(roadClass: roadClass, access: [.carForward, .bicycleForward, .pedestrianForward, .pedestrianBackward], flags: flags, name: name)143    }144145    static let carOnly: EdgeAccess = [.carForward, .carBackward]146    static let footOnly: EdgeAccess = [.pedestrianForward, .pedestrianBackward]147}148149func request(_ points: [Coordinate], _ profile: RoutingProfile = .car, alternatives: Int = 0) -> RouteRequest {150    var r = RouteRequest(waypoints: points.map { RouteWaypoint($0) }, profile: profile, alternatives: alternatives)151    r.maxSnapDistanceMeters = 200152    return r153}154155func p(_ x: Double, _ y: Double) -> Coordinate { TestGraph.point(x, y) }156157/// Deterministic generator (SplitMix64) so that randomized tests are reproducible.158struct SeededGenerator: RandomNumberGenerator {159    var state: UInt64160    init(seed: UInt64) { state = seed }161    mutating func next() -> UInt64 {162        state &+= 0x9E37_79B9_7F4A_7C15163        var z = state164        z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9165        z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB166        return z ^ (z >> 31)167    }168}169170/// Runs the internal search and returns the directed edges of the path, for independent validation.171func searchPath(_ graph: RoutingGraph, from a: Coordinate, to b: Coordinate, profile: RoutingProfile, heuristic: Bool = true) throws -> EdgeSearch.Outcome? {172    let compiled = CompiledProfile(profile, graph: graph.metadata)173    let options = SnapOptions(maxDistanceMeters: 200)174    let s = try graph.snap(a, mode: profile.mode, options: options, waypointIndex: 0)175    let t = try graph.snap(b, mode: profile.mode, options: options, waypointIndex: 1)176    return try EdgeSearch(graph: graph, profile: compiled).run(source: s, sourceDirections: [true, true], target: t, useHeuristic: heuristic)177}178179/// Checks a path against the graph with code that shares nothing with the search: continuity, direction-specific180/// access, barriers and turn restrictions. Returns a description of the first violation.181func violation(in path: [UInt32], graph: RoutingGraph, mode: TravelMode,182               restrictions: [(UInt32, UInt32, UInt32, RestrictionKind, Set<TravelMode>)]) -> String? {183    for (i, d) in path.enumerated() {184        guard let e = graph.edge(at: d >> 1) else { return "edge \(d >> 1) does not exist" }185        let allowed = d & 1 == 0 ? e.access.contains(.forward(mode)) : e.access.contains(.backward(mode))186        if !allowed { return "edge \(e.index) is not open to \(mode) in direction \(d & 1)" }187        guard i > 0 else { continue }188        let previous = graph.edge(at: path[i - 1] >> 1)!189        let via = path[i - 1] & 1 == 0 ? previous.nodeB : previous.nodeA190        let tail = d & 1 == 0 ? e.nodeA : e.nodeB191        if via != tail { return "edges \(previous.index) and \(e.index) do not meet" }192        if graph.flags(ofNode: via)!.contains(.blocks(mode)) { return "path goes through barrier node \(via)" }193        let applicable = restrictions.filter { $0.0 == previous.index && $0.1 == via && $0.4.contains(mode) }194        if applicable.contains(where: { $0.3 == .prohibitive && $0.2 == e.index }) { return "forbidden turn at node \(via)" }195        let mandatory = applicable.filter { $0.3 == .mandatory }196        if !mandatory.isEmpty, !mandatory.contains(where: { $0.2 == e.index }) { return "mandatory turn ignored at node \(via)" }197    }198    return nil199}200201/// Captures the typed result of a route computation.202func outcome(_ router: Router, _ request: RouteRequest) async -> Result<RouteResponse, RoutingError> {203    do throws(RoutingError) { return .success(try await router.route(request)) } catch { return .failure(error) }204}205
Files main
Menu

Theme