forked from valhalla/valhalla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathastar.cc
1801 lines (1578 loc) · 65.3 KB
/
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 "midgard/logging.h"
#include "test.h"
#include <cstdint>
#include "baldr/graphid.h"
#include "baldr/graphreader.h"
#include "baldr/location.h"
#include "baldr/rapidjson_utils.h"
#include "baldr/tilehierarchy.h"
#include "filesystem.h"
#include "loki/search.h"
#include "loki/worker.h"
#include "midgard/pointll.h"
#include "midgard/vector2.h"
#include "mjolnir/graphbuilder.h"
#include "mjolnir/graphenhancer.h"
#include "mjolnir/graphtilebuilder.h"
#include "mjolnir/graphvalidator.h"
#include "mjolnir/pbfgraphparser.h"
#include "mjolnir/util.h"
#include "odin/directionsbuilder.h"
#include "odin/worker.h"
#include "sif/costconstants.h"
#include "sif/dynamiccost.h"
#include "sif/pedestriancost.h"
#include "thor/bidirectional_astar.h"
#include "thor/pathalgorithm.h"
#include "thor/triplegbuilder.h"
#include "thor/unidirectional_astar.h"
#include "thor/worker.h"
#include "tyr/actor.h"
#include "tyr/serializers.h"
#include "gurka.h"
#include "proto/directions.pb.h"
#include "proto/options.pb.h"
#include "proto/trip.pb.h"
#include <boost/algorithm/string/join.hpp>
#include <boost/property_tree/ptree.hpp>
#if !defined(VALHALLA_SOURCE_DIR)
#define VALHALLA_SOURCE_DIR
#endif
namespace bpt = boost::property_tree;
using namespace valhalla;
namespace vm = valhalla::midgard;
namespace vb = valhalla::baldr;
namespace vs = valhalla::sif;
namespace vt = valhalla::thor;
namespace vk = valhalla::loki;
namespace vj = valhalla::mjolnir;
namespace vo = valhalla::odin;
namespace vr = valhalla::tyr;
#include "mjolnir/directededgebuilder.h"
#include "mjolnir/graphtilebuilder.h"
namespace {
// ph34r the ASCII art diagram:
//
// first test is just a square set of roads
const std::string map1 = R"(
a1------------2b
| |
| |
| |
| |
| 3
c--------------d
)";
const gurka::ways ways1 = {{"ab", {{"highway", "motorway"}}},
{"bd", {{"highway", "motorway"}}},
{"ac", {{"highway", "motorway"}}},
{"dc", {{"highway", "motorway"}}}};
//
// second test is a triangle set of roads, where the height of the triangle is
// about a third of its width.
const std::string map2 = R"(
e4--------5f
\ /
\ /
\ /
\ /
\ /
g
)";
const gurka::ways ways2 = {{"ef", {{"highway", "residential"}, {"foot", "yes"}}},
{"eg", {{"highway", "residential"}, {"foot", "yes"}}},
{"fg", {{"highway", "residential"}, {"foot", "yes"}}}};
// Third test has a complex turn restriction preventing K->H->I->L (marked with R)
// which should force the algorithm to take the detour via the J->M edge
// if starting at K and heading to L
//
const std::string map3 = R"(
h---V----i--------j
| | |
| | |
6 7 |
| | |
| | |
k l8-------m
|
|
|
n
)";
const gurka::ways ways3 = {{"kh", {{"highway", "motorway"}}}, {"hi", {{"highway", "motorway"}}},
{"ij", {{"highway", "motorway"}}}, {"lm", {{"highway", "motorway"}}},
{"mj", {{"highway", "motorway"}}}, {"il", {{"highway", "motorway"}}},
{"nk", {{"highway", "motorway"}}}};
const gurka::relations relations3 = {{{gurka::relation_member{gurka::way_member, "kh", "from"},
gurka::relation_member{gurka::way_member, "il", "to"},
gurka::relation_member{gurka::way_member, "hi", "via"}},
{{"type", "restriction"}, {"restriction", "no_right_turn"}}}};
const vb::GraphId tile_id = vb::TileHierarchy::GetGraphId({.125, .125}, 2);
gurka::nodelayout node_locations;
const std::string test_dir = "test/data/fake_tiles_astar";
const auto fake_conf =
test::make_config(test_dir,
{{"mjolnir.admin", VALHALLA_SOURCE_DIR "test/data/netherlands_admin.sqlite"},
{"mjolnir.timezone", VALHALLA_SOURCE_DIR "test/data/not_needed.sqlite"},
{"mjolnir.hierarchy", "false"},
{"mjolnir.shortcuts", "false"}});
void make_tile() {
if (filesystem::exists(test_dir))
filesystem::remove_all(test_dir);
filesystem::create_directories(test_dir);
const double gridsize = 666;
{
// Build the maps from the ASCII diagrams, and extract the generated lon,lat values
auto nodemap = gurka::detail::map_to_coordinates(map1, gridsize, {0, 0.2});
const int initial_osm_id = 0;
gurka::detail::build_pbf(nodemap, ways1, {}, {}, test_dir + "/map1.pbf", initial_osm_id);
for (const auto& n : nodemap)
node_locations[n.first] = n.second;
}
{
auto nodemap = gurka::detail::map_to_coordinates(map2, gridsize, {0.10, 0.2});
// Need to use a non-conflicting osm ID range for each map, as they
// all get merged during tile building, and we don't want a weirdly connected
// graph because IDs are shared
const int initial_osm_id = 100;
gurka::detail::build_pbf(nodemap, ways2, {}, {}, test_dir + "/map2.pbf", initial_osm_id);
for (const auto& n : nodemap)
node_locations[n.first] = n.second;
}
{
auto nodemap = gurka::detail::map_to_coordinates(map3, gridsize, {0.1, 0.1});
const int initial_osm_id = 200;
gurka::detail::build_pbf(nodemap, ways3, {}, relations3, test_dir + "/map3.pbf", initial_osm_id);
for (const auto& n : nodemap)
node_locations[n.first] = n.second;
}
{
constexpr bool release_osmpbf_memory = false;
mjolnir::build_tile_set(fake_conf,
{test_dir + "/map1.pbf", test_dir + "/map2.pbf", test_dir + "/map3.pbf"},
mjolnir::BuildStage::kInitialize, mjolnir::BuildStage::kValidate,
release_osmpbf_memory);
/** Set the freeflow and constrained flow speeds manually on all edges */
vj::GraphTileBuilder tile_builder(test_dir, tile_id, false);
std::vector<DirectedEdge> directededges;
directededges.reserve(tile_builder.header()->directededgecount());
for (uint32_t j = 0; j < tile_builder.header()->directededgecount(); ++j) {
// skip edges for which we dont have speed data
DirectedEdge& directededge = tile_builder.directededge(j);
directededge.set_free_flow_speed(100);
directededge.set_constrained_flow_speed(10);
directededge.set_forwardaccess(vb::kAllAccess);
directededge.set_reverseaccess(vb::kAllAccess);
directededges.emplace_back(std::move(directededge));
}
tile_builder.UpdatePredictedSpeeds(directededges);
}
auto tile = GraphTile::Create(test_dir, tile_id);
ASSERT_TRUE(tile);
ASSERT_EQ(tile->FileSuffix(tile_id), std::string("2/000/519/120.gph"))
<< "Tile ID didn't match the expected filename";
ASSERT_PRED1(filesystem::exists,
test_dir + filesystem::path::preferred_separator + tile->FileSuffix(tile_id))
<< "Expected tile file didn't show up on disk - are the fixtures in the right location?";
}
void create_costing_options(Options& options, Costing::Type costing) {
const rapidjson::Document doc;
options.set_costing_type(costing);
sif::ParseCosting(doc, "/costing_options", options);
}
// Convert locations to format needed by PathAlgorithm
std::vector<valhalla::Location> ToPBFLocations(const std::vector<vb::Location>& locations,
vb::GraphReader& graphreader,
const std::shared_ptr<vs::DynamicCost>& costing) {
const auto projections = loki::Search(locations, graphreader, costing);
std::vector<valhalla::Location> result;
for (const auto& loc : locations) {
valhalla::Location pbfLoc;
const auto& correlated = projections.at(loc);
PathLocation::toPBF(correlated, &pbfLoc, graphreader);
result.emplace_back(std::move(pbfLoc));
}
return result;
}
enum class TrivialPathTest {
MatchesEdge,
DurationEqualTo,
};
std::unique_ptr<vb::GraphReader> get_graph_reader(const std::string& tile_dir) {
// make the config file
std::stringstream json;
json << "{ \"tile_dir\": \"" << tile_dir << "\" }";
bpt::ptree conf;
rapidjson::read_json(json, conf);
std::unique_ptr<vb::GraphReader> reader(new vb::GraphReader(conf));
auto tile = reader->GetGraphTile(tile_id);
EXPECT_NE(tile, nullptr) << "Unable to load test tile! Did `make_tile` run successfully?";
if (tile->header()->directededgecount() != 28) {
throw std::logic_error("test-tiles does not contain expected number of edges");
}
auto endtile = reader->GetGraphTile(node_locations["b"]);
EXPECT_NE(endtile, nullptr) << "bad tile, node 'b' wasn't found in it";
return reader;
}
// check that a path from origin to dest goes along the edge with expected_edge_index
void assert_is_trivial_path(vt::PathAlgorithm& astar,
valhalla::Location& origin,
valhalla::Location& dest,
uint32_t expected_num_paths,
TrivialPathTest assert_type,
int32_t assert_type_value,
vs::TravelMode mode = vs::TravelMode::kPedestrian) {
auto reader = get_graph_reader(test_dir);
Options options;
auto costing = mode == vs::TravelMode::kPedestrian ? Costing::pedestrian : Costing::auto_;
create_costing_options(options, costing);
auto mode_costing = sif::CostFactory().CreateModeCosting(options, mode);
ASSERT_TRUE(bool(mode_costing[int(mode)]));
auto paths = astar.GetBestPath(origin, dest, *reader, mode_costing, mode);
int32_t time = 0;
for (const auto& path : paths) {
for (const auto& p : path) {
time += p.elapsed_cost.secs;
}
EXPECT_EQ(path.size(), expected_num_paths);
break;
}
auto tile = reader->GetGraphTile(tile_id);
uint32_t expected_time = 979797;
switch (assert_type) {
case TrivialPathTest::DurationEqualTo:
// Supply duration directly
expected_time = assert_type_value;
break;
case TrivialPathTest::MatchesEdge:
// Grab time from an edge index
const DirectedEdge* expected_edge = tile->directededge(assert_type_value);
auto expected_cost = mode_costing[int(mode)]->EdgeCost(expected_edge, tile);
expected_time = expected_cost.secs;
break;
};
EXPECT_NE(expected_time, 0) << "Expected time is 0, your test probably has a logic error";
EXPECT_EQ(time, expected_time) << "time in seconds";
}
// test that a path from A to B succeeds, even if the edges from A to C and B
// to D appear first in the PathLocation.
void TestTrivialPath(vt::PathAlgorithm& astar) {
Options options;
create_costing_options(options, Costing::auto_);
sif::TravelMode mode;
auto mode_costing = sif::CostFactory().CreateModeCosting(options, mode);
auto reader = get_graph_reader(test_dir);
std::vector<valhalla::baldr::Location> locations;
locations.push_back({node_locations["1"]});
locations.push_back({node_locations["2"]});
const auto projections = loki::Search(locations, *reader, mode_costing[static_cast<size_t>(mode)]);
valhalla::Location origin;
{
const auto& correlated = projections.at(locations[0]);
PathLocation::toPBF(correlated, &origin, *reader);
origin.set_date_time("2019-11-21T13:05");
}
valhalla::Location dest;
{
const auto& correlated = projections.at(locations[1]);
PathLocation::toPBF(correlated, &dest, *reader);
dest.set_date_time("2019-11-21T13:05");
}
// this should go along the path from A to B
assert_is_trivial_path(astar, origin, dest, 1, TrivialPathTest::DurationEqualTo, 3116,
vs::TravelMode::kDrive);
}
TEST(Astar, TestTrivialPathForward) {
vt::TimeDepForward astar;
TestTrivialPath(astar);
}
TEST(Astar, TestTrivialPathReverse) {
vt::TimeDepReverse astar;
TestTrivialPath(astar);
}
// test that a path from E to F succeeds, even if the edges from E and F
// to G appear first in the PathLocation.
TEST(Astar, TestTrivialPathTriangle) {
Options options;
create_costing_options(options, Costing::pedestrian);
vs::TravelMode mode;
auto costs = vs::CostFactory().CreateModeCosting(options, mode);
auto reader = get_graph_reader(test_dir);
std::vector<valhalla::baldr::Location> locations;
locations.push_back({node_locations["4"]});
locations.push_back({node_locations["5"]});
const auto projections = loki::Search(locations, *reader, costs[static_cast<size_t>(mode)]);
valhalla::Location origin;
{
const auto& correlated = projections.at(locations[0]);
PathLocation::toPBF(correlated, &origin, *reader);
}
valhalla::Location dest;
{
const auto& correlated = projections.at(locations[1]);
PathLocation::toPBF(correlated, &dest, *reader);
}
// TODO This fails with graphindex out of bounds for Reverse direction, is this
// related to why we short-circuit trivial routes to AStarPathAlgorithm in route_action.cc?
//
vt::TimeDepForward astar;
// this should go along the path from E to F
assert_is_trivial_path(astar, origin, dest, 1, TrivialPathTest::DurationEqualTo, 4231,
vs::TravelMode::kPedestrian);
}
void TestPartialDuration(vt::PathAlgorithm& astar) {
// Tests that a partial duration is returned when starting on a partial edge
Options options;
create_costing_options(options, Costing::auto_);
vs::TravelMode mode;
auto costs = vs::CostFactory().CreateModeCosting(options, mode);
auto reader = get_graph_reader(test_dir);
std::vector<valhalla::baldr::Location> locations;
locations.push_back({node_locations["1"]});
locations.push_back({node_locations["3"]});
auto projections = loki::Search(locations, *reader, costs[static_cast<size_t>(mode)]);
valhalla::Location origin;
{
auto& correlated = projections.at(locations[0]);
PathLocation::toPBF(correlated, &origin, *reader);
origin.set_date_time("2019-11-21T13:05");
}
valhalla::Location dest;
{
auto& correlated = projections.at(locations[1]);
PathLocation::toPBF(correlated, &dest, *reader);
dest.set_date_time("2019-11-21T13:05");
}
uint32_t expected_duration = 7911;
assert_is_trivial_path(astar, origin, dest, 2, TrivialPathTest::DurationEqualTo, expected_duration,
vs::TravelMode::kDrive);
}
TEST(Astar, TestPartialDurationForward) {
vt::TimeDepForward astar;
TestPartialDuration(astar);
}
TEST(Astar, TestPartialDurationReverse) {
vt::TimeDepReverse astar;
TestPartialDuration(astar);
}
TEST(Astar, TestTrivialPathNoUturns) {
boost::property_tree::ptree conf = test::make_config("test/data/utrecht_tiles");
vr::actor_t actor(conf);
valhalla::Api api;
actor.route(
R"({"costing":"pedestrian","locations":[{"lon":5.114587,"lat":52.095957},{"lon":5.114506,"lat":52.096141}]})",
{}, &api);
EXPECT_EQ(api.directions().routes(0).legs(0).summary().time(), 0);
}
struct route_tester {
route_tester(const boost::property_tree::ptree& _conf)
: conf(_conf), reader(new GraphReader(conf.get_child("mjolnir"))), loki_worker(conf, reader),
thor_worker(conf, reader), odin_worker(conf) {
}
Api test(const std::string& request_json) {
Api request;
ParseApi(request_json, valhalla::Options::route, request);
loki_worker.route(request);
thor_worker.route(request);
odin_worker.narrate(request);
// Cleanup
loki_worker.cleanup();
thor_worker.cleanup();
odin_worker.cleanup();
return request;
}
boost::property_tree::ptree conf;
std::shared_ptr<GraphReader> reader;
vk::loki_worker_t loki_worker;
vt::thor_worker_t thor_worker;
vo::odin_worker_t odin_worker;
};
TEST(Astar, test_oneway) {
auto conf = test::make_config("test/data/whitelion_tiles");
route_tester tester(conf);
// Test onewayness with this route - oneway works, South-West to North-East
std::string request =
R"({"locations":[{"lat":51.455768530466514,"lon":-2.5954368710517883},{"lat":51.456082740244824,"lon":-2.595050632953644}],"costing":"auto"})";
auto response = tester.test(request);
const auto& legs = response.trip().routes(0).legs();
const auto& directions = response.directions().routes(0).legs();
EXPECT_EQ(legs.size(), 1);
std::vector<std::string> names;
for (const auto& d : directions) {
for (const auto& m : d.maneuver()) {
std::string name;
for (const auto& n : m.street_name()) {
name += n.value() + " ";
}
if (!name.empty()) {
name.pop_back();
}
names.push_back(name);
}
}
auto correct_route = std::vector<std::string>{"Quay Street", ""};
EXPECT_EQ(names, correct_route) << "Incorrect route, got: \n" +
boost::algorithm::join(names, ", ") + ", expected: \n" +
boost::algorithm::join(correct_route, ", ");
}
TEST(Astar, test_oneway_wrong_way) {
auto conf = test::make_config("test/data/whitelion_tiles");
route_tester tester(conf);
// Test onewayness with this route - oneway wrong way, North-east to South-West
// Should produce no-route
std::string request =
R"({"locations":[{"lat":51.456082740244824,"lon":-2.595050632953644},{"lat":51.455768530466514,"lon":-2.5954368710517883}],"costing":"auto"})";
try {
auto response = tester.test(request);
FAIL() << "Expected exception!";
} catch (const std::exception& e) {
EXPECT_EQ(std::string(e.what()), "No path could be found for input");
} catch (...) { FAIL() << "Wrong exception type"; }
}
TEST(Astar, test_deadend) {
auto conf = test::make_config("test/data/whitelion_tiles");
route_tester tester(conf);
std::string request =
R"({
"locations":[
{"lat":51.45562646682483,"lon":-2.5952598452568054},
{"lat":51.455143447135974,"lon":-2.5958767533302307}
],
"costing":"auto"
})";
auto response = tester.test(request);
const auto& legs = response.trip().routes(0).legs();
const auto& directions = response.directions().routes(0).legs();
EXPECT_EQ(legs.size(), 1);
std::vector<std::string> names;
std::string uturn_street;
for (const auto& d : directions) {
for (const auto& m : d.maneuver()) {
std::string name;
for (const auto& n : m.street_name()) {
name += n.value() + " ";
}
if (!name.empty()) {
name.pop_back();
}
if (m.type() == DirectionsLeg_Maneuver_Type_kUturnRight ||
m.type() == DirectionsLeg_Maneuver_Type_kUturnLeft) {
uturn_street = name;
}
names.push_back(name);
}
}
auto correct_route =
std::vector<std::string>{"Bell Lane", "Small Street",
"Quay Street", // The u-turn on Quay Street is optimized away
"", ""};
EXPECT_EQ(names, correct_route) << "Incorrect route, got: \n" +
boost::algorithm::join(names, ", ") + ", expected: \n" +
boost::algorithm::join(correct_route, ", ");
EXPECT_EQ(uturn_street, "Quay Street") << "We did not find the expected u-turn";
}
TEST(Astar, test_time_dep_forward_with_current_time) {
// Test a request with date_time as "current" (type: 0)
//
auto conf = test::make_config("test/data/whitelion_tiles_reverse");
route_tester tester(conf);
std::string request =
R"({
"locations":[
{"lat":51.45562646682483,"lon":-2.5952598452568054},
{"lat":51.455143447135974,"lon":-2.5958767533302307}
],
"costing":"auto",
"date_time":{
"type":0
}
})";
auto response = tester.test(request);
const auto& legs = response.trip().routes(0).legs();
const auto& directions = response.directions().routes(0).legs();
EXPECT_EQ(legs.size(), 1) << "Should have 1 leg";
std::vector<std::string> names;
for (const auto& d : directions) {
for (const auto& m : d.maneuver()) {
std::string name;
for (const auto& n : m.street_name()) {
name += n.value() + " ";
}
if (!name.empty()) {
name.pop_back();
}
names.push_back(name);
}
}
auto correct_route =
std::vector<std::string>{"Bell Lane", "Small Street",
"Quay Street", // The u-turn on Quay Street is optimized away
"", ""};
EXPECT_EQ(names, correct_route) << "Incorrect route, got: \n" +
boost::algorithm::join(names, ", ") + ", expected: \n" +
boost::algorithm::join(correct_route, ", ");
}
TEST(Astar, test_deadend_timedep_forward) {
auto conf = test::make_config("test/data/whitelion_tiles_reverse");
route_tester tester(conf);
std::string request =
R"({
"locations":[
{"lat":51.45562646682483,"lon":-2.5952598452568054},
{"lat":51.455143447135974,"lon":-2.5958767533302307}
],
"costing":"auto",
"date_time":{
"type":1,
"value":"2019-11-21T11:05"
}
})";
auto response = tester.test(request);
const auto& legs = response.trip().routes(0).legs();
const auto& directions = response.directions().routes(0).legs();
EXPECT_EQ(legs.size(), 1);
std::vector<std::string> names;
std::string uturn_street;
for (const auto& d : directions) {
for (const auto& m : d.maneuver()) {
std::string name;
for (const auto& n : m.street_name()) {
name += n.value() + " ";
}
if (!name.empty()) {
name.pop_back();
}
if (m.type() == DirectionsLeg_Maneuver_Type_kUturnRight ||
m.type() == DirectionsLeg_Maneuver_Type_kUturnLeft) {
uturn_street = name;
}
names.push_back(name);
}
}
auto correct_route =
std::vector<std::string>{"Bell Lane", "Small Street",
"Quay Street", // The u-turn on Quay Street is optimized away
"", ""};
EXPECT_EQ(names, correct_route) << "Incorrect route, got: \n" +
boost::algorithm::join(names, ", ") + ", expected: \n" +
boost::algorithm::join(correct_route, ", ");
EXPECT_EQ(uturn_street, "Quay Street") << "We did not find the expected u-turn";
}
TEST(Astar, test_deadend_timedep_reverse) {
auto conf = test::make_config("test/data/whitelion_tiles");
route_tester tester(conf);
std::string request =
R"({
"locations":[
{"lat":51.45562646682483,"lon":-2.5952598452568054},
{"lat":51.455143447135974,"lon":-2.5958767533302307}
],
"costing":"auto",
"date_time":{
"type":2,
"value":"2019-11-21T11:05"
}
})";
auto response = tester.test(request);
const auto& legs = response.trip().routes(0).legs();
const auto& directions = response.directions().routes(0).legs();
EXPECT_EQ(legs.size(), 1);
std::vector<std::string> names;
std::string uturn_street;
for (const auto& d : directions) {
for (const auto& m : d.maneuver()) {
std::string name;
for (const auto& n : m.street_name()) {
name += n.value() + " ";
}
if (!name.empty()) {
name.pop_back();
}
if (m.type() == DirectionsLeg_Maneuver_Type_kUturnRight ||
m.type() == DirectionsLeg_Maneuver_Type_kUturnLeft) {
uturn_street = name;
}
names.push_back(name);
}
}
auto correct_route =
std::vector<std::string>{"Bell Lane", "Small Street",
"Quay Street", // The u-turn on Quay Street is optimized away
"", ""};
EXPECT_EQ(names, correct_route) << "Incorrect route, got: \n" +
boost::algorithm::join(names, ", ") + ", expected: \n" +
boost::algorithm::join(correct_route, ", ");
EXPECT_EQ(uturn_street, "Quay Street") << "We did not find the expected u-turn";
}
TEST(Astar, test_time_restricted_road_bidirectional) {
// Try routing over "Via Montebello" in Rome which is a time restricted road
// We should receive a route for a time-independent query but have the response
// note that it is time restricted
auto conf = test::make_config("test/data/roma_tiles");
route_tester tester(conf);
std::string request =
R"({"locations":[{"lat":41.90550,"lon":12.50090},{"lat":41.90477,"lon":12.49914}],"costing":"auto"})";
auto response = tester.test(request);
const auto& legs = response.trip().routes(0).legs();
const auto& directions = response.directions().routes(0).legs();
EXPECT_EQ(legs.size(), 1);
std::vector<std::string> names;
std::vector<std::string> restricted_streets;
for (const auto& d : directions) {
for (const auto& m : d.maneuver()) {
std::string name;
for (const auto& n : m.street_name()) {
name += n.value() + " ";
}
if (!name.empty()) {
name.pop_back();
}
if (m.has_time_restrictions()) {
restricted_streets.push_back(name);
}
names.push_back(name);
}
}
auto correct_route = std::vector<std::string>{"Via Goito", "Via Montebello", ""};
EXPECT_EQ(names, correct_route) << "Incorrect route, got: \n" +
boost::algorithm::join(names, ", ") + ", expected: \n" +
boost::algorithm::join(correct_route, ", ");
EXPECT_TRUE(response.trip().routes(0).legs(0).node(1).edge().has_time_restrictions())
<< "Expected leg to have time_restriction";
// Verify JSON payload
const std::string payload = tyr::serializeDirections(response);
rapidjson::Document response_json;
response_json.Parse(payload.c_str());
std::cout << payload << std::endl;
{
const char key[] = "/trip/legs/0/maneuvers/0/has_time_restrictions";
EXPECT_TRUE(GetValueByPointerWithDefault(response_json, key, false) != true)
<< "Via Goito is marked as time-restricted which is incorrect! JSON does have " << key
<< " set to true";
}
{
const char key[] = "/trip/legs/0/maneuvers/1/has_time_restrictions";
EXPECT_TRUE(GetValueByPointerWithDefault(response_json, key, false) == true)
<< std::string("JSON does not have ") + key + " set to true";
}
{
const char key[] = "/trip/legs/0/summary/has_time_restrictions";
EXPECT_TRUE(GetValueByPointerWithDefault(response_json, key, false) == true)
<< std::string("JSON does not have ") + key + " set to true";
}
{
const char key[] = "/trip/summary/has_time_restrictions";
EXPECT_TRUE(GetValueByPointerWithDefault(response_json, key, false) == true)
<< std::string("JSON does not have ") + key + " set to true";
}
}
Api route_on_timerestricted(const std::string& costing_str, int16_t hour) {
// Try routing over "Via Montebello" in Rome which is a time restricted road
// The restriction is
//
// <tag k="auto" v="yes"/>
// <tag k="motor_vehicle:conditional" v="no @ (Mo-Sa 07:00-16:00)"/>
// <tag k="pedestrian" v="no"/>
// <tag k="pedestrian:conditional" v="yes @ (Mo-Sa 08:00-15:00)"/>
//
// so lets use a timedependent a-star and verify that
LOG_INFO("Testing " + costing_str + " route at hour " + std::to_string(hour));
auto conf = test::make_config("test/data/roma_tiles");
route_tester tester(conf);
// The following request results in timedep astar during the restricted hours
// and should be denied
std::string request =
R"({
"locations":[{"lat":41.90550,"lon":12.50090},{"lat":41.90477,"lon":12.49914}],
"costing":")" +
costing_str + R"(",
"date_time":{
"type":1,
"value":"2020-01-16T)" +
std::to_string(hour) + R"(:05"
}
})";
return tester.test(request);
}
void test_route_restricted(const std::string& costing_str, int16_t hour) {
bool found_route = false;
try {
auto response = route_on_timerestricted(costing_str, hour);
found_route = true;
const auto& leg = response.directions().routes(0).legs(0);
LOG_INFO("Route that wasn't supposed to happen: " + leg.shape());
} catch (const std::exception& e) {
EXPECT_EQ(std::string(e.what()), "No path could be found for input");
return;
}
EXPECT_FALSE(found_route) << "Found a route when no route was expected";
}
TEST(Astar, test_time_restricted_road_denied_on_timedep) {
{
// A car at hour 11 should be denied
std::string costing_str("auto");
test_route_restricted(costing_str, 11);
}
{
// A pedestrian at hour 22 should be denied
std::string costing_str("pedestrian");
test_route_restricted(costing_str, 22);
}
}
void test_route_allowed(const std::string& costing_str, int16_t hour) {
auto response = route_on_timerestricted(costing_str, hour);
const auto& legs = response.trip().routes(0).legs();
EXPECT_EQ(legs.size(), 1) << "Should have 1 leg";
const auto& directions = response.directions().routes(0).legs(0);
const auto& summary = directions.summary();
EXPECT_NE(summary.time(), 0) << "Time shouldn't be 0";
}
TEST(Astar, test_time_restricted_road_allowed_on_timedep) {
{
// Pedestrian at hour 13 should be allowed
std::string costing_str("pedestrian");
test_route_allowed(costing_str, 13);
}
{
// A car at hour 22 should be allowed
std::string costing_str("auto");
test_route_allowed(costing_str, 22);
}
}
void test_backtrack_complex_restriction(int date_time_type) {
// Regression test for backtracking complex restriction behaviour.
//
// Test-case documented in https://github.com/valhalla/valhalla/issues/2103
//
auto conf = test::make_config("test/data/bayfront_singapore_tiles");
route_tester tester(conf);
std::string request;
switch (date_time_type) {
case 0:
// Bidir search
request = R"({
"locations": [
{
"lat":1.282185,
"lon":103.859650,
"street":"Sheares Link"
},
{
"lat":1.282493,
"lon":103.859421,
"street":"Sheares Link"
}
],
"costing":"auto"
})";
break;
case 1:
// Forward search
request = R"({
"locations": [
{
"lat":1.282185,
"lon":103.859650,
"street":"Sheares Link"
},
{
"lat":1.282493,
"lon":103.859421,
"street":"Sheares Link"
}
],
"costing":"auto",
"date_time": {
"type": 1,
"value": "2019-05-02T15:00"
}
})";
break;
case 2:
// Backward search with slightly different coordinates
request = R"({
"locations": [
{
"lat":1.282366,
"lon":-256.140661,
"street":"Sheares Link",
"minimum_reachability": 0
},
{
"lat":1.282355,
"lon":-256.140414,
"street":"Sheares Link"
}
],
"costing":"auto",
"date_time": {
"type": 2,
"value": "2019-05-02T15:00"
}
})";
break;
default:
throw std::runtime_error("Unhandled case");
}
LOGLN_WARN(request);
auto response = tester.test(request);
const auto& leg = response.trip().routes(0).legs(0);
std::string correct_shape;
switch (date_time_type) {
case 0:
case 1:
correct_shape =
R"(kggmA_{abeEyDbIaBtCp@Z|d@pYfGdCp]xRnCzArDlB{C`FqDyBwC_BsYmP}KoGsAw@wJmGcUcLo@[qFaDz@aB)";
break;
case 2:
correct_shape =
R"(wrgmAsgabeEy@hBqFaDkBcA_WcNkBw@iX_OuJ}EcIgFcVgL}ZgJoVeE^yEy@uBb@PvQfE|b@bLdIpDd`@|Sh\vQ~XxNfB~@pC}E)";
break;
default:
throw std::runtime_error("unhandled case");
}
EXPECT_TRUE(test::encoded_shape_equality(leg.shape(), correct_shape))
<< "Did not find expected shape. Found \n" + leg.shape() + "\nbut expected \n" + correct_shape;
std::vector<std::string> names;
const auto& directions = response.directions().routes(0).legs();
for (const auto& d : directions) {
for (const auto& m : d.maneuver()) {
std::string name;
for (const auto& n : m.street_name()) {
name += n.value() + " ";
}
if (!name.empty()) {
name.pop_back();
}
names.push_back(name);
}
}
auto correct_route = std::vector<std::string>{"Sheares Link", "Bayfront Avenue", "Bayfront Avenue",
"Sheares Link", ""};
if (names != correct_route) {
throw std::logic_error("Incorrect route, got: \n" + boost::algorithm::join(names, ", ") +
", expected: \n" + boost::algorithm::join(correct_route, ", "));
}
}
TEST(Astar, TestBacktrackComplexRestrictionForward) {
test_backtrack_complex_restriction(1);
}
TEST(Astar, TestBacktrackComplexRestrictionReverse) {
// Reverse direction condition is triggered via use of slightly tweaked start/end coordinates
test_backtrack_complex_restriction(2);
}
TEST(Astar, TestBacktrackComplexRestrictionBidirectional) {
// Bidirectional routed before via the reverse direction search
// So this becomes more of a regression test
test_backtrack_complex_restriction(0);
}
TEST(Astar, TestBacktrackComplexRestrictionForwardDetourAfterRestriction) {
// This tests if a detour _after_ a partial complex restriction is found.
// The other tests with Bayfront Singapore tests with a detour _before_