Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Packages/ORIXRouting/Tests/ORIXRoutingTests/RoutingTests.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@Suite struct RoutingTests {94 /// A 100 m square: a(0,0) b(100,0) c(100,100) d(0,100).95 static func square(abOneWay: Bool = false) -> TestGraph {96 var g = TestGraph()97 g.node("a", 0, 0); g.node("b", 100, 0); g.node("c", 100, 100); g.node("d", 0, 100)98 g.edge("a", "b", abOneWay ? .oneWay("South") : .road("South"))99 g.edge("b", "c", .road("East")); g.edge("c", "d", .road("North")); g.edge("d", "a", .road("West"))100 return g101 }102103 /// A cross at c(0,0) with arms w, e, n, s (100 m) and an outer ring joining the arm ends through the corners.104 static func cross() -> TestGraph {105 var g = TestGraph()106 g.node("c", 0, 0); g.node("w", -100, 0); g.node("e", 100, 0); g.node("n", 0, 100); g.node("s", 0, -100)107 g.node("ne", 100, 100); g.node("se", 100, -100); g.node("nw", -100, 100); g.node("sw", -100, -100)108 g.edge("w", "c", .road("Main")); g.edge("c", "e", .road("Main")); g.edge("c", "n", .road("Cross")); g.edge("c", "s", .road("Cross"))109 g.edge("n", "ne", .road("Ring")); g.edge("ne", "e", .road("Ring")); g.edge("e", "se", .road("Ring")); g.edge("se", "s", .road("Ring"))110 g.edge("s", "sw", .road("Ring")); g.edge("sw", "w", .road("Ring")); g.edge("w", "nw", .road("Ring")); g.edge("nw", "n", .road("Ring"))111 return g112 }113114 @Test func shortestRouteOnASquare() throws {115 let r = try Self.square().router().compute(request([p(10, 0), p(100, 60)]))116 #expect(abs(r.route.distanceMeters - 150) < 1)117 #expect(r.route.legs.count == 1)118 #expect(r.route.geometry.count == 3)119 #expect(Geodesy.distance(r.route.geometry[0], p(10, 0)) < 0.5)120 #expect(Geodesy.distance(r.route.geometry[2], p(100, 60)) < 0.5)121 #expect(abs(Geodesy.length(of: r.route.geometry) - r.route.distanceMeters) < 1)122 // 150 m of untagged residential at the assumed 30 km/h, plus one right… left turn is not penalized at a two-road corner.123 #expect(abs(r.route.durationSeconds - 150 / (30 / 3.6)) < 0.5)124 #expect(r.route.elevationProfile == nil)125 #expect(r.route.boundingBox.contains(p(50, 0)))126 #expect(r.regionID == "test")127 #expect(r.statistics.searches == 1 && r.statistics.settledStates > 0 && r.statistics.peakSearchMemoryBytes > 0)128 }129130 @Test func sameEdgeAndSamePoint() throws {131 let router = Self.square().router()132 let direct = try router.compute(request([p(20, 0), p(70, 0)]))133 #expect(abs(direct.route.distanceMeters - 50) < 0.5)134 #expect(direct.route.maneuvers.map(\.type) == [.depart, .arrive])135 let back = try router.compute(request([p(70, 0), p(20, 0)]))136 #expect(abs(back.route.distanceMeters - 50) < 0.5)137 let zero = try router.compute(request([p(40, 0), p(40, 0)]))138 #expect(zero.route.distanceMeters < 0.5)139 #expect(zero.route.maneuvers.last?.type == .arrive)140 }141142 @Test func oneWayStreetsAreRespected() throws {143 let router = Self.square(abOneWay: true).router()144 // With the traffic: straight along the edge.145 #expect(abs(try router.compute(request([p(10, 0), p(90, 0)])).route.distanceMeters - 80) < 0.5)146 // Against the traffic a car goes round the block and re-enters the street at its start.147 let around = try router.compute(request([p(90, 0), p(10, 0)]))148 #expect(abs(around.route.distanceMeters - 320) < 1)149 // A cyclist follows the same rule, a pedestrian walks back.150 #expect(abs(try router.compute(request([p(90, 0), p(10, 0)], .bicycle)).route.distanceMeters - 320) < 1)151 #expect(abs(try router.compute(request([p(90, 0), p(10, 0)], .pedestrian)).route.distanceMeters - 80) < 0.5)152 }153154 @Test func accessPerMode() throws {155 var g = TestGraph()156 g.node("a", 0, 0); g.node("b", 1000, 0); g.node("x", 500, 400); g.node("a0", -100, 0); g.node("b1", 1100, 0)157 g.edge("a0", "a", .road("Start")); g.edge("b", "b1", .road("End"))158 g.edge("a", "b", .road("Autoroute", .motorway, access: RoutingGraphWriter.EdgeAttributes.carOnly, speed: 100))159 g.edge("a", "x", .road("Sentier", .footway, access: RoutingGraphWriter.EdgeAttributes.footOnly))160 g.edge("x", "b", .road("Piste", .cycleway, access: [.bicycleForward, .bicycleBackward, .pedestrianForward, .pedestrianBackward]))161 let router = g.router()162 let car = try router.compute(request([p(-50, 0), p(1050, 0)]))163 #expect(abs(car.route.distanceMeters - 1100) < 1)164 #expect(car.route.segments.contains { $0.roadClass == .motorway })165 let walk = try router.compute(request([p(-50, 0), p(1050, 0)], .pedestrian))166 #expect(walk.route.distanceMeters > 1300)167 #expect(!walk.route.segments.contains { $0.roadClass == .motorway })168 // The footway is closed to bicycles: no way through.169 #expect(throws: RoutingError.noConnection(fromWaypointIndex: 0, toWaypointIndex: 1, differentComponents: true)) {170 try router.compute(request([p(-50, 0), p(1050, 0)], .bicycle))171 }172 }173174 @Test func prohibitiveRestriction() throws {175 var g = Self.cross()176 g.restrict(from: "w-c", via: "c", to: "c-n", .prohibitive)177 let router = g.router()178 // Left turn forbidden: the car goes round by the north-west corner instead (40 + 100 + 100 + 40 m).179 let car = try router.compute(request([p(-60, 0), p(0, 60)]))180 #expect(abs(car.route.distanceMeters - 280) < 1)181 // The reverse movement and other modes are not concerned.182 #expect(abs(try router.compute(request([p(0, 60), p(-60, 0)])).route.distanceMeters - 120) < 1)183 #expect(abs(try router.compute(request([p(-60, 0), p(0, 60)], .pedestrian)).route.distanceMeters - 120) < 1)184 #expect(abs(try router.compute(request([p(-60, 0), p(0, -60)])).route.distanceMeters - 120) < 1)185 // Without the restriction the car turns left directly.186 #expect(abs(try Self.cross().router().compute(request([p(-60, 0), p(0, 60)])).route.distanceMeters - 120) < 1)187 }188189 @Test func mandatoryRestriction() throws {190 var g = Self.cross()191 g.restrict(from: "w-c", via: "c", to: "c-e", .mandatory) // only_straight_on192 let router = g.router()193 #expect(abs(try router.compute(request([p(-60, 0), p(60, 0)])).route.distanceMeters - 120) < 1)194 #expect(abs(try router.compute(request([p(-60, 0), p(0, 60)])).route.distanceMeters - 280) < 1)195 #expect(abs(try router.compute(request([p(-60, 0), p(0, -60)])).route.distanceMeters - 280) < 1)196 // Coming from another arm the mandatory direction does not apply.197 #expect(abs(try router.compute(request([p(0, -60), p(0, 60)])).route.distanceMeters - 120) < 1)198 }199200 @Test func restrictionsApplyPerMode() throws {201 var g = Self.cross()202 g.restrict(from: "w-c", via: "c", to: "c-n", .prohibitive, modes: [.car]) // except=bicycle203 let router = g.router()204 #expect(abs(try router.compute(request([p(-60, 0), p(0, 60)])).route.distanceMeters - 280) < 1)205 #expect(abs(try router.compute(request([p(-60, 0), p(0, 60)], .bicycle)).route.distanceMeters - 120) < 1)206 }207208 @Test func uTurnRestrictionAndPolicy() throws {209 // A street a—b—c—d where b is mid-block, c a junction (side streets) and d a dead end.210 var g = TestGraph()211 g.node("a", 0, 0); g.node("b", 100, 0); g.node("c", 200, 0); g.node("d", 300, 0); g.node("cn", 200, 100); g.node("cs", 200, -100)212 g.edge("a", "b", .road("Rue")); g.edge("b", "c", .road("Rue")); g.edge("c", "d", .road("Rue"))213 g.edge("c", "cn", .road("Nord")); g.edge("c", "cs", .road("Sud"))214 // Leaving eastwards from (120, 0) with the destination behind: the car may not turn round mid-block, it does at junction c.215 var req = request([p(120, 0), p(50, 0)])216 req.waypoints[0].heading = 90217 let turned = try g.router().compute(req)218 #expect(abs(turned.route.distanceMeters - (80 + 100 + 50)) < 1, "\(turned.route.distanceMeters)")219 #expect(turned.route.maneuvers.contains { $0.type == .uTurn })220 // The U-turn costs time.221 #expect(turned.route.durationSeconds > turned.route.distanceMeters / (30 / 3.6) + 20)222223 // With no_u_turn at c, the car has to go to the dead end d.224 g.restrict(from: "b-c", via: "c", to: "b-c", .prohibitive)225 let farther = try g.router().compute(req)226 #expect(farther.route.distanceMeters > turned.route.distanceMeters + 100)227228 // Profile that refuses U-turns at junctions behaves the same without the relation.229 var strict = RoutingProfile.car230 strict.allowsUTurnAtJunctions = false231 var strictRequest = req232 strictRequest.profile = strict233 var plain = TestGraph()234 plain.node("a", 0, 0); plain.node("b", 100, 0); plain.node("c", 200, 0); plain.node("d", 300, 0); plain.node("cn", 200, 100); plain.node("cs", 200, -100)235 plain.edge("a", "b", .road("Rue")); plain.edge("b", "c", .road("Rue")); plain.edge("c", "d", .road("Rue"))236 plain.edge("c", "cn", .road("Nord")); plain.edge("c", "cs", .road("Sud"))237 // Dead ends always allow turning round: 80 m to c, 100 m into an arm and back, then 150 m to the destination.238 let viaDeadEnd = try plain.router().compute(strictRequest)239 #expect(abs(viaDeadEnd.route.distanceMeters - (80 + 100 + 100 + 100 + 50)) < 1, "\(viaDeadEnd.route.distanceMeters)")240241 // A pedestrian simply turns round on the spot.242 var walk = req243 walk.profile = .pedestrian244 walk.waypoints[0].heading = nil245 #expect(abs(try g.router().compute(walk).route.distanceMeters - 70) < 1)246 }247248 @Test func headingSelectsTheDepartureDirection() throws {249 let router = Self.square().router()250 var east = request([p(50, 0), p(0, 50)])251 east.waypoints[0].heading = 90252 #expect(abs(try router.compute(east).route.distanceMeters - 300) < 1)253 var west = east254 west.waypoints[0].heading = 270255 #expect(abs(try router.compute(west).route.distanceMeters - 100) < 1)256 // A heading across the road constrains nothing.257 var north = east258 north.waypoints[0].heading = 0259 #expect(abs(try router.compute(north).route.distanceMeters - 100) < 1)260 }261262 @Test func barriers() throws {263 var g = TestGraph()264 g.node("a", 0, 0); g.node("b", 100, 0, flags: [.blocksCar]); g.node("c", 200, 0); g.node("x", 100, 300)265 g.edge("a", "b", .road("Rue")); g.edge("b", "c", .road("Rue")); g.edge("a", "x", .road("Détour")); g.edge("x", "c", .road("Détour"))266 let router = g.router()267 let car = try router.compute(request([p(10, 0), p(190, 0)]))268 #expect(car.route.distanceMeters > 600)269 #expect(abs(try router.compute(request([p(10, 0), p(190, 0)], .pedestrian)).route.distanceMeters - 180) < 1)270 #expect(abs(try router.compute(request([p(10, 0), p(190, 0)], .bicycle)).route.distanceMeters - 180) < 1)271 // A car can still drive up to the bollard.272 #expect(abs(try router.compute(request([p(10, 0), p(90, 0)])).route.distanceMeters - 80) < 1)273274 // Without the detour the two sides are separate networks for cars: immediate answer.275 var cut = TestGraph()276 cut.node("a", 0, 0); cut.node("b", 100, 0, flags: [.blocksCar]); cut.node("c", 200, 0)277 cut.edge("a", "b", .road("Rue")); cut.edge("b", "c", .road("Rue"))278 #expect(throws: RoutingError.noConnection(fromWaypointIndex: 0, toWaypointIndex: 1, differentComponents: true)) {279 try cut.router().compute(request([p(10, 0), p(190, 0)]))280 }281 }282283 @Test func disconnectedComponents() throws {284 var g = Self.square()285 g.node("i1", 3000, 0); g.node("i2", 3100, 0); g.node("i3", 3100, 100)286 g.edge("i1", "i2", .road("Île")); g.edge("i2", "i3", .road("Île"))287 let graph = g.graph()288 #expect(graph.componentRank(ofNode: g.nodes["a"]!, mode: .car) == 1)289 #expect(graph.componentRank(ofNode: g.nodes["i1"]!, mode: .car) == 2)290 for profile in [RoutingProfile.car, .bicycle, .pedestrian] {291 #expect(throws: RoutingError.noConnection(fromWaypointIndex: 0, toWaypointIndex: 1, differentComponents: true)) {292 try Router(graph: graph).compute(request([p(10, 0), p(3050, 0)], profile))293 }294 }295 // Inside the island routing works.296 #expect(abs(try Router(graph: graph).compute(request([p(3010, 0), p(3100, 50)])).route.distanceMeters - 140) < 1)297 // With three waypoints the failing leg is reported.298 #expect(throws: RoutingError.noConnection(fromWaypointIndex: 1, toWaypointIndex: 2, differentComponents: true)) {299 try Router(graph: graph).compute(request([p(10, 0), p(90, 100), p(3050, 0)]))300 }301 }302303 @Test func oneWayTrapIsReportedBySearch() throws {304 // b can be reached from a but nothing leaves b: same weak component, no route back.305 var g = TestGraph()306 g.node("a", 0, 0); g.node("b", 100, 0); g.node("z", -100, 0)307 g.edge("z", "a", .road("Rue")); g.edge("a", "b", .oneWay("Sens unique"))308 let router = g.router()309 #expect(abs(try router.compute(request([p(-50, 0), p(60, 0)])).route.distanceMeters - 110) < 1)310 #expect(throws: RoutingError.noConnection(fromWaypointIndex: 0, toWaypointIndex: 1, differentComponents: false)) {311 try router.compute(request([p(60, 0), p(-50, 0)]))312 }313 }314315 @Test func snapping() throws {316 var g = Self.square()317 g.node("f1", 30, 20); g.node("f2", 70, 20)318 g.edge("f1", "f2", .road("Sentier", .footway, access: RoutingGraphWriter.EdgeAttributes.footOnly))319 g.node("q1", 0, -300); g.node("q2", 100, -300)320 g.edge("q1", "q2", .road("Traversier", .ferry))321 let graph = g.graph()322 // Nearest usable edge per mode.323 let walk = try graph.nearestRoad(to: p(50, 14), mode: .pedestrian)324 #expect(walk.name == "Sentier" && abs(walk.distanceMeters - 6) < 0.5 && abs(walk.fraction - 0.5) < 0.02)325 let car = try graph.nearestRoad(to: p(50, 14), mode: .car)326 #expect(car.name == "South" && abs(car.distanceMeters - 14) < 0.5)327 #expect(Geodesy.distance(car.coordinate, p(50, 0)) < 0.5)328 // Ferries are never snapped to.329 #expect(try graph.nearestRoad(to: p(50, -290), mode: .car, options: SnapOptions(maxDistanceMeters: 400)).name == "South")330 // Too far, and outside the coverage.331 #expect(throws: RoutingError.pointTooFarFromRoad(waypointIndex: 0, maxDistanceMeters: 100)) {332 try graph.nearestRoad(to: p(50, -150), mode: .car, options: SnapOptions(maxDistanceMeters: 100))333 }334 #expect(throws: RoutingError.pointOutsideCoverage(waypointIndex: 0)) {335 try graph.nearestRoad(to: p(50_000, 0), mode: .car)336 }337 #expect(throws: RoutingError.pointOutsideCoverage(waypointIndex: 1)) {338 try Router(graph: graph).compute(request([p(10, 0), p(0, 90_000)]))339 }340 var near = request([p(10, 0), p(50, -150)])341 near.maxSnapDistanceMeters = 100342 #expect(throws: RoutingError.pointTooFarFromRoad(waypointIndex: 1, maxDistanceMeters: 100)) {343 try Router(graph: graph).compute(near)344 }345 #expect(throws: RoutingError.invalidRequest("waypoint 0 is not a valid coordinate")) {346 try Router(graph: graph).compute(request([Coordinate(latitude: .nan, longitude: 0), p(0, 0)]))347 }348 #expect(throws: RoutingError.invalidRequest("at least two waypoints are required")) {349 try Router(graph: graph).compute(request([p(0, 0)]))350 }351 }352353 @Test func snappingPrefersTheMainNetwork() throws {354 // A 40-node street next to a short isolated driveway.355 var g = TestGraph()356 for i in 0..<40 { g.node("m\(i)", Double(i) * 50, 0) }357 for i in 1..<40 { g.edge("m\(i - 1)", "m\(i)", .road("Rue principale")) }358 g.node("x1", 500, 12); g.node("x2", 540, 12)359 g.edge("x1", "x2", .road("Entrée isolée", .service))360 let graph = g.graph()361 // The isolated edge is closer (4 m against 8 m) but leads nowhere.362 #expect(try graph.nearestRoad(to: p(520, 8), mode: .car).name == "Rue principale")363 // Far from the main network, the isolated road is still returned.364 let tolerant = SnapOptions(maxDistanceMeters: 500, isolatedRoadToleranceMeters: 2)365 #expect(try graph.nearestRoad(to: p(520, 11), mode: .car, options: tolerant).name == "Entrée isolée")366 }367368 @Test func waypointsAreVisitedInOrder() throws {369 let router = Self.cross().router()370 let r = try router.compute(request([p(-60, 0), p(0, 60), p(60, 0), p(0, -60)]))371 #expect(r.route.legs.count == 3)372 #expect(r.route.waypoints.count == 4)373 #expect(abs(r.route.distanceMeters - 360) < 1)374 #expect(abs(r.route.legs.map(\.distanceMeters).reduce(0, +) - r.route.distanceMeters) < 0.01)375 #expect(abs(r.route.legs.map(\.durationSeconds).reduce(0, +) - r.route.durationSeconds) < 0.01)376 #expect(r.statistics.searches == 3)377 // Legs chain through the geometry and the stops lie on it.378 #expect(r.route.legs[0].geometryRange.lowerBound == 0)379 #expect(r.route.legs[0].geometryRange.upperBound == r.route.legs[1].geometryRange.lowerBound)380 #expect(r.route.legs[2].geometryRange.upperBound == r.route.geometry.count - 1)381 #expect(Geodesy.distance(r.route.geometry[r.route.legs[1].geometryRange.lowerBound], p(0, 60)) < 0.5)382 #expect(Geodesy.distance(r.route.geometry[r.route.legs[2].geometryRange.lowerBound], p(60, 0)) < 0.5)383 let types = r.route.maneuvers.map(\.type)384 #expect(types.first == .depart && types.last == .arrive)385 #expect(types.filter { $0 == .waypoint }.count == 2)386 #expect(r.route.maneuvers.filter { $0.type == .waypoint }.map(\.waypointIndex) == [1, 2])387 // Maneuver ranges partition the list per leg.388 #expect(r.route.legs.map(\.maneuverRange.count).reduce(0, +) == r.route.maneuvers.count)389 #expect(r.route.maneuvers[r.route.legs[1].maneuverRange.lowerBound].type == .waypoint)390 #expect(abs(r.route.maneuvers.map(\.distanceMeters).reduce(0, +) - r.route.distanceMeters) < 0.01)391 }392393 @Test func alternativesAreDifferentValidRoutes() throws {394 // 7 × 7 grid of 100 m blocks.395 var g = TestGraph()396 for y in 0..<7 { for x in 0..<7 { g.node("\(x),\(y)", Double(x) * 100, Double(y) * 100) } }397 for y in 0..<7 {398 for x in 0..<7 {399 if x < 6 { g.edge("\(x),\(y)", "\(x + 1),\(y)", .road("H\(y)")) }400 if y < 6 { g.edge("\(x),\(y)", "\(x),\(y + 1)", .road("V\(x)")) }401 }402 }403 let router = g.router()404 let r = try router.compute(request([p(0, 50), p(600, 550)], alternatives: 2))405 #expect(r.alternatives.count == 2)406 #expect(r.routes.count == 3)407 #expect(r.statistics.searches >= 3)408 for (i, alternative) in r.alternatives.enumerated() {409 #expect(alternative.cost >= r.route.cost)410 #expect(alternative.cost <= r.route.cost * 1.4 + 0.001)411 #expect(Geodesy.distance(alternative.geometry.first!, r.route.geometry.first!) < 0.5)412 #expect(Geodesy.distance(alternative.geometry.last!, r.route.geometry.last!) < 0.5)413 #expect(abs(Geodesy.length(of: alternative.geometry) - alternative.distanceMeters) < 1)414 #expect(alternative.maneuvers.first?.type == .depart && alternative.maneuvers.last?.type == .arrive)415 // Really different: at most 70 % of its length is shared with any other route of the answer.416 for (j, other) in r.routes.enumerated() where j != i + 1 {417 #expect(sharedFraction(alternative.geometry, other.geometry) <= 0.71)418 }419 }420 // No alternative exists on a single street, and none is invented.421 var line = TestGraph()422 line.node("a", 0, 0); line.node("b", 500, 0)423 line.edge("a", "b", .road("Seule"))424 #expect(try line.router().compute(request([p(10, 0), p(400, 0)], alternatives: 2)).alternatives.isEmpty)425 // A much longer way round is not offered.426 var detour = TestGraph()427 detour.node("a", 0, 0); detour.node("b", 500, 0); detour.node("x", 250, 2000)428 detour.edge("a", "b", .road("Directe")); detour.edge("a", "x", .road("Loin")); detour.edge("x", "b", .road("Loin"))429 #expect(try detour.router().compute(request([p(0, 5), p(500, 5)], alternatives: 2)).alternatives.isEmpty)430 }431432 /// Fraction of the length of `a` that runs along segments also present in `b`.433 func sharedFraction(_ a: [Coordinate], _ b: [Coordinate]) -> Double {434 func key(_ c: Coordinate) -> String { "\(c.e7.lat),\(c.e7.lon)" }435 var segments = Set<String>()436 for i in 1..<b.count { segments.insert(key(b[i - 1]) + ">" + key(b[i])) }437 var shared = 0.0, total = 0.0438 for i in 1..<a.count {439 let d = Geodesy.distance(a[i - 1], a[i])440 total += d441 if segments.contains(key(a[i - 1]) + ">" + key(a[i])) { shared += d }442 }443 return total > 0 ? shared / total : 0444 }445446 @Test func avoidOptions() throws {447 // Two parallel ways from a to b: a fast special one and a slow plain one.448 func graph(_ special: RoutingGraphWriter.EdgeAttributes) -> TestGraph {449 var g = TestGraph()450 g.node("a0", -100, 0); g.node("a", 0, 0); g.node("b", 1000, 0); g.node("b1", 1100, 0); g.node("x", 500, 300)451 g.edge("a0", "a", .road("Start")); g.edge("b", "b1", .road("End"))452 g.edge("a", "b", special)453 g.edge("a", "x", .road("Lente")); g.edge("x", "b", .road("Lente"))454 return g455 }456 let cases: [(RoutingGraphWriter.EdgeAttributes, RouteAvoidance, RouteWarningKind?)] = [457 (.road("Péage", .primary, speed: 90, flags: [.toll]), RouteAvoidance(tolls: true), .toll),458 (.road("Autoroute", .motorway, speed: 100), RouteAvoidance(motorways: true), nil),459 (.road("Gravier", .primary, speed: 90, surface: .unpaved), RouteAvoidance(unpaved: true), .unpaved),460 ]461 for (special, avoid, warning) in cases {462 let router = graph(special).router()463 let normal = try router.compute(request([p(-50, 0), p(1050, 0)]))464 #expect(abs(normal.route.distanceMeters - 1100) < 1)465 if let warning {466 let w = try #require(normal.route.warnings.first { $0.kind == warning })467 #expect(abs(w.distanceMeters - 1000) < 1 && abs(w.share - 1000 / 1100) < 0.01)468 }469 let avoiding = try router.compute(request([p(-50, 0), p(1050, 0)], RoutingProfile.car.avoiding(avoid)))470 #expect(avoiding.route.distanceMeters > 1200)471 if let warning { #expect(!avoiding.route.warnings.contains { $0.kind == warning }) }472 }473 // Ferry: the only link between two shores.474 var g = TestGraph()475 g.node("a0", -100, 0); g.node("a", 0, 0); g.node("b", 1000, 0); g.node("b1", 1100, 0)476 g.edge("a0", "a", .road("Quai sud")); g.edge("b", "b1", .road("Quai nord"))477 g.edge("a", "b", .road("Traversier", .ferry, speed: 12))478 let router = g.router()479 let crossing = try router.compute(request([p(-50, 0), p(1050, 0)]))480 #expect(crossing.route.warnings.contains { $0.kind == .ferry })481 #expect(crossing.route.maneuvers.contains { $0.type == .ferry })482 // 1 km at 12 km/h = 300 s, plus 900 s of boarding, plus 100 m of street.483 #expect(abs(crossing.route.durationSeconds - (300 + 900 + 100 / (30 / 3.6))) < 1)484 #expect(throws: RoutingError.noConnection(fromWaypointIndex: 0, toWaypointIndex: 1, differentComponents: false)) {485 try router.compute(request([p(-50, 0), p(1050, 0)], RoutingProfile.car.avoiding(RouteAvoidance(ferries: true))))486 }487 }488489 @Test func durationAndAssumedSpeeds() throws {490 var g = TestGraph()491 g.node("a", 0, 0); g.node("b", 1000, 0); g.node("c", 2000, 0)492 g.edge("a", "b", .road("Tagged", .motorway, speed: 100))493 g.edge("b", "c", .road("Untagged", .motorway))494 let router = g.router()495 let r = try router.compute(request([p(0, 0), p(2000, 0)]))496 #expect(abs(r.route.distanceMeters - 2000) < 1)497 // 1 km at the tagged 100 km/h and 1 km at the assumed 100 km/h.498 #expect(abs(r.route.durationSeconds - 72) < 0.5)499 #expect(abs(r.route.assumedSpeedDistanceMeters - 1000) < 1)500 let warning = try #require(r.route.warnings.first { $0.kind == .assumedSpeeds })501 #expect(abs(warning.share - 0.5) < 0.01)502 #expect(r.route.segments.count == 2)503 #expect(r.route.segments[0].usesAssumedSpeed == false && r.route.segments[1].usesAssumedSpeed == true)504 #expect(r.route.segments[0].name == "Tagged" && r.route.segments[1].name == "Untagged")505 #expect(r.route.segments[0].geometryRange.upperBound == r.route.segments[1].geometryRange.lowerBound)506 // Walking does not depend on speed tags: nothing is "assumed".507 let walk = try router.compute(request([p(0, 0), p(2000, 0)], RoutingProfile(508 mode: .car, name: "slow", usesTaggedSpeeds: false, taggedSpeedCapKmh: 0, taggedSpeedFactor: [:], assumedSpeedKmh: [.motorway: 36],509 assumedLinkSpeedKmh: 36, classPreference: [:], unpavedSpeedFactor: 1, unknownSurfaceSpeedFactor: 1, unpavedPreference: 1,510 minorServicePreference: 1, ferryDefaultSpeedKmh: 10, ferryCostSpeedCapKmh: 10, ferryBoardingSeconds: 0, leftTurnSeconds: 0,511 rightTurnSeconds: 0, trafficSignalSeconds: 0, uTurnSeconds: 0, allowsUTurnAtJunctions: true, allowsUTurnMidBlock: true,512 restrictedAccessPenaltySeconds: 0)))513 #expect(abs(walk.route.durationSeconds - 200) < 0.5)514 #expect(walk.route.assumedSpeedDistanceMeters == 0)515 #expect(walk.route.profileName == "slow")516 }517518 @Test func turnCostsAndSignals() throws {519 var g = Self.cross()520 let plain = try g.router().compute(request([p(-60, 0), p(60, 0)]))521 let left = try g.router().compute(request([p(-60, 0), p(0, 60)]))522 let right = try g.router().compute(request([p(-60, 0), p(0, -60)]))523 let base = 120 / (30 / 3.6)524 #expect(abs(plain.route.durationSeconds - base) < 0.1)525 #expect(abs(left.route.durationSeconds - base - RoutingProfile.car.leftTurnSeconds) < 0.1)526 #expect(abs(right.route.durationSeconds - base - RoutingProfile.car.rightTurnSeconds) < 0.1)527 // The same junction with a traffic signal.528 g.nodes["c"] = nil529 var signalled = TestGraph()530 signalled.node("c", 0, 0, flags: [.trafficSignal]); signalled.node("w", -100, 0); signalled.node("e", 100, 0)531 signalled.node("n", 0, 100); signalled.node("s", 0, -100)532 signalled.edge("w", "c", .road("Main")); signalled.edge("c", "e", .road("Main"))533 signalled.edge("c", "n", .road("Cross")); signalled.edge("c", "s", .road("Cross"))534 let waited = try signalled.router().compute(request([p(-60, 0), p(60, 0)]))535 #expect(abs(waited.route.durationSeconds - base - RoutingProfile.car.trafficSignalSeconds) < 0.1)536 }537538 @Test func restrictedAccessIsALastResort() throws {539 // A private shortcut and a public way round.540 var g = TestGraph()541 g.node("a0", -100, 0); g.node("a", 0, 0); g.node("b", 400, 0); g.node("b1", 500, 0); g.node("x", 200, 300)542 g.node("m", 200, 0); g.node("h", 200, -100)543 g.edge("a0", "a", .road("Rue")); g.edge("b", "b1", .road("Rue"))544 g.edge("a", "m", .road("Privé", .service, flags: [.restrictedCar])); g.edge("m", "b", .road("Privé", .service, flags: [.restrictedCar]))545 g.edge("m", "h", .road("Cour", .service, flags: [.restrictedCar]))546 g.edge("a", "x", .road("Publique")); g.edge("x", "b", .road("Publique"))547 let router = g.router()548 let through = try router.compute(request([p(-50, 0), p(450, 0)]))549 #expect(through.route.distanceMeters > 700)550 #expect(!through.route.warnings.contains { $0.kind == .restrictedAccess })551 // A destination inside the private area is reached, with a warning.552 let inside = try router.compute(request([p(-50, 0), p(200, -60)]))553 #expect(abs(inside.route.distanceMeters - 310) < 1)554 let warning = try #require(inside.route.warnings.first { $0.kind == .restrictedAccess })555 #expect(abs(warning.distanceMeters - 260) < 1)556 #expect(inside.route.segments.contains { $0.isRestrictedAccess })557 // The penalty steers the choice but is not counted as travel time.558 #expect(inside.route.cost > inside.route.durationSeconds + 500)559 }560561 @Test func cancellation() async throws {562 let router = Self.square().router()563 let task = Task { () -> Result<RouteResponse, RoutingError> in564 withUnsafeCurrentTask { $0?.cancel() }565 return await outcome(router, request([p(10, 0), p(100, 60)]))566 }567 let first = await task.value568 #expect(first == Result<RouteResponse, RoutingError>.failure(.cancelled))569570 // A long search checked while it runs: cancelled or finished, never anything else.571 var g = TestGraph()572 let n = 120573 for y in 0..<n { for x in 0..<n { g.node("\(x),\(y)", Double(x) * 60, Double(y) * 60) } }574 for y in 0..<n {575 for x in 0..<n {576 if x < n - 1 { g.edge("\(x),\(y)", "\(x + 1),\(y)") }577 if y < n - 1 { g.edge("\(x),\(y)", "\(x),\(y + 1)") }578 }579 }580 let big = g.router()581 var req = request([p(0, 30), p(Double(n - 1) * 60, Double(n - 1) * 60 - 30)])582 req.algorithm = .dijkstra583 let long = Task { () -> Result<RouteResponse, RoutingError> in584 await outcome(big, req)585 }586 try await Task.sleep(nanoseconds: 2_000_000)587 long.cancel()588 let second = await long.value589 switch second {590 case .success(let r): #expect(r.route.distanceMeters > 14_000)591 case .failure(let e): #expect(e == .cancelled)592 }593 // The same request uncancelled succeeds, and asynchronous and synchronous entry points agree.594 let a = try await big.route(req), b = try big.compute(req)595 #expect(a.route.cost == b.route.cost && a.route.geometry == b.route.geometry)596 }597598 @Test func responsesAreCodable() throws {599 let response = try Self.cross().router().compute(request([p(-60, 0), p(0, 60), p(60, 0)], alternatives: 0))600 let encoder = JSONEncoder(), decoder = JSONDecoder()601 let decoded = try decoder.decode(RouteResponse.self, from: encoder.encode(response))602 #expect(decoded == response)603 let req = request([p(-60, 0), p(0, 60)], RoutingProfile.bicycle.avoiding(RouteAvoidance(ferries: true)), alternatives: 2)604 #expect(try decoder.decode(RouteRequest.self, from: encoder.encode(req)) == req)605 let error = RoutingError.noConnection(fromWaypointIndex: 0, toWaypointIndex: 1, differentComponents: true)606 #expect(try decoder.decode(RoutingError.self, from: encoder.encode(error)) == error)607 }608}609