/
bidirectional_astar.cc
1429 lines (1258 loc) · 66.3 KB
/
bidirectional_astar.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "thor/bidirectional_astar.h"
#include "baldr/datetime.h"
#include "baldr/directededge.h"
#include "baldr/graphid.h"
#include "midgard/encoded.h"
#include "midgard/logging.h"
#include "sif/edgelabel.h"
#include "sif/recost.h"
#include "thor/alternates.h"
#include <algorithm>
using namespace valhalla::midgard;
using namespace valhalla::baldr;
using namespace valhalla::sif;
namespace {
constexpr uint32_t kInitialEdgeLabelCountBD = 1000000;
// Threshold (seconds) to extend search once the first connection has been found.
// TODO - this is currently set based on some exceptional cases (e.g. routes taking
// the PA Turnpike which have very long edges). Using a metric based on maximum edge
// cost creates large performance drops - so perhaps some other metric can be found?
constexpr float kThresholdDelta = 420.0f;
// Relative cost extension to find alternative routes. It's a multiplier that we apply
// to the optimal route cost in order to get a new cost threshold. This threshold indicates
// an upper bound value cost for alternative routes we're looking for. Due to the fact that
// we can't estimate route cost that goes through some particular edge very precisely, we
// can find alternatives with costs greater than the threshold.
constexpr float kAlternativeCostExtend = 1.2f;
// Maximum number of additional iterations allowed once the first connection has been found.
// For alternative routes we use bigger cost extension than in the case with one route. This
// may lead to a significant increase in the number of iterations (~time). So, we should limit
// iterations in order no to drop performance too much.
constexpr uint32_t kAlternativeIterationsDelta = 100000;
inline float find_percent_along(const valhalla::Location& location, const GraphId& edge_id) {
for (const auto& e : location.correlation().edges()) {
if (e.graph_id() == edge_id)
return e.percent_along();
}
throw std::logic_error("Could not find candidate edge for the location");
}
} // namespace
namespace valhalla {
namespace thor {
// Default constructor
BidirectionalAStar::BidirectionalAStar(const boost::property_tree::ptree& config)
: PathAlgorithm(config.get<uint32_t>("max_reserved_labels_count", kInitialEdgeLabelCountBD),
config.get<bool>("clear_reserved_memory", false)),
extended_search_(config.get<bool>("extended_search", false)) {
cost_threshold_ = 0;
iterations_threshold_ = 0;
desired_paths_count_ = 1;
mode_ = travel_mode_t::kDrive;
access_mode_ = kAutoAccess;
travel_type_ = 0;
cost_diff_ = 0.0f;
pruning_disabled_at_origin_ = false;
pruning_disabled_at_destination_ = false;
ignore_hierarchy_limits_ = false;
}
// Destructor
BidirectionalAStar::~BidirectionalAStar() {
}
// Clear the temporary information generated during path construction.
void BidirectionalAStar::Clear() {
auto reservation = clear_reserved_memory_ ? 0 : max_reserved_labels_count_;
if (edgelabels_forward_.size() > reservation) {
edgelabels_forward_.resize(reservation);
edgelabels_forward_.shrink_to_fit();
}
if (edgelabels_reverse_.size() > reservation) {
edgelabels_reverse_.resize(reservation);
edgelabels_reverse_.shrink_to_fit();
}
edgelabels_forward_.clear();
edgelabels_reverse_.clear();
adjacencylist_forward_.clear();
adjacencylist_reverse_.clear();
edgestatus_forward_.clear();
edgestatus_reverse_.clear();
// Set the ferry flag to false
has_ferry_ = false;
// Set not thru pruning to true
not_thru_pruning_ = true;
// reset origin & destination pruning states
pruning_disabled_at_origin_ = false;
pruning_disabled_at_destination_ = false;
ignore_hierarchy_limits_ = false;
}
// Initialize the A* heuristic and adjacency lists for both the forward
// and reverse search.
void BidirectionalAStar::Init(const PointLL& origll, const PointLL& destll) {
// Initialize the A* heuristics
float factor = costing_->AStarCostFactor();
astarheuristic_forward_.Init(destll, factor);
astarheuristic_reverse_.Init(origll, factor);
// Reserve size for edge labels - do this here rather than in constructor so
// to limit how much extra memory is used for persistent objects
edgelabels_forward_.reserve(std::min(max_reserved_labels_count_, kInitialEdgeLabelCountBD));
edgelabels_reverse_.reserve(std::min(max_reserved_labels_count_, kInitialEdgeLabelCountBD));
// Construct adjacency list and initialize edge status lookup.
// Set bucket size and cost range based on DynamicCost.
const uint32_t bucketsize = costing_->UnitSize();
const float range = kBucketCount * bucketsize;
const float mincostf = astarheuristic_forward_.Get(origll);
adjacencylist_forward_.reuse(mincostf, range, bucketsize, &edgelabels_forward_);
const float mincostr = astarheuristic_reverse_.Get(destll);
adjacencylist_reverse_.reuse(mincostr, range, bucketsize, &edgelabels_reverse_);
edgestatus_forward_.clear();
edgestatus_reverse_.clear();
// Set the cost diff between forward and reverse searches (due to distance
// approximator differences). This is used to "even" the forward and reverse
// searches.
cost_diff_ = mincostf - mincostr;
// Initialize best connections as having none
best_connections_ = {};
// Set the cost threshold to the maximum float value. Once the initial connection is found
// the threshold is set.
cost_threshold_ = std::numeric_limits<float>::max();
iterations_threshold_ = std::numeric_limits<uint32_t>::max();
// Support for hierarchy transitions
hierarchy_limits_forward_ = costing_->GetHierarchyLimits();
hierarchy_limits_reverse_ = costing_->GetHierarchyLimits();
bool ignore_forward_limits =
std::all_of(hierarchy_limits_forward_.begin() + 1,
hierarchy_limits_forward_.begin() + TileHierarchy::levels().size(),
[](const HierarchyLimits& limits) {
return limits.max_up_transitions == kUnlimitedTransitions;
});
bool ignore_reverse_limits =
std::all_of(hierarchy_limits_reverse_.begin() + 1,
hierarchy_limits_reverse_.begin() + TileHierarchy::levels().size(),
[](const HierarchyLimits& limits) {
return limits.max_up_transitions == kUnlimitedTransitions;
});
// Set this flag to 'true' if we can expand edges at all hierarchy levels without limits
ignore_hierarchy_limits_ = ignore_forward_limits && ignore_reverse_limits;
}
// Runs in the inner loop of `Expand`, essentially evaluating if
// the edge described in `meta` should be placed on the stack
// as well as doing just that.
//
// Returns false if uturns are allowed.
// Returns true if we will expand or have expanded from this edge. In that case we disallow uturns.
// Some edges we won't expand from, but we will still put them on the adjacency list in order to
// connect the forward and reverse paths. In that case we return false to allow uturns only if this
// edge is a not-thru edge that will be pruned.
//
template <const ExpansionType expansion_direction>
inline bool BidirectionalAStar::ExpandInner(baldr::GraphReader& graphreader,
const sif::BDEdgeLabel& pred,
const baldr::DirectedEdge* opp_pred_edge,
const baldr::NodeInfo* nodeinfo,
const uint32_t pred_idx,
const EdgeMetadata& meta,
uint32_t& shortcuts,
const graph_tile_ptr& tile,
const baldr::TimeInfo& time_info) {
// Skip if this is a regular edge superseded by a shortcut.
if (shortcuts & meta.edge->superseded()) {
return false;
}
graph_tile_ptr t2 = nullptr;
baldr::GraphId opp_edge_id;
const auto get_opp_edge_data = [&t2, &opp_edge_id, &graphreader, &meta, &tile]() {
// Get end node tile, opposing edge Id, and opposing directed edge.
t2 = meta.edge->leaves_tile() ? graphreader.GetGraphTile(meta.edge->endnode()) : tile;
if (t2 == nullptr) {
return false;
}
opp_edge_id = t2->GetOpposingEdgeId(meta.edge);
return true;
};
constexpr bool FORWARD = expansion_direction == ExpansionType::forward;
auto& hierarchy_limits = FORWARD ? hierarchy_limits_forward_ : hierarchy_limits_reverse_;
// Skip shortcut edges until we have stopped expanding on the next level. Use regular
// edges while still expanding on the next level since we can still transition down to
// that level. If using a shortcut, set the shortcuts mask.
if (meta.edge->is_shortcut()) {
// Skip shortcuts if hierarchy limits are disabled
if (ignore_hierarchy_limits_ || !get_opp_edge_data())
return false;
const auto& opp_edgestatus = FORWARD ? edgestatus_reverse_ : edgestatus_forward_;
const auto opp_edge_set = opp_edgestatus.Get(opp_edge_id).set();
// Synchronize shortcuts for both directions. If this shortcut has been already
// encountered on the opposing search we should do the same now: skip or traverse.
if ((opp_edge_set != EdgeSet::kSkipped &&
hierarchy_limits[meta.edge_id.level() + 1].StopExpanding(pred.distance())) ||
opp_edge_set == EdgeSet::kPermanent || opp_edge_set == EdgeSet::kTemporary) {
shortcuts |= meta.edge->shortcut();
} else {
// Mark this edge as "skipped".
*meta.edge_status = {EdgeSet::kSkipped, 0};
return false;
}
}
// Skip this edge if edge is permanently labeled (best path already found
// to this directed edge), if no access is allowed (based on costing method),
// or if a complex restriction prevents transition onto this edge.
if (meta.edge_status->set() == EdgeSet::kPermanent) {
return true; // This is an edge we _could_ have expanded, so return true
}
const baldr::DirectedEdge* opp_edge = nullptr;
if (!FORWARD) {
// Check the access mode and skip this edge if access is not allowed in the reverse
// direction. This avoids the (somewhat expensive) retrieval of the opposing directed
// edge when no access is allowed in the reverse direction.
if (!(meta.edge->reverseaccess() & access_mode_)) {
return false;
}
if (t2 == nullptr && !get_opp_edge_data()) {
return false;
}
opp_edge = t2->directededge(opp_edge_id);
}
// Skip this edge if no access is allowed (based on costing method)
// or if a complex restriction prevents transition onto this edge.
// if its not time dependent set to 0 for Allowed and Restricted methods below
const uint64_t localtime = time_info.valid ? time_info.local_time : 0;
uint8_t restriction_idx = -1;
if (FORWARD) {
// Why is is_dest false?
// We have to consider next cases:
// 1) At least one step of reverse search was done -> forward search will never reach the
// destination edge. 2) There were no steps of the reverse search -> the destination edge is a
// connection edge.
// We can set is_dest incorrectly in the second case, but it is the rare case.
// The result path will be correct, because there are cosing.Allowed calls inside recost_forward
// function in second time.
if (!costing_->Allowed(meta.edge, false, pred, tile, meta.edge_id, localtime,
time_info.timezone_index, restriction_idx) ||
costing_->Restricted(meta.edge, pred, edgelabels_forward_, tile, meta.edge_id, true,
&edgestatus_forward_, localtime, time_info.timezone_index)) {
return false;
}
} else {
if (!costing_->AllowedReverse(meta.edge, pred, opp_edge, t2, opp_edge_id, localtime,
time_info.timezone_index, restriction_idx) ||
costing_->Restricted(meta.edge, pred, edgelabels_reverse_, tile, meta.edge_id, false,
&edgestatus_reverse_, localtime, time_info.timezone_index)) {
return false;
}
}
// Get cost
uint8_t flow_sources;
sif::Cost newcost =
pred.cost() + (FORWARD ? costing_->EdgeCost(meta.edge, tile, time_info, flow_sources)
: costing_->EdgeCost(opp_edge, t2, time_info, flow_sources));
// Separate out transition cost.
sif::Cost transition_cost =
FORWARD ? costing_->TransitionCost(meta.edge, nodeinfo, pred)
: costing_->TransitionCostReverse(meta.edge->localedgeidx(), nodeinfo, opp_edge,
opp_pred_edge,
static_cast<bool>(flow_sources & kDefaultFlowMask),
pred.internal_turn());
newcost += transition_cost;
// Check if edge is temporarily labeled and this path has less cost. If
// less cost the predecessor is updated and the sort cost is decremented
// by the difference in real cost (A* heuristic doesn't change)
if (meta.edge_status->set() == EdgeSet::kTemporary) {
BDEdgeLabel& lab = FORWARD ? edgelabels_forward_[meta.edge_status->index()]
: edgelabels_reverse_[meta.edge_status->index()];
if (newcost.cost < lab.cost().cost) {
float newsortcost = lab.sortcost() - (lab.cost().cost - newcost.cost);
if (FORWARD) {
adjacencylist_forward_.decrease(meta.edge_status->index(), newsortcost);
} else {
adjacencylist_reverse_.decrease(meta.edge_status->index(), newsortcost);
}
lab.Update(pred_idx, newcost, newsortcost, transition_cost, restriction_idx);
}
// Returning true since this means we approved the edge
return true;
}
// Get end node tile (skip if tile is not found) and opposing edge Id
if (t2 == nullptr && !get_opp_edge_data())
return false;
// Find the sort cost (with A* heuristic) using the lat,lng at the
// end node of the directed edge.
float dist = 0.0f;
float sortcost =
newcost.cost + (FORWARD
? astarheuristic_forward_.Get(t2->get_node_ll(meta.edge->endnode()), dist)
: astarheuristic_reverse_.Get(t2->get_node_ll(meta.edge->endnode()), dist));
// not_thru_pruning_ is only set to false on the 2nd pass in route_action.
// NOTE(nils): not_thru_pruning() will be false for the correlated (i.e. "first") edges as pred. if
// the current edge is also not_thru we won't prune in the next round. if the current edge is not a
// not_thru we will start pruning next round. that ensures that we can start on a not_thru edge and
// continue on other not_thru edges before pruning.
bool thru = not_thru_pruning_ ? (pred.not_thru_pruning() || !meta.edge->not_thru()) : false;
// Add edge label, add to the adjacency list and set edge status
uint32_t idx = 0;
if (FORWARD) {
idx = edgelabels_forward_.size();
if (hierarchy_limits_forward_[meta.edge_id.level()].max_up_transitions != kUnlimitedTransitions) {
// Override distance to the destination with a distance from the origin.
// It will be used by hierarchy limits
dist = astarheuristic_reverse_.GetDistance(t2->get_node_ll(meta.edge->endnode()));
}
edgelabels_forward_.emplace_back(pred_idx, meta.edge_id, opp_edge_id, meta.edge, newcost,
sortcost, dist, mode_, transition_cost, thru,
(pred.closure_pruning() || !costing_->IsClosed(meta.edge, tile)),
static_cast<bool>(flow_sources & kDefaultFlowMask),
costing_->TurnType(pred.opp_local_idx(), nodeinfo, meta.edge),
restriction_idx);
adjacencylist_forward_.add(idx);
} else {
idx = edgelabels_reverse_.size();
if (hierarchy_limits_reverse_[meta.edge_id.level()].max_up_transitions != kUnlimitedTransitions) {
// Override distance to the origin with a distance from the destination.
// It will be used by hierarchy limits
dist = astarheuristic_forward_.GetDistance(t2->get_node_ll(meta.edge->endnode()));
}
edgelabels_reverse_.emplace_back(pred_idx, meta.edge_id, opp_edge_id, meta.edge, newcost,
sortcost, dist, mode_, transition_cost, thru,
(pred.closure_pruning() || !costing_->IsClosed(meta.edge, tile)),
static_cast<bool>(flow_sources & kDefaultFlowMask),
costing_->TurnType(meta.edge->localedgeidx(), nodeinfo, opp_edge,
opp_pred_edge),
restriction_idx);
adjacencylist_reverse_.add(idx);
}
*meta.edge_status = {EdgeSet::kTemporary, idx};
// setting this edge as reached
if (expansion_callback_) {
expansion_callback_(graphreader, FORWARD ? meta.edge_id : opp_edge_id, "bidirectional_astar", "r",
pred.cost().secs, pred.path_distance(), pred.cost().cost);
}
// we've just added this edge to the queue, but we won't expand from it if it's a not-thru edge that
// will be pruned. In that case we want to allow uturns.
return !(pred.not_thru_pruning() && meta.edge->not_thru());
}
template <const ExpansionType expansion_direction>
bool BidirectionalAStar::Expand(baldr::GraphReader& graphreader,
const baldr::GraphId& node,
sif::BDEdgeLabel& pred,
const uint32_t pred_idx,
const baldr::DirectedEdge* opp_pred_edge,
const baldr::TimeInfo& time_info,
const bool invariant) {
constexpr bool FORWARD = expansion_direction == ExpansionType::forward;
// Get the tile and the node info. Skip if tile is null (can happen
// with regional data sets) or if no access at the node.
graph_tile_ptr tile = graphreader.GetGraphTile(node);
if (tile == nullptr) {
return false;
}
const NodeInfo* nodeinfo = tile->node(node);
// Keep track of superseded edges
uint32_t shortcuts = 0;
// Update the time information even if time is invariant to account for timezones
auto seconds_offset = invariant ? 0.f : pred.cost().secs;
auto offset_time = FORWARD
? time_info.forward(seconds_offset, static_cast<int>(nodeinfo->timezone()))
: time_info.reverse(seconds_offset, static_cast<int>(nodeinfo->timezone()));
auto& edgestatus = FORWARD ? edgestatus_forward_ : edgestatus_reverse_;
// If we encounter a node with an access restriction like a barrier we allow a uturn
if (!costing_->Allowed(nodeinfo)) {
const DirectedEdge* opp_edge = nullptr;
const GraphId opp_edge_id = graphreader.GetOpposingEdgeId(pred.edgeid(), opp_edge, tile);
// Mark the predecessor as a deadend to be consistent with how the
// edgelabels are set when an *actual* deadend (i.e. some dangling OSM geometry)
// is labelled
pred.set_deadend(true);
// Check if edge is null before using it (can happen with regional data sets)
return opp_edge &&
ExpandInner<expansion_direction>(graphreader, pred, opp_pred_edge, nodeinfo, pred_idx,
{opp_edge, opp_edge_id,
edgestatus.GetPtr(opp_edge_id, tile)},
shortcuts, tile, offset_time);
}
bool disable_uturn = false;
EdgeMetadata meta = EdgeMetadata::make(node, nodeinfo, tile, edgestatus);
EdgeMetadata uturn_meta{};
// Expand from end node in <expansion_direction> direction.
for (uint32_t i = 0; i < nodeinfo->edge_count(); ++i, ++meta) {
// Begin by checking if this is the opposing edge to pred.
// If so, it means we are attempting a u-turn. In that case, lets wait with evaluating
// this edge until last. If any other edges were emplaced, it means we should not
// even try to evaluate a u-turn since u-turns should only happen for deadends
uturn_meta = pred.opp_local_idx() == meta.edge->localedgeidx() ? meta : uturn_meta;
// Expand but only if this isnt the uturn, we'll try that later if nothing else works out
disable_uturn =
(pred.opp_local_idx() != meta.edge->localedgeidx() &&
ExpandInner<expansion_direction>(graphreader, pred, opp_pred_edge, nodeinfo, pred_idx, meta,
shortcuts, tile, offset_time)) ||
disable_uturn;
}
// Handle transitions - expand from the end node of each transition
if (nodeinfo->transition_count() > 0) {
const NodeTransition* trans = tile->transition(nodeinfo->transition_index());
auto& hierarchy_limits = FORWARD ? hierarchy_limits_forward_ : hierarchy_limits_reverse_;
for (uint32_t i = 0; i < nodeinfo->transition_count(); ++i, ++trans) {
// if this is a downward transition (ups are always allowed) AND we are no longer allowed OR
// we cant get the tile at that level (local extracts could have this problem) THEN bail
graph_tile_ptr trans_tile = nullptr;
if ((!trans->up() && !ignore_hierarchy_limits_ &&
hierarchy_limits[trans->endnode().level()].StopExpanding(pred.distance())) ||
!(trans_tile = graphreader.GetGraphTile(trans->endnode()))) {
continue;
}
// setup for expansion at this level
hierarchy_limits[node.level()].up_transition_count += trans->up();
const auto* trans_node = trans_tile->node(trans->endnode());
EdgeMetadata trans_meta =
EdgeMetadata::make(trans->endnode(), trans_node, trans_tile, edgestatus);
uint32_t trans_shortcuts = 0;
// expand the edges from this node at this level
for (uint32_t i = 0; i < trans_node->edge_count(); ++i, ++trans_meta) {
disable_uturn =
ExpandInner<expansion_direction>(graphreader, pred, opp_pred_edge, trans_node, pred_idx,
trans_meta, trans_shortcuts, trans_tile, offset_time) ||
disable_uturn;
}
}
}
// Now, after having looked at all the edges, including edges on other levels,
// we can say if this is a deadend or not, and if so, evaluate the uturn-edge (if it exists)
if (!disable_uturn && uturn_meta) {
// If we found no suitable edge to add, it means we're at a deadend
// so lets go back and re-evaluate a potential u-turn
pred.set_deadend(true);
// TODO Is there a shortcut that supersedes our u-turn?
// Decide if we should expand a shortcut or the non-shortcut edge...
// Expand the uturn possiblity
disable_uturn =
ExpandInner<expansion_direction>(graphreader, pred, opp_pred_edge, nodeinfo, pred_idx,
uturn_meta, shortcuts, tile, offset_time) ||
disable_uturn;
}
return disable_uturn;
}
// Calculate best path using bi-directional A*. No hierarchies or time
// dependencies are used. Suitable for pedestrian routes (and bicycle?).
std::vector<std::vector<PathInfo>>
BidirectionalAStar::GetBestPath(valhalla::Location& origin,
valhalla::Location& destination,
GraphReader& graphreader,
const sif::mode_costing_t& mode_costing,
const sif::travel_mode_t mode,
const Options& options) {
// Set the mode and costing
mode_ = mode;
costing_ = mode_costing[static_cast<uint32_t>(mode_)];
travel_type_ = costing_->travel_type();
access_mode_ = costing_->access_mode();
desired_paths_count_ = 1;
if (options.has_alternates_case() && options.alternates())
desired_paths_count_ += options.alternates();
// Initialize - create adjacency list, edgestatus support, A*, etc.
PointLL origin_new(origin.correlation().edges(0).ll().lng(),
origin.correlation().edges(0).ll().lat());
PointLL destination_new(destination.correlation().edges(0).ll().lng(),
destination.correlation().edges(0).ll().lat());
Init(origin_new, destination_new);
// we use a non varying time for all time dependent routes until we can figure out how to vary the
// time during the path computation in the bidirectional algorithm
bool invariant = options.date_time_type() != Options::no_time;
// Get time information for forward and backward searches
auto forward_time_info = TimeInfo::make(origin, graphreader, &tz_cache_);
auto reverse_time_info = TimeInfo::make(destination, graphreader, &tz_cache_);
// When a timedependent route is too long in distance it gets sent to this algorithm. It used to be
// the case that this algorithm called EdgeCost without a time component. This would result in
// timedependent routes falling back to time independent routing. Now that this algorithm is time
// aware we will be tracking time in one direction of the search. To revert to previous behavior
// you can uncomment the code below and get a time independent route in the fallback scenario.
// if (!invariant) {
// auto o = origin; o.mutable_date_time()->clear();
// forward_time_info = TimeInfo::make(o, graphreader, &tz_cache_);
// auto d = destination; d.mutable_date_time()->clear();
// reverse_time_info = TimeInfo::make(d, graphreader, &tz_cache_);
// }
// Set origin and destination locations - seeds the adj. lists
// Note: because we can correlate to more than one place for a given
// PathLocation using edges.front here means we are only setting the
// heuristics to one of them alternate paths using the other correlated
// points to may be harder to find
SetOrigin(graphreader, origin, forward_time_info);
SetDestination(graphreader, destination, reverse_time_info);
// Update hierarchy limits
if (!ignore_hierarchy_limits_)
ModifyHierarchyLimits();
// Find shortest path. Switch between a forward direction and a reverse
// direction search based on the current costs. Alternating like this
// prevents one tree from expanding much more quickly (if in a sparser
// portion of the graph) rather than strictly alternating.
// TODO - CostMatrix alternates, maybe should try alternating here?
int n = 0;
uint32_t forward_pred_idx, reverse_pred_idx;
BDEdgeLabel fwd_pred, rev_pred;
bool expand_forward = true;
bool expand_reverse = true;
while (true) {
// Allow this process to be aborted
if (interrupt && (++n % kInterruptIterationsInterval) == 0) {
(*interrupt)();
}
// Terminate if the iterations threshold has been exceeded.
if ((edgelabels_reverse_.size() + edgelabels_forward_.size()) > iterations_threshold_) {
return FormPath(graphreader, options, origin, destination, forward_time_info);
}
// Get the next predecessor (based on which direction was expanded in prior step)
if (expand_forward) {
forward_pred_idx = adjacencylist_forward_.pop();
if (forward_pred_idx != kInvalidLabel) {
fwd_pred = edgelabels_forward_[forward_pred_idx];
// Forward path to this edge can't be improved, so we can settle it right now.
edgestatus_forward_.Update(fwd_pred.edgeid(), EdgeSet::kPermanent);
// Terminate if the cost threshold has been exceeded.
if (fwd_pred.sortcost() + cost_diff_ > cost_threshold_) {
return FormPath(graphreader, options, origin, destination, forward_time_info);
}
// Check if the edge on the forward search connects to a settled edge on the
// reverse search tree. Do not expand further past this edge since it will just
// result in other connections. Handle special edge case when we encountered the
// destination edge that wasn't still pulled out of the queue.
const auto opp_status = edgestatus_reverse_.Get(fwd_pred.opp_edgeid());
if (opp_status.set() == EdgeSet::kPermanent ||
(opp_status.set() == EdgeSet::kTemporary &&
edgelabels_reverse_[opp_status.index()].predecessor() == kInvalidLabel)) {
if (SetForwardConnection(graphreader, fwd_pred) &&
opp_status.set() == EdgeSet::kPermanent) {
continue;
}
}
} else {
// Search is exhausted. If a connection has been found, return it
if (!best_connections_.empty()) {
return FormPath(graphreader, options, origin, destination, forward_time_info);
}
LOG_ERROR("Forward search exhausted: n = " + std::to_string(edgelabels_forward_.size()) +
"," + std::to_string(edgelabels_reverse_.size()));
// Search might've exhausted if it hit a closure or not_thru edge leading upto the
// destination. Instead of tracking if any of the other edges is within a not_thru/closure
// region (indicated by the pruning state of the edge label), we simply check if we started
// from the other end on a closed or not_thru edge. If either is true, we extend the search in
// the other direction (if allowed by the config option "thor.extended_search")
//
// Caveat: This assumption is not true if for eg the search from other end has pruning turned
// on later, causing us to needlessly expand when we could have aborted sooner. However, it
// ensures that most impossible route will fail fast provided one of the locations didn't
// start from a not_thru/closed edge
// TODO(nils):
// 1. extended_search doesn't seem to do what it's documented to do; it will force both
// both directions to be eventually exhausted, no matter if the other direction
// started on a closure/not_thru
if (!extended_search_ || !pruning_disabled_at_destination_) {
return {};
}
LOG_DEBUG("Extending search in reverse direction. Destination pruning disabled? " +
std::to_string(pruning_disabled_at_destination_));
}
}
if (expand_reverse) {
reverse_pred_idx = adjacencylist_reverse_.pop();
if (reverse_pred_idx != kInvalidLabel) {
rev_pred = edgelabels_reverse_[reverse_pred_idx];
// Reverse path to this edge can't be improved, so we can settle it right now.
edgestatus_reverse_.Update(rev_pred.edgeid(), EdgeSet::kPermanent);
// Terminate if the cost threshold has been exceeded.
if (rev_pred.sortcost() > cost_threshold_) {
return FormPath(graphreader, options, origin, destination, forward_time_info);
}
// Check if the edge on the reverse search connects to a settled edge on the
// forward search tree. Do not expand further past this edge since it will just
// result in other connections. Handle special edge case when we encountered the
// destination edge that wasn't still pulled out of the queue.
const auto opp_status = edgestatus_forward_.Get(rev_pred.opp_edgeid());
if (opp_status.set() == EdgeSet::kPermanent ||
(opp_status.set() == EdgeSet::kTemporary &&
edgelabels_forward_[opp_status.index()].predecessor() == kInvalidLabel)) {
if (SetReverseConnection(graphreader, rev_pred) &&
opp_status.set() == EdgeSet::kPermanent) {
continue;
}
}
} else {
// Search is exhausted. If a connection has been found, return it
if (!best_connections_.empty()) {
return FormPath(graphreader, options, origin, destination, forward_time_info);
}
LOG_ERROR("Reverse search exhausted: n = " + std::to_string(edgelabels_reverse_.size()) +
"," + std::to_string(edgelabels_forward_.size()));
// Search might've exhausted if it hit a closure or not_thru edge leading upto the origin.
// Instead of tracking if any of the other edges is within a not_thru/closure region
// (indicated by the pruning state of the edge label), we simply check if we started from the
// other end on a closed or not_thru edge. If either is true, we extend the search in the
// other direction (if allowed by the config option "thor.extended_search")
//
// Caveat: This assumption is not true if for eg the search from other end has pruning turned
// on later, causing us to needlessly expand when we could have aborted sooner. However, it
// ensures that most impossible route will fail fast provided one of the locations didn't end
// on a not_thru/closed edge
if (!extended_search_ || !pruning_disabled_at_origin_) {
return {};
}
LOG_DEBUG("Extending search in forward direction. Origin pruning disabled? " +
std::to_string(pruning_disabled_at_origin_));
}
}
bool forward_exhausted = forward_pred_idx == kInvalidLabel;
bool reverse_exhausted = reverse_pred_idx == kInvalidLabel;
// If both directions have exhausted, we've failed to find a route. Abort
if (forward_exhausted && reverse_exhausted) {
LOG_ERROR("Bi-directional route failure - search exhausted: n = " +
std::to_string(edgelabels_forward_.size()) + "," +
std::to_string(edgelabels_reverse_.size()));
return {};
}
// Exhaust hierarchy limits simultaneously in both directions. As soon as forward/reverse
// search exhausts limits on the particular level - it should stop and wait until reverse/forward
// search exhausts limits on the same hierarchy level. This logic ensures local optimality near
// the origin and destination and provides valid conditions for the reach-based pruning.
bool force_forward = false;
bool force_reverse = false;
if (!ignore_hierarchy_limits_) {
for (size_t level = TileHierarchy::levels().size() - 1; level > 0; --level) {
if (hierarchy_limits_reverse_[level].StopExpanding(rev_pred.distance()) &&
!hierarchy_limits_forward_[level].StopExpanding(fwd_pred.distance())) {
force_forward = true;
break;
} else if (hierarchy_limits_forward_[level].StopExpanding(fwd_pred.distance()) &&
!hierarchy_limits_reverse_[level].StopExpanding(rev_pred.distance())) {
force_reverse = true;
break;
}
}
}
// Expand from the search direction with lower sort cost
// Note: If one direction is exhausted, we force search in the remaining
// direction
if (!forward_exhausted &&
((!force_reverse && (fwd_pred.sortcost() + cost_diff_) < rev_pred.sortcost()) ||
force_forward || reverse_exhausted)) {
// Expand forward - set to get next edge from forward adj. list on the next pass
expand_forward = true;
expand_reverse = false;
// setting this edge as settled
if (expansion_callback_) {
expansion_callback_(graphreader, fwd_pred.edgeid(), "bidirectional_astar", "s",
fwd_pred.cost().secs, fwd_pred.path_distance(), fwd_pred.cost().cost);
}
// Prune path if predecessor is not a through edge or if the maximum
// number of upward transitions has been exceeded on this hierarchy level.
if ((fwd_pred.not_thru() && fwd_pred.not_thru_pruning()) ||
(!ignore_hierarchy_limits_ &&
hierarchy_limits_forward_[fwd_pred.endnode().level()].StopExpanding(
fwd_pred.distance()))) {
continue;
}
// Check if this branch can be pruned. It's implementation of the reach-based pruning technique
// for bidirectional astar: https://repub.eur.nl/pub/16100/ei2009-10.pdf .
if (cost_threshold_ != std::numeric_limits<float>::max() &&
fwd_pred.predecessor() != kInvalidLabel) {
const auto tile = graphreader.GetGraphTile(fwd_pred.endnode());
if (tile != nullptr) {
// Estimate lower bound cost for the shortest path that goes through the current edge.
float route_lower_bound =
edgelabels_forward_[fwd_pred.predecessor()].cost().cost +
fwd_pred.transition_cost().cost + rev_pred.sortcost() -
astarheuristic_reverse_.Get(tile->get_node_ll(fwd_pred.endnode()));
// Prune this edge if estimated lower bound cost exceeds the cost threshold.
if (route_lower_bound > cost_threshold_) {
continue;
}
} else {
// Failed to get tile for the endnode. Skip expansion from this node.
continue;
}
}
// Expand from the end node in forward direction.
Expand<ExpansionType::forward>(graphreader, fwd_pred.endnode(), fwd_pred, forward_pred_idx,
nullptr, forward_time_info, invariant);
} else {
// Expand reverse - set to get next edge from reverse adj. list on the next pass
expand_forward = false;
expand_reverse = true;
// setting this edge as settled, sending the opposing because this is the reverse tree
if (expansion_callback_) {
expansion_callback_(graphreader, rev_pred.opp_edgeid(), "bidirectional_astar", "s",
rev_pred.cost().secs, rev_pred.path_distance(), rev_pred.cost().cost);
}
// Prune path if predecessor is not a through edge
if ((rev_pred.not_thru() && rev_pred.not_thru_pruning()) ||
(!ignore_hierarchy_limits_ &&
hierarchy_limits_reverse_[rev_pred.endnode().level()].StopExpanding(
rev_pred.distance()))) {
continue;
}
// Get the opposing predecessor directed edge. Need to make sure we get
// the correct one if a transition occurred
const auto rev_pred_tile = graphreader.GetGraphTile(rev_pred.opp_edgeid());
if (rev_pred_tile == nullptr) {
continue;
}
const DirectedEdge* opp_pred_edge = rev_pred_tile->directededge(rev_pred.opp_edgeid());
// Check if this branch can be pruned. It's implementation of the reach-based pruning technique
// for bidirectional astar: https://repub.eur.nl/pub/16100/ei2009-10.pdf .
if (cost_threshold_ != std::numeric_limits<float>::max() &&
rev_pred.predecessor() != kInvalidLabel) {
const auto tile = graphreader.GetGraphTile(rev_pred.endnode());
if (tile != nullptr) {
// Estimate lower bound cost for the shortest path that goes through the current edge.
float route_lower_bound =
edgelabels_reverse_[rev_pred.predecessor()].cost().cost +
rev_pred.transition_cost().cost + fwd_pred.sortcost() -
astarheuristic_forward_.Get(tile->get_node_ll(rev_pred.endnode()));
// Prune this edge if estimated lower bound cost exceeds the cost threshold.
if (route_lower_bound > cost_threshold_) {
continue;
}
} else {
// Failed to get tile for the endnode. Skip expansion from this node.
continue;
}
}
// Expand from the end node in reverse direction.
Expand<ExpansionType::reverse>(graphreader, rev_pred.endnode(), rev_pred, reverse_pred_idx,
opp_pred_edge, reverse_time_info, invariant);
}
}
return {}; // If we are here the route failed
}
// The edge on the forward search connects to a reached edge on the reverse
// search tree. Check if this is the best connection so far and set the
// search threshold.
bool BidirectionalAStar::SetForwardConnection(GraphReader& graphreader, const BDEdgeLabel& pred) {
// Find pred on opposite side
GraphId oppedge = pred.opp_edgeid();
EdgeStatusInfo oppedgestatus = edgestatus_reverse_.Get(oppedge);
auto opp_pred = edgelabels_reverse_[oppedgestatus.index()];
// Disallow connections that are part of an uturn on an internal edge
if (pred.internal_turn() != InternalTurn::kNoTurn) {
return false;
}
// Disallow connections that are part of a complex restriction
if (pred.on_complex_rest()) {
// Lets dig deeper and test if we are really triggering these restrictions
// since the complex restriction can span many edges
if (IsBridgingEdgeRestricted(graphreader, edgelabels_forward_, edgelabels_reverse_, pred,
opp_pred, costing_)) {
return false;
}
}
// Get the opposing edge - a candidate shortest path has been found to the
// end node of this directed edge. Get total cost.
float c;
if (pred.predecessor() != kInvalidLabel) {
// Get the start of the predecessor edge on the forward path. Cost is to
// the end this edge, plus the cost to the end of the reverse predecessor,
// plus the transition cost.
c = edgelabels_forward_[pred.predecessor()].cost().cost + opp_pred.cost().cost +
pred.transition_cost().cost;
} else {
// If no predecessor on the forward path get the predecessor on
// the reverse path to form the cost.
uint32_t predidx = opp_pred.predecessor();
float oppcost = (predidx == kInvalidLabel) ? 0 : edgelabels_reverse_[predidx].cost().cost;
c = pred.cost().cost + oppcost + opp_pred.transition_cost().cost;
}
// Set thresholds to extend search
if (cost_threshold_ == std::numeric_limits<float>::max() || c < best_connections_.front().cost) {
if (desired_paths_count_ == 1) {
cost_threshold_ = c + kThresholdDelta;
} else {
// For short routes it may be not enough to use just scale to extend the cost threshold.
// So, we also add the delta to find more alternatives.
// TODO: use different constants to extend the search based on route distance.
cost_threshold_ = kAlternativeCostExtend * c + kThresholdDelta;
iterations_threshold_ =
edgelabels_forward_.size() + edgelabels_reverse_.size() + kAlternativeIterationsDelta;
}
}
// Keep the best ones at the front all others to the back
best_connections_.emplace_back(CandidateConnection{pred.edgeid(), oppedge, c});
if (c < best_connections_.front().cost)
std::swap(best_connections_.front(), best_connections_.back());
// setting this edge as connected
if (expansion_callback_) {
expansion_callback_(graphreader, pred.edgeid(), "bidirectional_astar", "c", pred.cost().secs,
pred.path_distance(), pred.cost().cost);
}
return true;
}
// The edge on the reverse search connects to a reached edge on the forward
// search tree. Check if this is the best connection so far and set the
// search threshold.
bool BidirectionalAStar::SetReverseConnection(GraphReader& graphreader, const BDEdgeLabel& rev_pred) {
GraphId fwd_edge_id = rev_pred.opp_edgeid();
EdgeStatusInfo fwd_edge_status = edgestatus_forward_.Get(fwd_edge_id);
auto fwd_pred = edgelabels_forward_[fwd_edge_status.index()];
// Disallow connections that are part of an uturn on an internal edge
if (rev_pred.internal_turn() != InternalTurn::kNoTurn) {
return false;
}
// Disallow connections that are part of a complex restriction
if (rev_pred.on_complex_rest()) {
// Lets dig deeper and test if we are really triggering these restrictions
// since the complex restriction can span many edges
if (IsBridgingEdgeRestricted(graphreader, edgelabels_forward_, edgelabels_reverse_, fwd_pred,
rev_pred, costing_)) {
return false;
}
}
// Get the opposing edge - a candidate shortest path has been found to the
// end node of this directed edge. Get total cost.
float c;
if (rev_pred.predecessor() != kInvalidLabel) {
// Get the start of the predecessor edge on the reverse path. Cost is to
// the end this edge, plus the cost to the end of the forward predecessor,
// plus the transition cost.
c = edgelabels_reverse_[rev_pred.predecessor()].cost().cost + fwd_pred.cost().cost +
rev_pred.transition_cost().cost;
} else {
// If no predecessor on the reverse path get the predecessor on
// the forward path to form the cost.
uint32_t predidx = fwd_pred.predecessor();
float oppcost = (predidx == kInvalidLabel) ? 0 : edgelabels_forward_[predidx].cost().cost;
c = rev_pred.cost().cost + oppcost + fwd_pred.transition_cost().cost;
}
// Set thresholds to extend search
if (cost_threshold_ == std::numeric_limits<float>::max() || c < best_connections_.front().cost) {
if (desired_paths_count_ == 1) {
cost_threshold_ = c + kThresholdDelta;
} else {
// For short routes it may be not enough to use just scale to extend the cost threshold.
// So, we also add the delta to find more alternatives.
// TODO: use different constants to extend the search based on route distance.
cost_threshold_ = kAlternativeCostExtend * c + kThresholdDelta;
iterations_threshold_ =
edgelabels_forward_.size() + edgelabels_reverse_.size() + kAlternativeIterationsDelta;
}
}
// Keep the best ones at the front all others to the back
best_connections_.emplace_back(CandidateConnection{fwd_edge_id, rev_pred.edgeid(), c});
if (c < best_connections_.front().cost)
std::swap(best_connections_.front(), best_connections_.back());
// setting this edge as connected, sending the opposing because this is the reverse tree
if (expansion_callback_) {
expansion_callback_(graphreader, fwd_edge_id, "bidirectional_astar", "c", fwd_pred.cost().secs,
fwd_pred.path_distance(), fwd_pred.cost().cost);
}
return true;
}
// Add edges at the origin to the forward adjacency list.
void BidirectionalAStar::SetOrigin(GraphReader& graphreader,
valhalla::Location& origin,
const TimeInfo& time_info) {
// Only skip inbound edges if we have other options
bool has_other_edges =
std::any_of(origin.correlation().edges().begin(), origin.correlation().edges().end(),
[](const valhalla::PathEdge& e) { return !e.end_node(); });
// Iterate through edges and add to adjacency list
const NodeInfo* nodeinfo = nullptr;
const NodeInfo* closest_ni = nullptr;
for (const auto& edge : origin.correlation().edges()) {
// If origin is at a node - skip any inbound edge (dist = 1)
if (has_other_edges && edge.end_node()) {
continue;
}
// Disallow any user avoid edges if the avoid location is ahead of the origin along the edge
GraphId edgeid(edge.graph_id());
if (costing_->AvoidAsOriginEdge(edgeid, edge.percent_along())) {
continue;
}
// Get the directed edge
graph_tile_ptr tile = graphreader.GetGraphTile(edgeid);
if (tile == nullptr) {
continue;
}
const DirectedEdge* directededge = tile->directededge(edgeid);
// Get the tile at the end node. Skip if tile not found as we won't be
// able to expand from this origin edge.
graph_tile_ptr endtile = graphreader.GetGraphTile(directededge->endnode());
if (!endtile) {
continue;
}
// Get cost and sort cost (based on distance from endnode of this edge
// to the destination
nodeinfo = endtile->node(directededge->endnode());
uint8_t flow_sources;
Cost cost = costing_->EdgeCost(directededge, tile, time_info, flow_sources) *
(1.0f - edge.percent_along());
// Store a node-info for later timezone retrieval (approximate for closest)
if (closest_ni == nullptr) {
closest_ni = nodeinfo;
}
// We need to penalize this location based on its score (distance in meters from input)
// We assume the slowest speed you could travel to cover that distance to start/end the route
// TODO: assumes 1m/s which is a maximum penalty this could vary per costing model
cost.cost += edge.distance();