| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Linq; |
| | | 4 | | using System.Threading; |
| | | 5 | | using System.Threading.Tasks; |
| | | 6 | | using Itinero.Network; |
| | | 7 | | using Itinero.Network.Enumerators.Edges; |
| | | 8 | | using Itinero.Routes.Paths; |
| | | 9 | | using Itinero.Routing.Costs; |
| | | 10 | | using Itinero.Routing.DataStructures; |
| | | 11 | | using Itinero.Snapping; |
| | | 12 | | |
| | | 13 | | namespace Itinero.Routing.Flavours.Dijkstra.Bidirectional; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Edge-based bidirectional Dijkstra. Two single-source edge-based searches grow |
| | | 17 | | /// simultaneously — forward from the source, backward from the target. Visits in |
| | | 18 | | /// both halves are dedup'd by <c>(edge, vertex)</c>, so different incoming edges at |
| | | 19 | | /// a vertex retain distinct best-cost state. They meet wherever a forward-settled |
| | | 20 | | /// <c>(E_f, V)</c> shares a vertex V with a backward-settled <c>(E_b, V)</c> and the |
| | | 21 | | /// turn at V from E_f to E_b is allowed. |
| | | 22 | | /// |
| | | 23 | | /// When <c>isMainN</c> is supplied each half applies the same per-half access rule |
| | | 24 | | /// in its own search direction: reject relaxations where the previous edge is main-N |
| | | 25 | | /// and the candidate next edge is not. The two halves combined admit exactly the |
| | | 26 | | /// five valid path shapes the unidirectional state-bit Dijkstra admits. |
| | | 27 | | /// </summary> |
| | | 28 | | internal class BidirectionalDijkstra |
| | | 29 | | { |
| | 77 | 30 | | private readonly Half _forward = new(); |
| | 77 | 31 | | private readonly Half _backward = new(); |
| | | 32 | | |
| | | 33 | | // Best meeting found so far. |
| | | 34 | | private double _bestCost; |
| | | 35 | | private uint _bestForward; |
| | | 36 | | private uint _bestBackward; |
| | | 37 | | // Path returned by the same-edge single-hop fast path; bypasses meeting. |
| | | 38 | | private Path? _singleHopPath; |
| | | 39 | | |
| | | 40 | | private sealed class Half |
| | | 41 | | { |
| | 154 | 42 | | public readonly PathTree Tree = new(); |
| | 154 | 43 | | public readonly BinaryHeap<(uint pointer, EdgeId edge, VertexId vertex)> Heap = new(); |
| | 154 | 44 | | public readonly HashSet<(EdgeId edge, VertexId vertex)> Settled = new(); |
| | | 45 | | // Per-vertex list of settled arrivals. Each entry records the incoming edge plus |
| | | 46 | | // the head order at this vertex for that edge — both are needed to query turn |
| | | 47 | | // costs against this label when the other half asks "can I meet you here?". |
| | 154 | 48 | | public readonly Dictionary<VertexId, List<SettledEntry>> SettledByVertex = new(); |
| | | 49 | | |
| | | 50 | | public void Clear() |
| | 154 | 51 | | { |
| | 154 | 52 | | Tree.Clear(); |
| | 154 | 53 | | Heap.Clear(); |
| | 154 | 54 | | Settled.Clear(); |
| | 154 | 55 | | SettledByVertex.Clear(); |
| | 154 | 56 | | } |
| | | 57 | | } |
| | | 58 | | |
| | 462 | 59 | | private readonly record struct SettledEntry(EdgeId Edge, bool Forward, byte? HeadOrder, uint Pointer, double Cost); |
| | | 60 | | |
| | | 61 | | /// <summary>Fresh instance per call. See <see cref="Dijkstra.Default"/> for rationale.</summary> |
| | 77 | 62 | | public static BidirectionalDijkstra Default => new(); |
| | | 63 | | |
| | | 64 | | public async Task<(Path? path, double cost)> RunAsync( |
| | | 65 | | RoutingNetwork network, |
| | | 66 | | SnapPoint source, |
| | | 67 | | SnapPoint target, |
| | | 68 | | ICostFunction costFunction, |
| | | 69 | | Func<VertexId, Task<bool>>? settledCb = null, |
| | | 70 | | CancellationToken cancellationToken = default, |
| | | 71 | | IsMainNFunc? isMainN = null) |
| | 77 | 72 | | { |
| | 77 | 73 | | _forward.Clear(); |
| | 77 | 74 | | _backward.Clear(); |
| | 77 | 75 | | _bestCost = double.MaxValue; |
| | 77 | 76 | | _bestForward = uint.MaxValue; |
| | 77 | 77 | | _bestBackward = uint.MaxValue; |
| | 77 | 78 | | _singleHopPath = null; |
| | | 79 | | |
| | | 80 | | // Single-edge fast path. If both snap points are on the same edge a direct sub-edge |
| | | 81 | | // path may already win; we seed _bestCost so the bidirectional search can still |
| | | 82 | | // improve via a longer path that happens to have lower cost. |
| | 77 | 83 | | if (network.TrySingleHop(source, target, costFunction, out var singleHopPath, out var singleHopCost)) |
| | 48 | 84 | | { |
| | 48 | 85 | | _singleHopPath = singleHopPath; |
| | 48 | 86 | | _bestCost = singleHopCost; |
| | 48 | 87 | | } |
| | | 88 | | |
| | 77 | 89 | | var enumerator = network.GetEdgeEnumerator(); |
| | | 90 | | |
| | 77 | 91 | | PushTerminal(enumerator, source, costFunction, _forward, asOrigin: true); |
| | 77 | 92 | | PushTerminal(enumerator, target, costFunction, _backward, asOrigin: false); |
| | | 93 | | |
| | 77 | 94 | | var forwardCost = 0.0; |
| | 77 | 95 | | var backwardCost = 0.0; |
| | | 96 | | |
| | 870 | 97 | | while (_forward.Heap.Count > 0 || _backward.Heap.Count > 0) |
| | 843 | 98 | | { |
| | 843 | 99 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 100 | | |
| | | 101 | | // Stopping: once both heap mins combined exceed best, no improvement possible. |
| | 893 | 102 | | if (_bestCost <= forwardCost + backwardCost) break; |
| | | 103 | | |
| | 793 | 104 | | if (_forward.Heap.Count > 0) |
| | 786 | 105 | | { |
| | 786 | 106 | | var popped = await this.Step(network, _forward, _backward, isForwardHalf: true, costFunction, isMainN, s |
| | 1572 | 107 | | if (popped.HasValue) forwardCost = popped.Value; |
| | 786 | 108 | | } |
| | 793 | 109 | | if (_backward.Heap.Count > 0) |
| | 791 | 110 | | { |
| | 791 | 111 | | var popped = await this.Step(network, _backward, _forward, isForwardHalf: false, costFunction, isMainN, |
| | 1582 | 112 | | if (popped.HasValue) backwardCost = popped.Value; |
| | 791 | 113 | | } |
| | 793 | 114 | | } |
| | | 115 | | |
| | 89 | 116 | | if (_bestCost >= double.MaxValue) return (null, double.MaxValue); |
| | | 117 | | |
| | | 118 | | // Single-hop won. |
| | 113 | 119 | | if (_bestForward == uint.MaxValue) return (_singleHopPath, _bestCost); |
| | | 120 | | |
| | 17 | 121 | | var forwardPath = BuildPath(network, _forward.Tree, _bestForward); |
| | 17 | 122 | | var backwardPath = BuildPath(network, _backward.Tree, _bestBackward); |
| | 17 | 123 | | forwardPath.Append(backwardPath.InvertDirection()); |
| | | 124 | | |
| | 17 | 125 | | forwardPath.Offset1 = forwardPath.First.direction ? source.Offset : (ushort)(ushort.MaxValue - source.Offset); |
| | 17 | 126 | | forwardPath.Offset2 = forwardPath.Last.direction ? target.Offset : (ushort)(ushort.MaxValue - target.Offset); |
| | | 127 | | |
| | 17 | 128 | | return (forwardPath, _bestCost); |
| | 77 | 129 | | } |
| | | 130 | | |
| | | 131 | | private static void PushTerminal( |
| | | 132 | | RoutingNetworkEdgeEnumerator enumerator, |
| | | 133 | | SnapPoint snap, |
| | | 134 | | ICostFunction costFunction, |
| | | 135 | | Half half, |
| | | 136 | | bool asOrigin) |
| | 154 | 137 | | { |
| | | 138 | | // Mirror of the vertex-based DijkstraAlgorithmExtensions.Push contract: |
| | | 139 | | // asOrigin=true → cost computed in the edge's natural direction (tailToHead = true); |
| | | 140 | | // asOrigin=false → cost computed against the edge (tailToHead = false), so the |
| | | 141 | | // backward search reaches "back toward source" with the right weights. |
| | 1078 | 142 | | foreach (var forward in new[] { true, false }) |
| | 308 | 143 | | { |
| | 308 | 144 | | if (!enumerator.MoveTo(snap.EdgeId, forward)) continue; |
| | 308 | 145 | | var (canAccess, _, localAccess, cost, _) = costFunction.Get(enumerator, tailToHead: asOrigin, null); |
| | 342 | 146 | | if (!canAccess || cost <= 0) continue; |
| | 274 | 147 | | var offsetCost = forward |
| | 274 | 148 | | ? cost * (1 - snap.OffsetFactor()) |
| | 274 | 149 | | : cost * snap.OffsetFactor(); |
| | 274 | 150 | | var p = half.Tree.AddVisit(enumerator, leftMain: false, localAccess: localAccess, uint.MaxValue); |
| | 274 | 151 | | half.Heap.Push((p, enumerator.EdgeId, enumerator.Head), offsetCost); |
| | 274 | 152 | | } |
| | 154 | 153 | | } |
| | | 154 | | |
| | | 155 | | private async Task<double?> Step( |
| | | 156 | | RoutingNetwork network, |
| | | 157 | | Half active, |
| | | 158 | | Half other, |
| | | 159 | | bool isForwardHalf, |
| | | 160 | | ICostFunction costFunction, |
| | | 161 | | IsMainNFunc? isMainN, |
| | | 162 | | Func<VertexId, Task<bool>>? settledCb, |
| | | 163 | | CancellationToken cancellationToken) |
| | 1577 | 164 | | { |
| | | 165 | | // Dequeue, skipping already-settled (edge, vertex) labels. |
| | 1577 | 166 | | var entry = active.Heap.Pop(out var cost); |
| | 3768 | 167 | | while (active.Settled.Contains((entry.edge, entry.vertex))) |
| | 2191 | 168 | | { |
| | 2191 | 169 | | if (active.Heap.Count == 0) return cost; |
| | 2191 | 170 | | entry = active.Heap.Pop(out cost); |
| | 2191 | 171 | | } |
| | 1577 | 172 | | if (!active.Settled.Add((entry.edge, entry.vertex))) return cost; |
| | | 173 | | |
| | 1577 | 174 | | var (vertex, edge, forward, _, localAccess, headOrder, _) = active.Tree.GetVisitWithState(entry.pointer); |
| | | 175 | | |
| | | 176 | | // Record in per-vertex settled multimap for meeting checks initiated by the other half. |
| | 1577 | 177 | | if (!active.SettledByVertex.TryGetValue(vertex, out var list)) |
| | 586 | 178 | | { |
| | 586 | 179 | | list = new List<SettledEntry>(2); |
| | 586 | 180 | | active.SettledByVertex[vertex] = list; |
| | 586 | 181 | | } |
| | 1577 | 182 | | list.Add(new SettledEntry(edge, forward, headOrder, entry.pointer, cost)); |
| | | 183 | | |
| | | 184 | | // Settled callback semantics match the unidirectional edge-based: returning true |
| | | 185 | | // means "stop expanding from this vertex" (e.g. outside the max-distance box). |
| | 1577 | 186 | | if (settledCb != null && await settledCb(vertex)) return cost; |
| | 1577 | 187 | | if (cancellationToken.IsCancellationRequested) return cost; |
| | | 188 | | |
| | | 189 | | // Meeting check against already-settled labels at this vertex in the other half. |
| | 1577 | 190 | | this.TryMeet(network, costFunction, isForwardHalf, edge, forward, headOrder, entry.pointer, cost, vertex, other) |
| | | 191 | | |
| | | 192 | | // Expand neighbours. |
| | 1577 | 193 | | var probe = network.GetEdgeEnumerator(); |
| | 1577 | 194 | | if (!probe.MoveTo(vertex)) return cost; |
| | 7215 | 195 | | while (probe.MoveNext()) |
| | 5638 | 196 | | { |
| | 5638 | 197 | | var neighbourEdge = probe.EdgeId; |
| | 7215 | 198 | | if (neighbourEdge == edge) continue; // no U-turn |
| | | 199 | | |
| | | 200 | | // Cost in this half's direction. Forward uses tailToHead=true, backward uses false. |
| | | 201 | | // PreviousEdgeEnumerable provides turn-cost context from the path so far. |
| | 4061 | 202 | | var prev = new PreviousEdgeEnumerable(active.Tree, entry.pointer); |
| | 4061 | 203 | | var (canAccess, _, neighbourLocalAccess, neighbourCost, turnCost) = |
| | 4061 | 204 | | costFunction.Get(probe, tailToHead: isForwardHalf, prev); |
| | 4061 | 205 | | if (!canAccess || neighbourCost is >= double.MaxValue or <= 0) continue; |
| | 4087 | 206 | | if (turnCost is >= double.MaxValue or < 0) continue; |
| | | 207 | | |
| | | 208 | | // Per-half access-aware rule: reject prev_main && !curr_main in this half's direction. |
| | 4035 | 209 | | if (isMainN != null) |
| | 4025 | 210 | | { |
| | 4025 | 211 | | var prevMain = IsMain(edge, localAccess, isMainN); |
| | 4025 | 212 | | var currMain = IsMain(neighbourEdge, neighbourLocalAccess, isMainN); |
| | 4029 | 213 | | if (prevMain && !currMain) continue; |
| | 4021 | 214 | | } |
| | | 215 | | |
| | 4031 | 216 | | var totalCost = cost + neighbourCost + turnCost; |
| | 4053 | 217 | | if (totalCost >= _bestCost) continue; |
| | | 218 | | |
| | 4009 | 219 | | var neighbourPointer = active.Tree.AddVisit(probe, leftMain: false, localAccess: neighbourLocalAccess, entry |
| | | 220 | | |
| | | 221 | | // Meeting check against the other half's settled set BEFORE pushing — mirrors the |
| | | 222 | | // existing vertex-based pattern's OnQueued hook. |
| | 4009 | 223 | | this.TryMeet(network, costFunction, isForwardHalf, neighbourEdge, probe.Forward, probe.HeadOrder, |
| | 4009 | 224 | | neighbourPointer, totalCost, probe.Head, other); |
| | | 225 | | |
| | 4009 | 226 | | active.Heap.Push((neighbourPointer, neighbourEdge, probe.Head), totalCost); |
| | 4009 | 227 | | } |
| | | 228 | | |
| | 1577 | 229 | | return cost; |
| | 1577 | 230 | | } |
| | | 231 | | |
| | | 232 | | private void TryMeet( |
| | | 233 | | RoutingNetwork network, |
| | | 234 | | ICostFunction costFunction, |
| | | 235 | | bool isForwardHalf, |
| | | 236 | | EdgeId edge, |
| | | 237 | | bool forward, |
| | | 238 | | byte? headOrder, |
| | | 239 | | uint pointer, |
| | | 240 | | double cost, |
| | | 241 | | VertexId vertex, |
| | | 242 | | Half other) |
| | 5586 | 243 | | { |
| | 11028 | 244 | | if (!other.SettledByVertex.TryGetValue(vertex, out var settledList)) return; |
| | | 245 | | |
| | 842 | 246 | | foreach (var entry in settledList) |
| | 205 | 247 | | { |
| | 236 | 248 | | if (entry.Edge == edge) continue; // U-turn |
| | | 249 | | |
| | | 250 | | // Quick early-out before computing the turn cost. |
| | 174 | 251 | | var combinedNoTurn = cost + entry.Cost; |
| | 315 | 252 | | if (combinedNoTurn >= _bestCost) continue; |
| | | 253 | | |
| | | 254 | | // Determine the path-incoming and path-outgoing edge at the meeting vertex: |
| | | 255 | | // - Path-incoming is the FORWARD half's settled edge at V (forward arrived here via it). |
| | | 256 | | // - Path-outgoing is the BACKWARD half's settled edge at V (path order continues via it |
| | | 257 | | // toward target; backward search came from target via that edge). |
| | | 258 | | // When the active half is forward, `edge` is path-incoming and `entry.Edge` is outgoing; |
| | | 259 | | // when active half is backward, the roles swap. |
| | | 260 | | EdgeId pathIncoming; |
| | | 261 | | byte? pathIncomingHeadOrder; |
| | | 262 | | EdgeId pathOutgoing; |
| | | 263 | | bool pathOutgoingForwardFromOther; |
| | 33 | 264 | | if (isForwardHalf) |
| | 5 | 265 | | { |
| | 5 | 266 | | pathIncoming = edge; |
| | 5 | 267 | | pathIncomingHeadOrder = headOrder; |
| | 5 | 268 | | pathOutgoing = entry.Edge; |
| | 5 | 269 | | pathOutgoingForwardFromOther = entry.Forward; |
| | 5 | 270 | | } |
| | | 271 | | else |
| | 28 | 272 | | { |
| | 28 | 273 | | pathIncoming = entry.Edge; |
| | 28 | 274 | | pathIncomingHeadOrder = entry.HeadOrder; |
| | 28 | 275 | | pathOutgoing = edge; |
| | 28 | 276 | | pathOutgoingForwardFromOther = forward; |
| | 28 | 277 | | } |
| | | 278 | | |
| | 33 | 279 | | var turnCost = TurnCostAtMeeting(network, costFunction, vertex, |
| | 33 | 280 | | pathIncoming, pathIncomingHeadOrder, |
| | 33 | 281 | | pathOutgoing, pathOutgoingForwardFromOther); |
| | 49 | 282 | | if (turnCost is >= double.MaxValue or < 0) continue; |
| | | 283 | | |
| | 17 | 284 | | var combined = combinedNoTurn + turnCost; |
| | 17 | 285 | | if (combined >= _bestCost) continue; |
| | | 286 | | |
| | 17 | 287 | | _bestCost = combined; |
| | 17 | 288 | | if (isForwardHalf) |
| | 4 | 289 | | { |
| | 4 | 290 | | _bestForward = pointer; |
| | 4 | 291 | | _bestBackward = entry.Pointer; |
| | 4 | 292 | | } |
| | | 293 | | else |
| | 13 | 294 | | { |
| | 13 | 295 | | _bestForward = entry.Pointer; |
| | 13 | 296 | | _bestBackward = pointer; |
| | 13 | 297 | | } |
| | 17 | 298 | | } |
| | 5586 | 299 | | } |
| | | 300 | | |
| | | 301 | | /// <summary> |
| | | 302 | | /// Turn cost at the meeting vertex from the path-incoming edge to the path-outgoing edge. |
| | | 303 | | /// The backward search's enumerator visited <paramref name="pathOutgoing"/> with V as the |
| | | 304 | | /// head; in path order V is the tail of pathOutgoing, so the path-outgoing traversal is |
| | | 305 | | /// the opposite of the backward enumerator's direction. |
| | | 306 | | /// </summary> |
| | | 307 | | private static double TurnCostAtMeeting( |
| | | 308 | | RoutingNetwork network, |
| | | 309 | | ICostFunction costFunction, |
| | | 310 | | VertexId vertex, |
| | | 311 | | EdgeId pathIncoming, |
| | | 312 | | byte? pathIncomingHeadOrder, |
| | | 313 | | EdgeId pathOutgoing, |
| | | 314 | | bool pathOutgoingForwardFromOther) |
| | 33 | 315 | | { |
| | 33 | 316 | | var probe = network.GetEdgeEnumerator(); |
| | | 317 | | // Position at the outgoing edge in path-outgoing direction (V is tail). |
| | 33 | 318 | | if (!probe.MoveTo(pathOutgoing, !pathOutgoingForwardFromOther)) return double.MaxValue; |
| | | 319 | | |
| | 33 | 320 | | var previous = pathIncomingHeadOrder.HasValue |
| | 33 | 321 | | ? new (EdgeId edgeId, byte? turn)[] { (pathIncoming, pathIncomingHeadOrder) } |
| | 33 | 322 | | : null; |
| | 33 | 323 | | var (_, _, _, _, turnCost) = costFunction.Get(probe, tailToHead: true, previous); |
| | 33 | 324 | | return turnCost; |
| | 33 | 325 | | } |
| | | 326 | | |
| | | 327 | | private static bool IsMain(EdgeId edgeId, bool localAccess, IsMainNFunc isMainN) |
| | 8050 | 328 | | { |
| | 8050 | 329 | | var verdict = isMainN(edgeId, localAccess); |
| | | 330 | | // Without a leftMain state-bit the bidirectional defaults unknown to "main": the per-half |
| | | 331 | | // rule then doesn't spuriously reject across edges we know nothing about. |
| | 8050 | 332 | | return verdict ?? true; |
| | 8050 | 333 | | } |
| | | 334 | | |
| | | 335 | | private static Path BuildPath(RoutingNetwork network, PathTree tree, uint pointer) |
| | 34 | 336 | | { |
| | 34 | 337 | | var path = new Path(network); |
| | 34 | 338 | | var visit = tree.GetVisit(pointer); |
| | 79 | 339 | | while (true) |
| | 79 | 340 | | { |
| | 79 | 341 | | path.Prepend(visit.edge, visit.forward); |
| | 113 | 342 | | if (visit.previousPointer == uint.MaxValue) break; |
| | 45 | 343 | | visit = tree.GetVisit(visit.previousPointer); |
| | 45 | 344 | | } |
| | 34 | 345 | | return path; |
| | 34 | 346 | | } |
| | | 347 | | } |