SPB Git

Repository Public BSD-3-Clause

EquivalenceTests.swift 17.5 KB 306 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/EquivalenceTests.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/// A* against Dijkstra against an independent label-correcting reference, on random graphs and random profiles.94@Suite struct EquivalenceTests {95    struct RandomGraph {96        var graph: TestGraph97        var extent: Double98    }99100    static func randomGraph(seed: UInt64, nodeCount: Int, extent: Double) -> RandomGraph {101        var rng = SeededGenerator(seed: seed)102        var g = TestGraph()103        var positions: [(Double, Double)] = []104        for i in 0..<nodeCount {105            let x = Double.random(in: 0...extent, using: &rng), y = Double.random(in: 0...extent, using: &rng)106            positions.append((x, y))107            var flags: NodeFlags = []108            let roll = Int.random(in: 0..<100, using: &rng)109            if roll < 4 { flags.insert(.blocksCar) } else if roll < 6 { flags.insert(.blocksBicycle) } else if roll < 7 { flags.insert(.blocksPedestrian) }110            if Int.random(in: 0..<10, using: &rng) == 0 { flags.insert(.trafficSignal) }111            g.node("\(i)", x, y, flags: flags)112        }113        let classes: [RoadClass] = [.motorway, .trunk, .primary, .secondary, .tertiary, .residential, .residential, .service, .track, .footway, .path, .cycleway, .steps, .ferry]114        var pairs = Set<String>()115        var incident: [[String]] = Array(repeating: [], count: nodeCount)116        for i in 0..<nodeCount {117            let nearest = (0..<nodeCount).filter { $0 != i }.sorted {118                hypot(positions[$0].0 - positions[i].0, positions[$0].1 - positions[i].1) < hypot(positions[$1].0 - positions[i].0, positions[$1].1 - positions[i].1)119            }120            // A chain through all nodes keeps most of the graph in one piece.121            for j in Array(nearest.prefix(Int.random(in: 2...3, using: &rng))) + (i + 1 < nodeCount ? [i + 1] : []) {122                let key = "\(min(i, j))-\(max(i, j))"123                // Sometimes a parallel edge between the same nodes.124                if pairs.contains(key), Int.random(in: 0..<8, using: &rng) != 0 { continue }125                let name = pairs.contains(key) ? "\(i)-\(j)#2" : "\(i)-\(j)"126                pairs.insert(key)127                let roadClass = classes.randomElement(using: &rng)!128                var access = EdgeAccess.all129                switch Int.random(in: 0..<20, using: &rng) {130                case 0..<4: access = [.carForward, .bicycleForward, .pedestrianForward, .pedestrianBackward]131                case 4: access = [.carBackward, .bicycleBackward, .bicycleForward, .pedestrianForward, .pedestrianBackward]132                case 5: access = RoutingGraphWriter.EdgeAttributes.carOnly133                case 6: access = RoutingGraphWriter.EdgeAttributes.footOnly134                case 7: access = [.bicycleForward, .bicycleBackward, .pedestrianForward, .pedestrianBackward]135                default: break136                }137                var flags: EdgeFlags = []138                if Int.random(in: 0..<10, using: &rng) == 0 { flags.insert(.toll) }139                if Int.random(in: 0..<10, using: &rng) == 0 { flags.insert(.trafficSignal) }140                if Int.random(in: 0..<10, using: &rng) == 0 { flags.insert(.link) }141                if Int.random(in: 0..<12, using: &rng) == 0 { flags.insert(.restrictedCar) }142                if Int.random(in: 0..<12, using: &rng) == 0 { flags.insert(.restrictedPedestrian) }143                if Int.random(in: 0..<12, using: &rng) == 0 { flags.insert(.restrictedBicycle) }144                if Int.random(in: 0..<10, using: &rng) == 0 { flags.insert(.cycleLane) }145                if Int.random(in: 0..<15, using: &rng) == 0 { flags.insert(.minorService) }146                let speed: Double? = Bool.random(using: &rng) ? Double([20, 30, 40, 50, 70, 90, 100].randomElement(using: &rng)!) : nil147                let surface = SurfaceClass(rawValue: UInt8.random(in: 0...2, using: &rng))!148                var shape: [(Double, Double)] = []149                if Int.random(in: 0..<3, using: &rng) == 0 {150                    let mx = (positions[i].0 + positions[j].0) / 2 + Double.random(in: -60...60, using: &rng)151                    let my = (positions[i].1 + positions[j].1) / 2 + Double.random(in: -60...60, using: &rng)152                    shape = [(mx, my)]153                }154                let attributes = RoutingGraphWriter.EdgeAttributes(roadClass: roadClass, access: access, surface: surface, flags: flags,155                                                                   speedKmh: roadClass == .ferry ? (speed.map { $0 / 4 }) : speed, name: name)156                let index = try! g.writer.addEdge(from: UInt32(i), to: UInt32(j), shape: shape.map { TestGraph.point($0.0, $0.1) }, attributes: attributes)157                g.edges[name] = index158                incident[i].append(name); incident[j].append(name)159            }160        }161        // Random turn restrictions.162        for _ in 0..<(nodeCount / 2) {163            let via = Int.random(in: 0..<nodeCount, using: &rng)164            guard incident[via].count >= 2 else { continue }165            let from = incident[via].randomElement(using: &rng)!, to = incident[via].randomElement(using: &rng)!166            let kind: RestrictionKind = Int.random(in: 0..<3, using: &rng) == 0 ? .mandatory : .prohibitive167            let modes: Set<TravelMode> = Bool.random(using: &rng) ? [.car, .bicycle] : [.car]168            try! g.writer.addRestriction(from: g.edges[from]!, via: UInt32(via), to: g.edges[to]!, kind: kind, modes: modes)169            g.restrictions.append((g.edges[from]!, UInt32(via), g.edges[to]!, kind, modes))170        }171        return RandomGraph(graph: g, extent: extent)172    }173174    static func randomProfile(_ rng: inout SeededGenerator) -> RoutingProfile {175        var p = RoutingProfile.standard(for: TravelMode.allCases.randomElement(using: &rng)!)176        p.avoid = RouteAvoidance(tolls: Int.random(in: 0..<5, using: &rng) == 0, ferries: Int.random(in: 0..<5, using: &rng) == 0,177                                 motorways: Int.random(in: 0..<5, using: &rng) == 0, unpaved: Int.random(in: 0..<5, using: &rng) == 0)178        p.leftTurnSeconds = Double.random(in: 0...20, using: &rng)179        p.rightTurnSeconds = Double.random(in: 0...10, using: &rng)180        p.uTurnSeconds = Double.random(in: 0...40, using: &rng)181        p.trafficSignalSeconds = Double.random(in: 0...15, using: &rng)182        p.allowsUTurnAtJunctions = Bool.random(using: &rng)183        p.allowsUTurnMidBlock = Bool.random(using: &rng)184        p.restrictedAccessPenaltySeconds = Double.random(in: 0...400, using: &rng)185        p.ferryBoardingSeconds = Double.random(in: 0...300, using: &rng)186        p.cycleLanePreference = Double.random(in: 0.5...1, using: &rng)187        p.unpavedSpeedFactor = Double.random(in: 0.3...1, using: &rng)188        p.unpavedPreference = Double.random(in: 1...2, using: &rng)189        return p190    }191192    /// Label-correcting reference (Bellman–Ford style over directed-edge states): no queue, no heuristic, no early exit.193    static func referenceCost(_ graph: RoutingGraph, _ profile: CompiledProfile, _ source: SnapCandidate, _ target: SnapCandidate) -> UInt64? {194        let search = EdgeSearch(graph: graph, profile: profile)195        let shift = profile.accessShift196        var cost = [UInt64](repeating: .max, count: graph.edgeCount * 2)197        var best = UInt64.max198        let sBase = profile.baseCost(source.record), tBase = profile.baseCost(target.record)199        for dir in 0..<2 where (source.record.access >> (shift + UInt8(dir))) & 1 == 1 {200            if source.edge == target.edge {201                let along = dir == 0 ? target.fraction - source.fraction : source.fraction - target.fraction202                if along >= 0 { best = min(best, EdgeSearch.ceilMs(sBase * along)) }203            }204            cost[Int(source.edge << 1) | dir] = EdgeSearch.ceilMs(sBase * (dir == 0 ? 1 - source.fraction : source.fraction))205        }206        var changed = true207        var rounds = 0208        while changed, rounds <= graph.edgeCount * 2 + 1 {209            changed = false210            rounds += 1211            for s in 0..<UInt32(graph.edgeCount * 2) where cost[Int(s)] != .max {212                let rec = graph.edge(s >> 1)213                let v = s & 1 == 0 ? rec.nodeB : rec.nodeA214                let nodeFlags = graph.nodeFlagBits(v)215                if nodeFlags & profile.blockBit != 0 { continue }216                let others = search.otherUsableEdges(at: v, excluding: s >> 1)217                for d2 in graph.directedEdges(leaving: v) {218                    let r2 = graph.edge(d2 >> 1)219                    guard (r2.access >> (shift + UInt8(d2 & 1))) & 1 == 1 else { continue }220                    if d2 >> 1 != source.edge, d2 >> 1 != target.edge, profile.excludes(r2) { continue }221                    guard let turn = search.transition(from: s, rec, to: d2, r2, at: v, nodeFlags: nodeFlags, others: others) else { continue }222                    let start = cost[Int(s)] + UInt64(turn.costMs)223                    if d2 >> 1 == target.edge {224                        best = min(best, start + EdgeSearch.ceilMs(tBase * (d2 & 1 == 0 ? target.fraction : 1 - target.fraction)))225                    }226                    var full = start + EdgeSearch.ceilMs(profile.baseCost(r2))227                    if r2.flags & EdgeFlags.trafficSignal.rawValue != 0 { full += UInt64(profile.signalMs) }228                    if full < cost[Int(d2)] { cost[Int(d2)] = full; changed = true }229                }230            }231        }232        return best == .max ? nil : best233    }234235    @Test(arguments: 0..<24)236    func aStarEqualsDijkstraAndReference(seed: Int) throws {237        let random = Self.randomGraph(seed: UInt64(seed) &* 7919 &+ 17, nodeCount: 30 + seed * 3, extent: 1500 + Double(seed) * 150)238        let graph = random.graph.graph()239        var rng = SeededGenerator(seed: UInt64(seed) &+ 1000)240        var found = 0, unreachable = 0241        for _ in 0..<40 {242            let profile = Self.randomProfile(&rng)243            let compiled = CompiledProfile(profile, graph: graph.metadata)244            let a = p(Double.random(in: 0...random.extent, using: &rng), Double.random(in: 0...random.extent, using: &rng))245            let b = p(Double.random(in: 0...random.extent, using: &rng), Double.random(in: 0...random.extent, using: &rng))246            let options = SnapOptions(maxDistanceMeters: 5000)247            guard let s = try? graph.snap(a, mode: profile.mode, options: options, waypointIndex: 0),248                  let t = try? graph.snap(b, mode: profile.mode, options: options, waypointIndex: 1) else { continue }249            let search = EdgeSearch(graph: graph, profile: compiled)250            let astar = try search.run(source: s, sourceDirections: [true, true], target: t, useHeuristic: true)251            let dijkstra = try search.run(source: s, sourceDirections: [true, true], target: t, useHeuristic: false)252            let reference = Self.referenceCost(graph, compiled, s, t)253            #expect(astar?.costMs == dijkstra?.costMs, "seed \(seed) \(profile.mode)")254            #expect(dijkstra.map { UInt64($0.costMs) } == reference, "seed \(seed) \(profile.mode)")255            guard let astar, let dijkstra else { unreachable += 1; continue }256            found += 1257            #expect(astar.settled <= dijkstra.settled + 2)258            for path in [astar.path, dijkstra.path] {259                #expect(violation(in: path, graph: graph, mode: profile.mode, restrictions: random.graph.restrictions) == nil)260                #expect(path.first! >> 1 == s.edge && path.last! >> 1 == t.edge)261            }262            // The assembled route reports the cost found by the search, and its geometry is continuous.263            let snaps = [s, t]264            let request = RouteRequest(waypoints: [RouteWaypoint(a), RouteWaypoint(b)], profile: profile)265            let route = RouteAssembler(graph: graph, profile: compiled, request: request, snaps: snaps).assemble(paths: [astar.path])266            #expect(route.cost == Double(astar.costMs) / 1000)267            #expect(abs(Geodesy.length(of: route.geometry) - route.distanceMeters) <= 0.5 + route.distanceMeters * 0.001)268            #expect(Geodesy.distance(route.geometry.first!, s.point) < 0.01 && Geodesy.distance(route.geometry.last!, t.point) < 0.01)269            #expect(route.maneuvers.first?.type == .depart && route.maneuvers.last?.type == .arrive)270            #expect(abs(route.maneuvers.map(\.distanceMeters).reduce(0, +) - route.distanceMeters) < 0.01)271            #expect(abs(route.segments.map(\.distanceMeters).reduce(0, +) - route.distanceMeters) < 0.01)272            // Preferences and penalties only ever add to the travel time.273            #expect(route.durationSeconds <= route.cost + 0.001 * Double(astar.path.count + 1))274        }275        #expect(found >= 8, "seed \(seed): only \(found) routes found, \(unreachable) unreachable")276    }277278    @Test func publicAPIAgreesBetweenAlgorithms() throws {279        var compared = 0280        for seed in 100..<108 {281            let random = Self.randomGraph(seed: UInt64(seed), nodeCount: 80, extent: 4000)282            let router = random.graph.router()283            var rng = SeededGenerator(seed: UInt64(seed) &* 31)284            for _ in 0..<25 {285                var req = RouteRequest(waypoints: (0..<3).map { _ in286                    RouteWaypoint(p(Double.random(in: 0...4000, using: &rng), Double.random(in: 0...4000, using: &rng)))287                }, profile: Self.randomProfile(&rng), maxSnapDistanceMeters: 5000)288                let a = Result { try router.compute(req) }289                req.algorithm = .dijkstra290                let d = Result { try router.compute(req) }291                switch (a, d) {292                case (.success(let x), .success(let y)):293                    compared += 1294                    #expect(x.route.cost == y.route.cost)295                    #expect(x.statistics.settledStates <= y.statistics.settledStates + 6)296                case (.failure(let x), .failure(let y)):297                    #expect((x as? RoutingError) == (y as? RoutingError))298                default:299                    Issue.record("one algorithm found a route and the other did not (seed \(seed))")300                }301            }302        }303        #expect(compared > 40)304    }305}306
Files main
Menu

Theme