/
autocost.cc
1257 lines (1108 loc) · 53.5 KB
/
autocost.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 "sif/autocost.h"
#include "baldr/accessrestriction.h"
#include "baldr/directededge.h"
#include "baldr/graphconstants.h"
#include "baldr/nodeinfo.h"
#include "midgard/constants.h"
#include "midgard/util.h"
#include "proto_conversions.h"
#include "sif/costconstants.h"
#include "sif/dynamiccost.h"
#include "sif/osrm_car_duration.h"
#include <cassert>
#ifdef INLINE_TEST
#include "test.h"
#include "worker.h"
#include <random>
#endif
using namespace valhalla::midgard;
using namespace valhalla::baldr;
namespace valhalla {
namespace sif {
// Default options/values
namespace {
// Base transition costs
constexpr float kDefaultServicePenalty = 75.0f; // Seconds
// Other options
constexpr float kDefaultUseHighways = 0.5f; // Default preference of using a motorway or trunk 0-1
constexpr float kDefaultUseTolls = 0.5f; // Default preference of using toll roads 0-1
constexpr float kDefaultUseTracks = 0.f; // Default preference of using tracks 0-1
constexpr float kDefaultUseDistance = 0.f; // Default preference of using distance vs time 0-1
constexpr uint32_t kDefaultRestrictionProbability = 100; // Default percentage of allowing probable
// restrictions 0% means do not include them
// Default turn costs
constexpr float kTCStraight = 0.5f;
constexpr float kTCSlight = 0.75f;
constexpr float kTCFavorable = 1.0f;
constexpr float kTCFavorableSharp = 1.5f;
constexpr float kTCCrossing = 2.0f;
constexpr float kTCUnfavorable = 2.5f;
constexpr float kTCUnfavorableSharp = 3.5f;
constexpr float kTCReverse = 9.5f;
// How much to favor taxi roads.
constexpr float kTaxiFactor = 0.85f;
// Do not avoid alleys by default
constexpr float kDefaultAlleyFactor = 1.0f;
// How much to favor turn channels
constexpr float kTurnChannelFactor = 0.6f;
// Turn costs based on side of street driving
constexpr float kRightSideTurnCosts[] = {kTCStraight, kTCSlight, kTCFavorable,
kTCFavorableSharp, kTCReverse, kTCUnfavorableSharp,
kTCUnfavorable, kTCSlight};
constexpr float kLeftSideTurnCosts[] = {kTCStraight, kTCSlight, kTCUnfavorable,
kTCUnfavorableSharp, kTCReverse, kTCFavorableSharp,
kTCFavorable, kTCSlight};
constexpr float kMinFactor = 0.1f;
constexpr float kMaxFactor = 100000.0f;
// Default auto attributes
constexpr float kDefaultAutoHeight = 1.6f; // Meters (62.9921 inches)
constexpr float kDefaultAutoWidth = 1.9f; // Meters (74.8031 inches)
// Valid ranges and defaults
constexpr ranged_default_t<float> kAlleyFactorRange{kMinFactor, kDefaultAlleyFactor, kMaxFactor};
constexpr ranged_default_t<float> kUseHighwaysRange{0, kDefaultUseHighways, 1.0f};
constexpr ranged_default_t<float> kUseTollsRange{0, kDefaultUseTolls, 1.0f};
constexpr ranged_default_t<float> kUseDistanceRange{0, kDefaultUseDistance, 1.0f};
constexpr ranged_default_t<float> kAutoHeightRange{0, kDefaultAutoHeight, 10.0f};
constexpr ranged_default_t<float> kAutoWidthRange{0, kDefaultAutoWidth, 10.0f};
constexpr ranged_default_t<uint32_t> kProbabilityRange{0, kDefaultRestrictionProbability, 100};
constexpr float kHighwayFactor[] = {
1.0f, // Motorway
0.5f, // Trunk
0.0f, // Primary
0.0f, // Secondary
0.0f, // Tertiary
0.0f, // Unclassified
0.0f, // Residential
0.0f // Service, other
};
constexpr float kSurfaceFactor[] = {
0.0f, // kPavedSmooth
0.0f, // kPaved
0.0f, // kPaveRough
0.1f, // kCompacted
0.2f, // kDirt
0.5f, // kGravel
1.0f // kPath
};
// The basic costing for an edge is a trade off between time and distance. We allow the user to
// specify which one is more important to them and then we use a linear combination to combine the two
// into a final metric. The problem is that time in seconds and length in meters have two wildly
// different ranges, so the linear combination always favors length vs time. What we do to combat this
// is to change length units into time units by multiplying by the reciprocal of a constant speed.
// This means basically changes the units of distance to be more in the same ballpark as the units of
// time and makes the linear combination make more sense.
constexpr float kInvMedianSpeed = 1.f / 16.f; // about 37mph
BaseCostingOptionsConfig GetBaseCostOptsConfig() {
BaseCostingOptionsConfig cfg{};
// override defaults
cfg.service_penalty_.def = kDefaultServicePenalty;
cfg.use_tracks_.def = kDefaultUseTracks;
return cfg;
}
const BaseCostingOptionsConfig kBaseCostOptsConfig = GetBaseCostOptsConfig();
} // namespace
/**
* Derived class providing dynamic edge costing for "direct" auto routes. This
* is a route that is generally shortest time but uses route hierarchies that
* can result in slightly longer routes that avoid shortcuts on residential
* roads.
*/
class AutoCost : public DynamicCost {
public:
/**
* Construct auto costing. Pass in cost type and costing_options using protocol buffer(pbf).
* @param costing_options pbf with request costing_options.
*/
AutoCost(const Costing& costing_options, uint32_t access_mask = (kAutoAccess | kHOVAccess));
virtual ~AutoCost() {
}
/**
* Does the costing method allow multiple passes (with relaxed hierarchy
* limits).
* @return Returns true if the costing model allows multiple passes.
*/
virtual bool AllowMultiPass() const override {
return true;
}
/**
* Checks if access is allowed for the provided directed edge.
* This is generally based on mode of travel and the access modes
* allowed on the edge. However, it can be extended to exclude access
* based on other parameters such as conditional restrictions and
* conditional access that can depend on time and travel mode.
* @param edge Pointer to a directed edge.
* @param is_dest Is a directed edge the destination?
* @param pred Predecessor edge information.
* @param tile Current tile.
* @param edgeid GraphId of the directed edge.
* @param current_time Current time (seconds since epoch). A value of 0
* indicates the route is not time dependent.
* @param tz_index timezone index for the node
* @return Returns true if access is allowed, false if not.
*/
virtual bool Allowed(const baldr::DirectedEdge* edge,
const bool is_dest,
const EdgeLabel& pred,
const graph_tile_ptr& tile,
const baldr::GraphId& edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const override;
/**
* Checks if access is allowed for an edge on the reverse path
* (from destination towards origin). Both opposing edges (current and
* predecessor) are provided. The access check is generally based on mode
* of travel and the access modes allowed on the edge. However, it can be
* extended to exclude access based on other parameters such as conditional
* restrictions and conditional access that can depend on time and travel
* mode.
* @param edge Pointer to a directed edge.
* @param pred Predecessor edge information.
* @param opp_edge Pointer to the opposing directed edge.
* @param tile Current tile.
* @param edgeid GraphId of the opposing edge.
* @param current_time Current time (seconds since epoch). A value of 0
* indicates the route is not time dependent.
* @param tz_index timezone index for the node
* @return Returns true if access is allowed, false if not.
*/
virtual bool AllowedReverse(const baldr::DirectedEdge* edge,
const EdgeLabel& pred,
const baldr::DirectedEdge* opp_edge,
const graph_tile_ptr& tile,
const baldr::GraphId& opp_edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const override;
/**
* Callback for Allowed doing mode specific restriction checks
*/
virtual bool ModeSpecificAllowed(const baldr::AccessRestriction& restriction) const override;
/**
* Only transit costings are valid for this method call, hence we throw
* @param edge
* @param departure
* @param curr_time
* @return
*/
virtual Cost EdgeCost(const baldr::DirectedEdge*,
const baldr::TransitDeparture*,
const uint32_t) const override {
throw std::runtime_error("AutoCost::EdgeCost does not support transit edges");
}
/**
* Get the cost to traverse the specified directed edge. Cost includes
* the time (seconds) to traverse the edge.
* @param edge Pointer to a directed edge.
* @param tile Graph tile.
* @param time_info Time info about edge passing.
* @return Returns the cost and time (seconds)
*/
virtual Cost EdgeCost(const baldr::DirectedEdge* edge,
const graph_tile_ptr& tile,
const baldr::TimeInfo& time_info,
uint8_t& flow_sources) const override;
/**
* Returns the cost to make the transition from the predecessor edge.
* Defaults to 0. Costing models that wish to include edge transition
* costs (i.e., intersection/turn costs) must override this method.
* @param edge Directed edge (the to edge)
* @param node Node (intersection) where transition occurs.
* @param pred Predecessor edge information.
* @return Returns the cost and time (seconds)
*/
virtual Cost TransitionCost(const baldr::DirectedEdge* edge,
const baldr::NodeInfo* node,
const EdgeLabel& pred) const override;
/**
* Returns the cost to make the transition from the predecessor edge
* when using a reverse search (from destination towards the origin).
* @param idx Directed edge local index
* @param node Node (intersection) where transition occurs.
* @param pred the opposing current edge in the reverse tree.
* @param edge the opposing predecessor in the reverse tree
* @param has_measured_speed Do we have any of the measured speed types set?
* @param internal_turn Did we make an turn on a short internal edge.
* @return Returns the cost and time (seconds)
*/
virtual Cost TransitionCostReverse(const uint32_t idx,
const baldr::NodeInfo* node,
const baldr::DirectedEdge* pred,
const baldr::DirectedEdge* edge,
const bool has_measured_speed,
const InternalTurn internal_turn) const override;
/**
* Get the cost factor for A* heuristics. This factor is multiplied
* with the distance to the destination to produce an estimate of the
* minimum cost to the destination. The A* heuristic must underestimate the
* cost to the destination. So a time based estimate based on speed should
* assume the maximum speed is used to the destination such that the time
* estimate is less than the least possible time along roads.
*/
virtual float AStarCostFactor() const override {
return speedfactor_[top_speed_];
}
/**
* Get the current travel type.
* @return Returns the current travel type.
*/
virtual uint8_t travel_type() const override {
return static_cast<uint8_t>(type_);
}
bool IsHOVAllowed(const baldr::DirectedEdge* edge) const {
// A non-hov edge means hov is allowed.
if (!edge->is_hov_only())
return true;
// The edge is either HOV-2 or HOV-3 from this point forward.
// If include_hov3 is set we can route onto both HOV-2 and HOV-3 edges
if (include_hov3_)
return true;
// If include_hov2 is set we can route onto HOV-2 edges.
if (include_hov2_ && (edge->hov_type() == baldr::HOVEdgeType::kHOV2))
return true;
// If include_hot is set we can route onto HOT edges (HOV and tolled).
if (include_hot_ && edge->toll())
return true;
return false;
}
/**
* Function to be used in location searching which will
* exclude and allow ranking results from the search by looking at each
* edges attribution and suitability for use as a location by the travel
* mode used by the costing method. It's also used to filter
* edges not usable / inaccessible by automobile.
*/
virtual bool Allowed(const baldr::DirectedEdge* edge,
const graph_tile_ptr& tile,
uint16_t disallow_mask = kDisallowNone) const override {
bool allow_closures = (!filter_closures_ && !(disallow_mask & kDisallowClosure)) ||
!(flow_mask_ & kCurrentFlowMask);
return DynamicCost::Allowed(edge, tile, disallow_mask) && !edge->bss_connection() &&
(allow_closures || !tile->IsClosed(edge)) && IsHOVAllowed(edge);
}
// Hidden in source file so we don't need it to be protected
// We expose it within the source file for testing purposes
public:
VehicleType type_; // Vehicle type: car (default), motorcycle, etc
std::vector<float> speedfactor_;
float density_factor_[16]; // Density factor
float highway_factor_; // Factor applied when road is a motorway or trunk
float alley_factor_; // Avoid alleys factor.
float toll_factor_; // Factor applied when road has a toll
float surface_factor_; // How much the surface factors are applied.
float distance_factor_; // How much distance factors in overall favorability
float inv_distance_factor_; // How much time factors in overall favorability
// Vehicle attributes (used for special restrictions and costing)
float height_; // Vehicle height in meters
float width_; // Vehicle width in meters
// Density factor used in edge transition costing
std::vector<float> trans_density_factor_;
};
// Constructor
AutoCost::AutoCost(const Costing& costing, uint32_t access_mask)
: DynamicCost(costing, TravelMode::kDrive, access_mask, true),
trans_density_factor_{1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.1f, 1.2f, 1.3f,
1.4f, 1.6f, 1.9f, 2.2f, 2.5f, 2.8f, 3.1f, 3.5f} {
const auto& costing_options = costing.options();
// Get the vehicle type - enter as string and convert to enum.
// Used to set the surface factor - penalize some roads based on surface type.
surface_factor_ = 0.5f;
type_ = VehicleType::kCar;
// Get the base transition costs
get_base_costs(costing);
// Get alley factor from costing options.
alley_factor_ = costing_options.alley_factor();
// Preference to use highways. Is a value from 0 to 1
// Factor for highway use - use a non-linear factor with values at 0.5 being neutral (factor
// of 0). Values between 0.5 and 1 slowly decrease to a maximum of -0.125 (to slightly prefer
// highways) while values between 0.5 to 0 slowly increase to a maximum of kMaxHighwayBiasFactor
// to avoid/penalize highways.
float use_highways = costing_options.use_highways();
if (use_highways >= 0.5f) {
float f = (0.5f - use_highways);
highway_factor_ = f * f * f;
} else {
float f = 1.0f - (use_highways * 2.0f);
highway_factor_ = kMaxHighwayBiasFactor * (f * f);
}
// Preference for distance vs time
distance_factor_ = costing_options.use_distance() * kInvMedianSpeed;
inv_distance_factor_ = 1.f - costing_options.use_distance();
// Preference to use toll roads (separate from toll booth penalty). Sets a toll
// factor. A toll factor of 0 would indicate no adjustment to weighting for toll roads.
// use_tolls = 1 would reduce weighting slightly (a negative delta) while
// use_tolls = 0 would penalize (positive delta to weighting factor).
float use_tolls = costing_options.use_tolls();
toll_factor_ = use_tolls < 0.5f ? (4.0f - 8 * use_tolls) : // ranges from 4 to 0
(0.5f - use_tolls) * 0.03f; // ranges from 0 to -0.15
include_hot_ = costing_options.include_hot();
include_hov2_ = costing_options.include_hov2();
include_hov3_ = costing_options.include_hov3();
// Get the vehicle attributes
height_ = costing_options.height();
width_ = costing_options.width();
// Create speed cost table
speedfactor_.resize(kMaxSpeedKph + 1, 0);
speedfactor_[0] = kSecPerHour; // TODO - what to make speed=0?
for (uint32_t s = 1; s <= kMaxSpeedKph; s++) {
speedfactor_[s] = (kSecPerHour * 0.001f) / static_cast<float>(s);
}
// Set density factors - used to penalize edges in dense, urban areas
for (uint32_t d = 0; d < 16; d++) {
density_factor_[d] = 0.85f + (d * 0.025f);
}
}
// Check if access is allowed on the specified edge.
bool AutoCost::Allowed(const baldr::DirectedEdge* edge,
const bool is_dest,
const EdgeLabel& pred,
const graph_tile_ptr& tile,
const baldr::GraphId& edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const {
// Check access, U-turn, and simple turn restriction.
// Allow U-turns at dead-end nodes in case the origin is inside
// a not thru region and a heading selected an edge entering the
// region.
if (!IsAccessible(edge) || (!pred.deadend() && pred.opp_local_idx() == edge->localedgeidx()) ||
((pred.restrictions() & (1 << edge->localedgeidx())) && !ignore_restrictions_) ||
edge->surface() == Surface::kImpassable || IsUserAvoidEdge(edgeid) ||
(!allow_destination_only_ && !pred.destonly() && edge->destonly()) ||
(pred.closure_pruning() && IsClosed(edge, tile)) ||
(exclude_unpaved_ && !pred.unpaved() && edge->unpaved()) || !IsHOVAllowed(edge)) {
return false;
}
return DynamicCost::EvaluateRestrictions(access_mask_, edge, is_dest, tile, edgeid, current_time,
tz_index, restriction_idx);
}
// Checks if access is allowed for an edge on the reverse path (from
// destination towards origin). Both opposing edges are provided.
bool AutoCost::AllowedReverse(const baldr::DirectedEdge* edge,
const EdgeLabel& pred,
const baldr::DirectedEdge* opp_edge,
const graph_tile_ptr& tile,
const baldr::GraphId& opp_edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const {
// Check access, U-turn, and simple turn restriction.
// Allow U-turns at dead-end nodes.
if (!IsAccessible(opp_edge) || (!pred.deadend() && pred.opp_local_idx() == edge->localedgeidx()) ||
((opp_edge->restrictions() & (1 << pred.opp_local_idx())) && !ignore_restrictions_) ||
opp_edge->surface() == Surface::kImpassable || IsUserAvoidEdge(opp_edgeid) ||
(!allow_destination_only_ && !pred.destonly() && opp_edge->destonly()) ||
(pred.closure_pruning() && IsClosed(opp_edge, tile)) ||
(exclude_unpaved_ && !pred.unpaved() && opp_edge->unpaved()) || !IsHOVAllowed(opp_edge)) {
return false;
}
return DynamicCost::EvaluateRestrictions(access_mask_, edge, false, tile, opp_edgeid, current_time,
tz_index, restriction_idx);
}
bool AutoCost::ModeSpecificAllowed(const baldr::AccessRestriction& restriction) const {
switch (restriction.type()) {
case AccessType::kMaxHeight:
return height_ <= static_cast<float>(restriction.value() * 0.01);
case AccessType::kMaxWidth:
return width_ <= static_cast<float>(restriction.value() * 0.01);
default:
return true;
};
// Unreachable line
return true;
}
// Get the cost to traverse the edge in seconds
Cost AutoCost::EdgeCost(const baldr::DirectedEdge* edge,
const graph_tile_ptr& tile,
const baldr::TimeInfo& time_info,
uint8_t& flow_sources) const {
// either the computed edge speed or optional top_speed
auto edge_speed = fixed_speed_ == baldr::kDisableFixedSpeed
? tile->GetSpeed(edge, flow_mask_, time_info.second_of_week, false,
&flow_sources, time_info.seconds_from_now)
: fixed_speed_;
auto final_speed = std::min(edge_speed, top_speed_);
float sec = edge->length() * speedfactor_[final_speed];
if (shortest_) {
return Cost(edge->length(), sec);
}
// base factor is either ferry, rail ferry or density based
float factor = 1;
switch (edge->use()) {
case Use::kFerry:
factor = ferry_factor_;
break;
case Use::kRailFerry:
factor = rail_ferry_factor_;
break;
default:
factor = density_factor_[edge->density()];
break;
}
factor += highway_factor_ * kHighwayFactor[static_cast<uint32_t>(edge->classification())] +
surface_factor_ * kSurfaceFactor[static_cast<uint32_t>(edge->surface())] +
SpeedPenalty(edge, tile, time_info, flow_sources, edge_speed) +
edge->toll() * toll_factor_;
switch (edge->use()) {
case Use::kAlley:
factor *= alley_factor_;
break;
case Use::kTrack:
factor *= track_factor_;
break;
case Use::kLivingStreet:
factor *= living_street_factor_;
break;
case Use::kServiceRoad:
factor *= service_factor_;
break;
case Use::kTurnChannel:
if (flow_sources & kDefaultFlowMask) {
// boost only historic & live speeds
factor *= kTurnChannelFactor;
}
break;
default:
break;
}
if (IsClosed(edge, tile)) {
// Add a penalty for traversing a closed edge
factor *= closure_factor_;
}
// base cost before the factor is a linear combination of time vs distance, depending on which
// one the user thinks is more important to them
return Cost((sec * inv_distance_factor_ + edge->length() * distance_factor_) * factor, sec);
}
// Returns the time (in seconds) to make the transition from the predecessor
Cost AutoCost::TransitionCost(const baldr::DirectedEdge* edge,
const baldr::NodeInfo* node,
const EdgeLabel& pred) const {
// Get the transition cost for country crossing, ferry, gate, toll booth,
// destination only, alley, maneuver penalty
uint32_t idx = pred.opp_local_idx();
Cost c = base_transition_cost(node, edge, &pred, idx);
c.secs += OSRMCarTurnDuration(edge, node, pred.opp_local_idx());
// Transition time = turncost * stopimpact * densityfactor
if (edge->stopimpact(idx) > 0 && !shortest_) {
float turn_cost;
if (edge->edge_to_right(idx) && edge->edge_to_left(idx)) {
turn_cost = kTCCrossing;
} else {
turn_cost = (node->drive_on_right())
? kRightSideTurnCosts[static_cast<uint32_t>(edge->turntype(idx))]
: kLeftSideTurnCosts[static_cast<uint32_t>(edge->turntype(idx))];
}
if ((edge->use() != Use::kRamp && pred.use() == Use::kRamp) ||
(edge->use() == Use::kRamp && pred.use() != Use::kRamp)) {
turn_cost += 1.5f;
if (edge->roundabout())
turn_cost += 0.5f;
}
float seconds = turn_cost;
bool is_turn = false;
bool has_left = (edge->turntype(idx) == baldr::Turn::Type::kLeft ||
edge->turntype(idx) == baldr::Turn::Type::kSharpLeft);
bool has_right = (edge->turntype(idx) == baldr::Turn::Type::kRight ||
edge->turntype(idx) == baldr::Turn::Type::kSharpRight);
bool has_reverse = edge->turntype(idx) == baldr::Turn::Type::kReverse;
// Separate time and penalty when traffic is present. With traffic, edge speeds account for
// much of the intersection transition time (TODO - evaluate different elapsed time settings).
// Still want to add a penalty so routes avoid high cost intersections.
if (has_left || has_right || has_reverse) {
seconds *= edge->stopimpact(idx);
is_turn = true;
}
AddUturnPenalty(idx, node, edge, has_reverse, has_left, has_right, true, pred.internal_turn(),
seconds);
// Apply density factor and stop impact penalty if there isn't traffic on this edge or you're not
// using traffic
if (!pred.has_measured_speed()) {
if (!is_turn)
seconds *= edge->stopimpact(idx);
seconds *= trans_density_factor_[node->density()];
}
c.cost += seconds;
}
// Account for the user preferring distance
c.cost *= inv_distance_factor_;
return c;
}
// Returns the cost to make the transition from the predecessor edge
// when using a reverse search (from destination towards the origin).
// pred is the opposing current edge in the reverse tree
// edge is the opposing predecessor in the reverse tree
Cost AutoCost::TransitionCostReverse(const uint32_t idx,
const baldr::NodeInfo* node,
const baldr::DirectedEdge* pred,
const baldr::DirectedEdge* edge,
const bool has_measured_speed,
const InternalTurn internal_turn) const {
// Get the transition cost for country crossing, ferry, gate, toll booth,
// destination only, alley, maneuver penalty
Cost c = base_transition_cost(node, edge, pred, idx);
c.secs += OSRMCarTurnDuration(edge, node, pred->opp_local_idx());
// Transition time = turncost * stopimpact * densityfactor
if (edge->stopimpact(idx) > 0 && !shortest_) {
float turn_cost;
if (edge->edge_to_right(idx) && edge->edge_to_left(idx)) {
turn_cost = kTCCrossing;
} else {
turn_cost = (node->drive_on_right())
? kRightSideTurnCosts[static_cast<uint32_t>(edge->turntype(idx))]
: kLeftSideTurnCosts[static_cast<uint32_t>(edge->turntype(idx))];
}
if ((edge->use() != Use::kRamp && pred->use() == Use::kRamp) ||
(edge->use() == Use::kRamp && pred->use() != Use::kRamp)) {
turn_cost += 1.5f;
if (edge->roundabout())
turn_cost += 0.5f;
}
float seconds = turn_cost;
bool is_turn = false;
bool has_left = (edge->turntype(idx) == baldr::Turn::Type::kLeft ||
edge->turntype(idx) == baldr::Turn::Type::kSharpLeft);
bool has_right = (edge->turntype(idx) == baldr::Turn::Type::kRight ||
edge->turntype(idx) == baldr::Turn::Type::kSharpRight);
bool has_reverse = edge->turntype(idx) == baldr::Turn::Type::kReverse;
// Separate time and penalty when traffic is present. With traffic, edge speeds account for
// much of the intersection transition time (TODO - evaluate different elapsed time settings).
// Still want to add a penalty so routes avoid high cost intersections.
if (has_left || has_right || has_reverse) {
seconds *= edge->stopimpact(idx);
is_turn = true;
}
AddUturnPenalty(idx, node, edge, has_reverse, has_left, has_right, true, internal_turn, seconds);
// Apply density factor and stop impact penalty if there isn't traffic on this edge or you're not
// using traffic
if (!has_measured_speed) {
if (!is_turn)
seconds *= edge->stopimpact(idx);
seconds *= trans_density_factor_[node->density()];
}
c.cost += seconds;
}
// Account for the user preferring distance
c.cost *= inv_distance_factor_;
return c;
}
void ParseAutoCostOptions(const rapidjson::Document& doc,
const std::string& costing_options_key,
Costing* c) {
c->set_type(Costing::auto_);
c->set_name(Costing_Enum_Name(c->type()));
auto* co = c->mutable_options();
rapidjson::Value dummy;
const auto& json = rapidjson::get_child(doc, costing_options_key.c_str(), dummy);
ParseBaseCostOptions(json, c, kBaseCostOptsConfig);
JSON_PBF_RANGED_DEFAULT(co, kAlleyFactorRange, json, "/alley_factor", alley_factor);
JSON_PBF_RANGED_DEFAULT(co, kUseHighwaysRange, json, "/use_highways", use_highways);
JSON_PBF_RANGED_DEFAULT(co, kUseTollsRange, json, "/use_tolls", use_tolls);
JSON_PBF_RANGED_DEFAULT(co, kUseDistanceRange, json, "/use_distance", use_distance);
JSON_PBF_RANGED_DEFAULT(co, kAutoHeightRange, json, "/height", height);
JSON_PBF_RANGED_DEFAULT(co, kAutoWidthRange, json, "/width", width);
JSON_PBF_RANGED_DEFAULT(co, kProbabilityRange, json, "/restriction_probability",
restriction_probability);
JSON_PBF_DEFAULT(co, false, json, "/include_hot", include_hot);
JSON_PBF_DEFAULT(co, false, json, "/include_hov2", include_hov2);
JSON_PBF_DEFAULT(co, false, json, "/include_hov3", include_hov3);
}
cost_ptr_t CreateAutoCost(const Costing& costing_options) {
return std::make_shared<AutoCost>(costing_options);
}
/**
* Derived class providing bus costing for driving.
*/
class BusCost : public AutoCost {
public:
/**
* Construct bus costing.
* Pass in configuration using property tree.
* @param pt Property tree with configuration/options.
*/
BusCost(const Costing& costing_options) : AutoCost(costing_options, kBusAccess) {
type_ = VehicleType::kBus;
}
/// virtual destructor
virtual ~BusCost() {
}
/**
* Checks if access is allowed for the provided directed edge.
* This is generally based on mode of travel and the access modes
* allowed on the edge. However, it can be extended to exclude access
* based on other parameters such as conditional restrictions and
* conditional access that can depend on time and travel mode.
* @param edge Pointer to a directed edge.
* @param is_dest Is a directed edge the destination?
* @param pred Predecessor edge information.
* @param tile Current tile.
* @param edgeid GraphId of the directed edge.
* @param current_time Current time (seconds since epoch). A value of 0
* indicates the route is not time dependent.
* @param tz_index timezone index for the node
* @return Returns true if access is allowed, false if not.
*/
virtual bool Allowed(const baldr::DirectedEdge* edge,
const bool is_dest,
const EdgeLabel& pred,
const graph_tile_ptr& tile,
const baldr::GraphId& edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const override;
/**
* Checks if access is allowed for an edge on the reverse path
* (from destination towards origin). Both opposing edges (current and
* predecessor) are provided. The access check is generally based on mode
* of travel and the access modes allowed on the edge. However, it can be
* extended to exclude access based on other parameters such as conditional
* restrictions and conditional access that can depend on time and travel
* mode.
* @param edge Pointer to a directed edge.
* @param pred Predecessor edge information.
* @param opp_edge Pointer to the opposing directed edge.
* @param tile Current tile.
* @param edgeid GraphId of the opposing edge.
* @param current_time Current time (seconds since epoch). A value of 0
* indicates the route is not time dependent.
* @param tz_index timezone index for the node
* @return Returns true if access is allowed, false if not.
*/
virtual bool AllowedReverse(const baldr::DirectedEdge* edge,
const EdgeLabel& pred,
const baldr::DirectedEdge* opp_edge,
const graph_tile_ptr& tile,
const baldr::GraphId& opp_edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const override;
};
// Check if access is allowed on the specified edge.
bool BusCost::Allowed(const baldr::DirectedEdge* edge,
const bool is_dest,
const EdgeLabel& pred,
const graph_tile_ptr& tile,
const baldr::GraphId& edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const {
// Check access, U-turn, and simple turn restriction.
// Allow U-turns at dead-end nodes.
if (!IsAccessible(edge) || (!pred.deadend() && pred.opp_local_idx() == edge->localedgeidx()) ||
((pred.restrictions() & (1 << edge->localedgeidx())) && !ignore_restrictions_) ||
edge->surface() == Surface::kImpassable || IsUserAvoidEdge(edgeid) ||
(!allow_destination_only_ && !pred.destonly() && edge->destonly()) ||
(pred.closure_pruning() && IsClosed(edge, tile)) ||
(exclude_unpaved_ && !pred.unpaved() && edge->unpaved())) {
return false;
}
return DynamicCost::EvaluateRestrictions(access_mask_, edge, is_dest, tile, edgeid, current_time,
tz_index, restriction_idx);
}
// Checks if access is allowed for an edge on the reverse path (from
// destination towards origin). Both opposing edges are provided.
bool BusCost::AllowedReverse(const baldr::DirectedEdge* edge,
const EdgeLabel& pred,
const baldr::DirectedEdge* opp_edge,
const graph_tile_ptr& tile,
const baldr::GraphId& opp_edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const {
// Check access, U-turn, and simple turn restriction.
// Allow U-turns at dead-end nodes.
if (!IsAccessible(opp_edge) || (!pred.deadend() && pred.opp_local_idx() == edge->localedgeidx()) ||
((opp_edge->restrictions() & (1 << pred.opp_local_idx())) && !ignore_restrictions_) ||
opp_edge->surface() == Surface::kImpassable || IsUserAvoidEdge(opp_edgeid) ||
(!allow_destination_only_ && !pred.destonly() && opp_edge->destonly()) ||
(pred.closure_pruning() && IsClosed(opp_edge, tile)) ||
(exclude_unpaved_ && !pred.unpaved() && opp_edge->unpaved())) {
return false;
}
return DynamicCost::EvaluateRestrictions(access_mask_, edge, false, tile, opp_edgeid, current_time,
tz_index, restriction_idx);
}
void ParseBusCostOptions(const rapidjson::Document& doc,
const std::string& costing_options_key,
Costing* c) {
ParseAutoCostOptions(doc, costing_options_key, c);
c->set_type(Costing::bus);
c->set_name(Costing_Enum_Name(c->type()));
}
cost_ptr_t CreateBusCost(const Costing& costing_options) {
return std::make_shared<BusCost>(costing_options);
}
/**
* Derived class providing an alternate costing for driving that is intended
* to favor Taxi roads.
*/
class TaxiCost : public AutoCost {
public:
/**
* Construct taxi costing.
* Pass in costing_options using protocol buffer(pbf).
* @param costing_options pbf with costing_options.
*/
TaxiCost(const Costing& costing_options) : AutoCost(costing_options, kTaxiAccess) {
}
virtual ~TaxiCost() {
}
/**
* Checks if access is allowed for the provided directed edge.
* This is generally based on mode of travel and the access modes
* allowed on the edge. However, it can be extended to exclude access
* based on other parameters such as conditional restrictions and
* conditional access that can depend on time and travel mode.
* @param edge Pointer to a directed edge.
* @param is_dest Is a directed edge the destination?
* @param pred Predecessor edge information.
* @param tile Current tile.
* @param edgeid GraphId of the directed edge.
* @param current_time Current time (seconds since epoch). A value of 0
* indicates the route is not time dependent.
* @param tz_index timezone index for the node
* @return Returns true if access is allowed, false if not.
*/
virtual bool Allowed(const baldr::DirectedEdge* edge,
const bool is_dest,
const EdgeLabel& pred,
const graph_tile_ptr& tile,
const baldr::GraphId& edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const override;
/**
* Checks if access is allowed for an edge on the reverse path
* (from destination towards origin). Both opposing edges (current and
* predecessor) are provided. The access check is generally based on mode
* of travel and the access modes allowed on the edge. However, it can be
* extended to exclude access based on other parameters such as conditional
* restrictions and conditional access that can depend on time and travel
* mode.
* @param edge Pointer to a directed edge.
* @param pred Predecessor edge information.
* @param opp_edge Pointer to the opposing directed edge.
* @param tile Current tile.
* @param edgeid GraphId of the opposing edge.
* @param current_time Current time (seconds since epoch). A value of 0
* indicates the route is not time dependent.
* @param tz_index timezone index for the node
*/
virtual bool AllowedReverse(const baldr::DirectedEdge* edge,
const EdgeLabel& pred,
const baldr::DirectedEdge* opp_edge,
const graph_tile_ptr& tile,
const baldr::GraphId& opp_edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const override;
/**
* Returns the cost to traverse the edge and an estimate of the actual time
* (in seconds) to traverse the edge.
* @param edge Pointer to a directed edge.
* @param tile Current tile.
* @param time_info Time info about edge passing.
* @return Returns the cost to traverse the edge.
*/
virtual Cost EdgeCost(const baldr::DirectedEdge* edge,
const graph_tile_ptr& tile,
const baldr::TimeInfo& time_info,
uint8_t& flow_sources) const override {
auto edge_speed = fixed_speed_ == baldr::kDisableFixedSpeed
? tile->GetSpeed(edge, flow_mask_, time_info.second_of_week, false,
&flow_sources, time_info.seconds_from_now)
: fixed_speed_;
auto final_speed = std::min(edge_speed, top_speed_);
float sec = (edge->length() * speedfactor_[final_speed]);
if (shortest_) {
return Cost(edge->length(), sec);
}
float factor = (edge->use() == Use::kFerry) ? ferry_factor_ : density_factor_[edge->density()];
factor += SpeedPenalty(edge, tile, time_info, flow_sources, edge_speed);
if ((edge->forwardaccess() & kTaxiAccess) && !(edge->forwardaccess() & kAutoAccess)) {
factor *= kTaxiFactor;
}
if (edge->use() == Use::kAlley) {
factor *= alley_factor_;
} else if (edge->use() == Use::kTrack) {
factor *= track_factor_;
} else if (edge->use() == Use::kLivingStreet) {
factor *= living_street_factor_;
} else if (edge->use() == Use::kServiceRoad) {
factor *= service_factor_;
}
if (IsClosed(edge, tile)) {
// Add a penalty for traversing a closed edge
factor *= closure_factor_;
}
return Cost(sec * factor, sec);
}
};
// Check if access is allowed on the specified edge.
bool TaxiCost::Allowed(const baldr::DirectedEdge* edge,
const bool is_dest,
const EdgeLabel& pred,
const graph_tile_ptr& tile,
const baldr::GraphId& edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const {
// Check access, U-turn, and simple turn restriction.
// Allow U-turns at dead-end nodes in case the origin is inside
// a not thru region and a heading selected an edge entering the
// region.
if (!IsAccessible(edge) || (!pred.deadend() && pred.opp_local_idx() == edge->localedgeidx()) ||
((pred.restrictions() & (1 << edge->localedgeidx())) && !ignore_restrictions_) ||
edge->surface() == Surface::kImpassable || IsUserAvoidEdge(edgeid) ||
(!allow_destination_only_ && !pred.destonly() && edge->destonly()) ||
(pred.closure_pruning() && IsClosed(edge, tile)) ||
(exclude_unpaved_ && !pred.unpaved() && edge->unpaved())) {
return false;
}
return DynamicCost::EvaluateRestrictions(access_mask_, edge, is_dest, tile, edgeid, current_time,
tz_index, restriction_idx);
}
// Checks if access is allowed for an edge on the reverse path (from
// destination towards origin). Both opposing edges are provided.
bool TaxiCost::AllowedReverse(const baldr::DirectedEdge* edge,
const EdgeLabel& pred,
const baldr::DirectedEdge* opp_edge,
const graph_tile_ptr& tile,
const baldr::GraphId& opp_edgeid,
const uint64_t current_time,
const uint32_t tz_index,
uint8_t& restriction_idx) const {
// Check access, U-turn, and simple turn restriction.
// Allow U-turns at dead-end nodes.
if (!IsAccessible(opp_edge) || (!pred.deadend() && pred.opp_local_idx() == edge->localedgeidx()) ||
((opp_edge->restrictions() & (1 << pred.opp_local_idx())) && !ignore_restrictions_) ||
opp_edge->surface() == Surface::kImpassable || IsUserAvoidEdge(opp_edgeid) ||
(!allow_destination_only_ && !pred.destonly() && opp_edge->destonly()) ||
(pred.closure_pruning() && IsClosed(opp_edge, tile)) ||
(exclude_unpaved_ && !pred.unpaved() && opp_edge->unpaved())) {
return false;
}
return DynamicCost::EvaluateRestrictions(access_mask_, edge, false, tile, opp_edgeid, current_time,
tz_index, restriction_idx);
}