-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
GraphHopper.java
1361 lines (1190 loc) · 64 KB
/
GraphHopper.java
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
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper;
import com.bedatadriven.jackson.datatype.jts.JtsModule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.graphhopper.config.CHProfile;
import com.graphhopper.config.LMProfile;
import com.graphhopper.config.Profile;
import com.graphhopper.jackson.Jackson;
import com.graphhopper.reader.dem.*;
import com.graphhopper.reader.osm.OSMReader;
import com.graphhopper.reader.osm.conditional.DateRangeParser;
import com.graphhopper.routing.*;
import com.graphhopper.routing.ch.CHPreparationHandler;
import com.graphhopper.routing.ch.PrepareContractionHierarchies;
import com.graphhopper.routing.ev.*;
import com.graphhopper.routing.lm.LMConfig;
import com.graphhopper.routing.lm.LMPreparationHandler;
import com.graphhopper.routing.lm.LandmarkStorage;
import com.graphhopper.routing.lm.PrepareLandmarks;
import com.graphhopper.routing.subnetwork.PrepareRoutingSubnetworks;
import com.graphhopper.routing.subnetwork.PrepareRoutingSubnetworks.PrepareJob;
import com.graphhopper.routing.util.*;
import com.graphhopper.routing.util.countryrules.CountryRuleFactory;
import com.graphhopper.routing.util.parsers.*;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.routing.weighting.custom.CustomProfile;
import com.graphhopper.routing.weighting.custom.CustomWeighting;
import com.graphhopper.storage.*;
import com.graphhopper.storage.index.LocationIndex;
import com.graphhopper.storage.index.LocationIndexTree;
import com.graphhopper.util.*;
import com.graphhopper.util.Parameters.Landmark;
import com.graphhopper.util.Parameters.Routing;
import com.graphhopper.util.details.PathDetailsBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static com.graphhopper.util.GHUtility.readCountries;
import static com.graphhopper.util.Helper.*;
import static com.graphhopper.util.Parameters.Algorithms.RoundTrip;
/**
* Easy to use access point to configure import and (offline) routing.
*
* @author Peter Karich
*/
public class GraphHopper {
private static final Logger logger = LoggerFactory.getLogger(GraphHopper.class);
private final Map<String, Profile> profilesByName = new LinkedHashMap<>();
private final String fileLockName = "gh.lock";
// utils
private final TranslationMap trMap = new TranslationMap().doImport();
boolean removeZipped = true;
// for country rules:
private CountryRuleFactory countryRuleFactory = null;
// for custom areas:
private String customAreasDirectory = "";
// for graph:
private BaseGraph baseGraph;
private StorableProperties properties;
private EncodingManager encodingManager;
private OSMParsers osmParsers;
private int defaultSegmentSize = -1;
private String ghLocation = "";
private DAType dataAccessDefaultType = DAType.RAM_STORE;
private final LinkedHashMap<String, String> dataAccessConfig = new LinkedHashMap<>();
private boolean sortGraph = false;
private boolean elevation = false;
private LockFactory lockFactory = new NativeFSLockFactory();
private boolean allowWrites = true;
private boolean fullyLoaded = false;
private final OSMReaderConfig osmReaderConfig = new OSMReaderConfig();
// for routing
private final RouterConfig routerConfig = new RouterConfig();
// for index
private LocationIndex locationIndex;
private int preciseIndexResolution = 300;
private int maxRegionSearch = 4;
// for prepare
private int minNetworkSize = 200;
// preparation handlers
private final LMPreparationHandler lmPreparationHandler = new LMPreparationHandler();
private final CHPreparationHandler chPreparationHandler = new CHPreparationHandler();
private Map<String, RoutingCHGraph> chGraphs = Collections.emptyMap();
private Map<String, LandmarkStorage> landmarks = Collections.emptyMap();
// for data reader
private String osmFile;
private ElevationProvider eleProvider = ElevationProvider.NOOP;
private VehicleEncodedValuesFactory vehicleEncodedValuesFactory = new DefaultVehicleEncodedValuesFactory();
private VehicleTagParserFactory vehicleTagParserFactory = new DefaultVehicleTagParserFactory();
private EncodedValueFactory encodedValueFactory = new DefaultEncodedValueFactory();
private TagParserFactory tagParserFactory = new DefaultTagParserFactory();
private PathDetailsBuilderFactory pathBuilderFactory = new PathDetailsBuilderFactory();
private String dateRangeParserString = "";
private String encodedValuesString = "";
private String flagEncodersString = "";
public GraphHopper setEncodedValuesString(String encodedValuesString) {
this.encodedValuesString = encodedValuesString;
return this;
}
public GraphHopper setFlagEncodersString(String flagEncodersString) {
this.flagEncodersString = flagEncodersString;
return this;
}
public EncodingManager getEncodingManager() {
if (encodingManager == null)
throw new IllegalStateException("EncodingManager not yet built");
return encodingManager;
}
public OSMParsers getOSMParsers() {
if (osmParsers == null)
throw new IllegalStateException("OSMParsers not yet built");
return osmParsers;
}
public ElevationProvider getElevationProvider() {
return eleProvider;
}
public GraphHopper setElevationProvider(ElevationProvider eleProvider) {
if (eleProvider == null || eleProvider == ElevationProvider.NOOP)
setElevation(false);
else
setElevation(true);
this.eleProvider = eleProvider;
return this;
}
public GraphHopper setPathDetailsBuilderFactory(PathDetailsBuilderFactory pathBuilderFactory) {
this.pathBuilderFactory = pathBuilderFactory;
return this;
}
public PathDetailsBuilderFactory getPathDetailsBuilderFactory() {
return pathBuilderFactory;
}
/**
* Precise location resolution index means also more space (disc/RAM) could be consumed and
* probably slower query times, which would be e.g. not suitable for Android. The resolution
* specifies the tile width (in meter).
*/
public GraphHopper setPreciseIndexResolution(int precision) {
ensureNotLoaded();
preciseIndexResolution = precision;
return this;
}
public GraphHopper setMinNetworkSize(int minNetworkSize) {
ensureNotLoaded();
this.minNetworkSize = minNetworkSize;
return this;
}
/**
* Only valid option for in-memory graph and if you e.g. want to disable store on flush for unit
* tests. Specify storeOnFlush to true if you want that existing data will be loaded FROM disc
* and all in-memory data will be flushed TO disc after flush is called e.g. while OSM import.
*
* @param storeOnFlush true by default
*/
public GraphHopper setStoreOnFlush(boolean storeOnFlush) {
ensureNotLoaded();
if (storeOnFlush)
dataAccessDefaultType = DAType.RAM_STORE;
else
dataAccessDefaultType = DAType.RAM;
return this;
}
/**
* Sets the routing profiles that shall be supported by this GraphHopper instance. The (and only the) given profiles
* can be used for routing without preparation and for CH/LM preparation.
* <p>
* Here is an example how to setup two CH profiles and one LM profile (via the Java API)
*
* <pre>
* {@code
* hopper.setProfiles(
* new Profile("my_car").setVehicle("car").setWeighting("shortest"),
* new Profile("your_bike").setVehicle("bike").setWeighting("fastest")
* );
* hopper.getCHPreparationHandler().setCHProfiles(
* new CHProfile("my_car"),
* new CHProfile("your_bike")
* );
* hopper.getLMPreparationHandler().setLMProfiles(
* new LMProfile("your_bike")
* );
* }
* </pre>
* <p>
* See also https://github.com/graphhopper/graphhopper/pull/1922.
*
* @see CHPreparationHandler#setCHProfiles
* @see LMPreparationHandler#setLMProfiles
*/
public GraphHopper setProfiles(Profile... profiles) {
return setProfiles(Arrays.asList(profiles));
}
public GraphHopper setProfiles(List<Profile> profiles) {
if (!profilesByName.isEmpty())
throw new IllegalArgumentException("Cannot initialize profiles multiple times");
if (encodingManager != null)
throw new IllegalArgumentException("Cannot set profiles after EncodingManager was built");
for (Profile profile : profiles) {
Profile previous = this.profilesByName.put(profile.getName(), profile);
if (previous != null)
throw new IllegalArgumentException("Profile names must be unique. Duplicate name: '" + profile.getName() + "'");
}
return this;
}
public List<Profile> getProfiles() {
return new ArrayList<>(profilesByName.values());
}
/**
* Returns the profile for the given profile name, or null if it does not exist
*/
public Profile getProfile(String profileName) {
return profilesByName.get(profileName);
}
/**
* @return true if storing and fetching elevation data is enabled. Default is false
*/
public boolean hasElevation() {
return elevation;
}
/**
* Enable storing and fetching elevation data. Default is false
*/
public GraphHopper setElevation(boolean includeElevation) {
this.elevation = includeElevation;
return this;
}
public String getGraphHopperLocation() {
return ghLocation;
}
/**
* Sets the graphhopper folder.
*/
public GraphHopper setGraphHopperLocation(String ghLocation) {
ensureNotLoaded();
if (ghLocation == null)
throw new IllegalArgumentException("graphhopper location cannot be null");
this.ghLocation = ghLocation;
return this;
}
public String getOSMFile() {
return osmFile;
}
/**
* This file can be an osm xml (.osm), a compressed xml (.osm.zip or .osm.gz) or a protobuf file
* (.pbf).
*/
public GraphHopper setOSMFile(String osmFile) {
ensureNotLoaded();
if (isEmpty(osmFile))
throw new IllegalArgumentException("OSM file cannot be empty.");
this.osmFile = osmFile;
return this;
}
/**
* The underlying graph used in algorithms.
*
* @throws IllegalStateException if graph is not instantiated.
*/
public BaseGraph getBaseGraph() {
if (baseGraph == null)
throw new IllegalStateException("GraphHopper storage not initialized");
return baseGraph;
}
public void setBaseGraph(BaseGraph baseGraph) {
this.baseGraph = baseGraph;
setFullyLoaded();
}
public StorableProperties getProperties() {
return properties;
}
/**
* @return a mapping between profile names and according CH preparations. The map will be empty before loading
* or import.
*/
public Map<String, RoutingCHGraph> getCHGraphs() {
return chGraphs;
}
/**
* @return a mapping between profile names and according landmark preparations. The map will be empty before loading
* or import.
*/
public Map<String, LandmarkStorage> getLandmarks() {
return landmarks;
}
/**
* The location index created from the graph.
*
* @throws IllegalStateException if index is not initialized
*/
public LocationIndex getLocationIndex() {
if (locationIndex == null)
throw new IllegalStateException("LocationIndex not initialized");
return locationIndex;
}
protected void setLocationIndex(LocationIndex locationIndex) {
this.locationIndex = locationIndex;
}
/**
* Sorts the graph which requires more RAM while import. See #12
*/
public GraphHopper setSortGraph(boolean sortGraph) {
ensureNotLoaded();
this.sortGraph = sortGraph;
return this;
}
public boolean isAllowWrites() {
return allowWrites;
}
/**
* Specifies if it is allowed for GraphHopper to write. E.g. for read only filesystems it is not
* possible to create a lock file and so we can avoid write locks.
*/
public GraphHopper setAllowWrites(boolean allowWrites) {
this.allowWrites = allowWrites;
return this;
}
public TranslationMap getTranslationMap() {
return trMap;
}
public GraphHopper setVehicleEncodedValuesFactory(VehicleEncodedValuesFactory factory) {
this.vehicleEncodedValuesFactory = factory;
return this;
}
public EncodedValueFactory getEncodedValueFactory() {
return this.encodedValueFactory;
}
public GraphHopper setEncodedValueFactory(EncodedValueFactory factory) {
this.encodedValueFactory = factory;
return this;
}
public VehicleTagParserFactory getVehicleTagParserFactory() {
return this.vehicleTagParserFactory;
}
public GraphHopper setVehicleTagParserFactory(VehicleTagParserFactory factory) {
this.vehicleTagParserFactory = factory;
return this;
}
public TagParserFactory getTagParserFactory() {
return this.tagParserFactory;
}
public GraphHopper setTagParserFactory(TagParserFactory factory) {
this.tagParserFactory = factory;
return this;
}
public GraphHopper setCustomAreasDirectory(String customAreasDirectory) {
this.customAreasDirectory = customAreasDirectory;
return this;
}
public String getCustomAreasDirectory() {
return this.customAreasDirectory;
}
/**
* Sets the factory used to create country rules. Use `null` to disable country rules
*/
public GraphHopper setCountryRuleFactory(CountryRuleFactory countryRuleFactory) {
this.countryRuleFactory = countryRuleFactory;
return this;
}
public CountryRuleFactory getCountryRuleFactory() {
return this.countryRuleFactory;
}
/**
* Reads the configuration from a {@link GraphHopperConfig} object which can be manually filled, or more typically
* is read from `config.yml`.
* <p>
* Important note: Calling this method overwrites the configuration done in some of the setter methods of this class,
* so generally it is advised to either use this method to configure GraphHopper or the different setter methods,
* but not both. Unfortunately, this still does not cover all cases and sometimes you have to use both, but then you
* should make sure there are no conflicts. If you need both it might also help to call the init before calling the
* setters, because this way the init method won't apply defaults to configuration options you already chose using
* the setters.
*/
public GraphHopper init(GraphHopperConfig ghConfig) {
ensureNotLoaded();
// disabling_allowed config options were removed for GH 3.0
if (ghConfig.has("routing.ch.disabling_allowed"))
throw new IllegalArgumentException("The 'routing.ch.disabling_allowed' configuration option is no longer supported");
if (ghConfig.has("routing.lm.disabling_allowed"))
throw new IllegalArgumentException("The 'routing.lm.disabling_allowed' configuration option is no longer supported");
if (ghConfig.has("osmreader.osm"))
throw new IllegalArgumentException("Instead of osmreader.osm use datareader.file, for other changes see CHANGELOG.md");
String tmpOsmFile = ghConfig.getString("datareader.file", "");
if (!isEmpty(tmpOsmFile))
osmFile = tmpOsmFile;
String graphHopperFolder = ghConfig.getString("graph.location", "");
if (isEmpty(graphHopperFolder) && isEmpty(ghLocation)) {
if (isEmpty(osmFile))
throw new IllegalArgumentException("If no graph.location is provided you need to specify an OSM file.");
graphHopperFolder = pruneFileEnd(osmFile) + "-gh";
}
ghLocation = graphHopperFolder;
countryRuleFactory = ghConfig.getBool("country_rules.enabled", false) ? new CountryRuleFactory() : null;
customAreasDirectory = ghConfig.getString("custom_areas.directory", customAreasDirectory);
defaultSegmentSize = ghConfig.getInt("graph.dataaccess.segment_size", defaultSegmentSize);
String daTypeString = ghConfig.getString("graph.dataaccess.default_type", ghConfig.getString("graph.dataaccess", "RAM_STORE"));
dataAccessDefaultType = DAType.fromString(daTypeString);
for (Map.Entry<String, Object> entry : ghConfig.asPMap().toMap().entrySet()) {
if (entry.getKey().startsWith("graph.dataaccess.type."))
dataAccessConfig.put(entry.getKey().substring("graph.dataaccess.type.".length()), entry.getValue().toString());
if (entry.getKey().startsWith("graph.dataaccess.mmap.preload."))
dataAccessConfig.put(entry.getKey().substring("graph.dataaccess.mmap.".length()), entry.getValue().toString());
}
sortGraph = ghConfig.getBool("graph.do_sort", sortGraph);
removeZipped = ghConfig.getBool("graph.remove_zipped", removeZipped);
if (!ghConfig.getString("spatial_rules.location", "").isEmpty())
throw new IllegalArgumentException("spatial_rules.location has been deprecated. Please use custom_areas.directory instead and read the documentation for custom areas.");
if (!ghConfig.getString("spatial_rules.borders_directory", "").isEmpty())
throw new IllegalArgumentException("spatial_rules.borders_directory has been deprecated. Please use custom_areas.directory instead and read the documentation for custom areas.");
// todo: maybe introduce custom_areas.max_bbox if this is needed later
if (!ghConfig.getString("spatial_rules.max_bbox", "").isEmpty())
throw new IllegalArgumentException("spatial_rules.max_bbox has been deprecated. There is no replacement, all custom areas will be considered.");
setProfiles(ghConfig.getProfiles());
flagEncodersString = ghConfig.getString("graph.flag_encoders", flagEncodersString);
encodedValuesString = ghConfig.getString("graph.encoded_values", encodedValuesString);
dateRangeParserString = ghConfig.getString("datareader.date_range_parser_day", dateRangeParserString);
if (ghConfig.getString("graph.locktype", "native").equals("simple"))
lockFactory = new SimpleFSLockFactory();
else
lockFactory = new NativeFSLockFactory();
// elevation
osmReaderConfig.setSmoothElevation(ghConfig.getBool("graph.elevation.smoothing", osmReaderConfig.isSmoothElevation()));
osmReaderConfig.setLongEdgeSamplingDistance(ghConfig.getDouble("graph.elevation.long_edge_sampling_distance", osmReaderConfig.getLongEdgeSamplingDistance()));
osmReaderConfig.setElevationMaxWayPointDistance(ghConfig.getDouble("graph.elevation.way_point_max_distance", osmReaderConfig.getElevationMaxWayPointDistance()));
routerConfig.setElevationWayPointMaxDistance(ghConfig.getDouble("graph.elevation.way_point_max_distance", routerConfig.getElevationWayPointMaxDistance()));
ElevationProvider elevationProvider = createElevationProvider(ghConfig);
setElevationProvider(elevationProvider);
if (osmReaderConfig.getLongEdgeSamplingDistance() < Double.MAX_VALUE && !elevationProvider.canInterpolate())
logger.warn("Long edge sampling enabled, but bilinear interpolation disabled. See #1953");
// optimizable prepare
minNetworkSize = ghConfig.getInt("prepare.min_network_size", minNetworkSize);
// prepare CH&LM
chPreparationHandler.init(ghConfig);
lmPreparationHandler.init(ghConfig);
// osm import
osmReaderConfig.setParseWayNames(ghConfig.getBool("datareader.instructions", osmReaderConfig.isParseWayNames()));
osmReaderConfig.setPreferredLanguage(ghConfig.getString("datareader.preferred_language", osmReaderConfig.getPreferredLanguage()));
osmReaderConfig.setMaxWayPointDistance(ghConfig.getDouble(Routing.INIT_WAY_POINT_MAX_DISTANCE, osmReaderConfig.getMaxWayPointDistance()));
osmReaderConfig.setWorkerThreads(ghConfig.getInt("datareader.worker_threads", osmReaderConfig.getWorkerThreads()));
// index
preciseIndexResolution = ghConfig.getInt("index.high_resolution", preciseIndexResolution);
maxRegionSearch = ghConfig.getInt("index.max_region_search", maxRegionSearch);
// routing
routerConfig.setMaxVisitedNodes(ghConfig.getInt(Routing.INIT_MAX_VISITED_NODES, routerConfig.getMaxVisitedNodes()));
routerConfig.setMaxRoundTripRetries(ghConfig.getInt(RoundTrip.INIT_MAX_RETRIES, routerConfig.getMaxRoundTripRetries()));
routerConfig.setNonChMaxWaypointDistance(ghConfig.getInt(Parameters.NON_CH.MAX_NON_CH_POINT_DISTANCE, routerConfig.getNonChMaxWaypointDistance()));
routerConfig.setInstructionsEnabled(ghConfig.getBool(Routing.INIT_INSTRUCTIONS, routerConfig.isInstructionsEnabled()));
int activeLandmarkCount = ghConfig.getInt(Landmark.ACTIVE_COUNT_DEFAULT, Math.min(8, lmPreparationHandler.getLandmarks()));
if (activeLandmarkCount > lmPreparationHandler.getLandmarks())
throw new IllegalArgumentException("Default value for active landmarks " + activeLandmarkCount
+ " should be less or equal to landmark count of " + lmPreparationHandler.getLandmarks());
routerConfig.setActiveLandmarkCount(activeLandmarkCount);
return this;
}
private void buildEncodingManagerAndOSMParsers(String flagEncodersStr, String encodedValuesStr, String dateRangeParserString, Collection<Profile> profiles) {
Map<String, String> flagEncodersMap = new LinkedHashMap<>();
for (String encoderStr : flagEncodersStr.split(",")) {
String name = encoderStr.split("\\|")[0].trim();
if (name.isEmpty())
continue;
if (flagEncodersMap.containsKey(name))
throw new IllegalArgumentException("Duplicate flag encoder: " + name + " in: " + encoderStr);
flagEncodersMap.put(name, encoderStr);
}
Map<String, String> flagEncodersFromProfilesMap = new LinkedHashMap<>();
for (Profile profile : profiles) {
// if a profile uses a flag encoder with turn costs make sure we add that flag encoder with turn costs
String vehicle = profile.getVehicle().trim();
if (!flagEncodersFromProfilesMap.containsKey(vehicle) || profile.isTurnCosts())
flagEncodersFromProfilesMap.put(vehicle, vehicle + (profile.isTurnCosts() ? "|turn_costs=true" : ""));
}
// flag encoders from profiles are only taken into account when they were not given explicitly
flagEncodersFromProfilesMap.forEach(flagEncodersMap::putIfAbsent);
List<String> encodedValueStrings = Arrays.stream(encodedValuesStr.split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
EncodingManager.Builder emBuilder = new EncodingManager.Builder();
flagEncodersMap.forEach((name, encoderStr) -> emBuilder.add(vehicleEncodedValuesFactory.createVehicleEncodedValues(name, new PMap(encoderStr))));
profiles.forEach(profile -> emBuilder.add(Subnetwork.create(profile.getName())));
encodedValueStrings.forEach(s -> emBuilder.add(encodedValueFactory.create(s)));
encodingManager = emBuilder.build();
osmParsers = new OSMParsers();
encodedValueStrings.forEach(s -> osmParsers.addWayTagParser(tagParserFactory.create(encodingManager, s)));
// this needs to be in sync with the default EVs added in EncodingManager.Builder#build. ideally I would like to remove
// all these defaults and just use the config as the single source of truth
if (!encodedValueStrings.contains(Roundabout.KEY))
osmParsers.addWayTagParser(new OSMRoundaboutParser(encodingManager.getBooleanEncodedValue(Roundabout.KEY)));
if (!encodedValueStrings.contains(RoadClass.KEY))
osmParsers.addWayTagParser(new OSMRoadClassParser(encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class)));
if (!encodedValueStrings.contains(RoadClassLink.KEY))
osmParsers.addWayTagParser(new OSMRoadClassLinkParser(encodingManager.getBooleanEncodedValue(RoadClassLink.KEY)));
if (!encodedValueStrings.contains(RoadEnvironment.KEY))
osmParsers.addWayTagParser(new OSMRoadEnvironmentParser(encodingManager.getEnumEncodedValue(RoadEnvironment.KEY, RoadEnvironment.class)));
if (!encodedValueStrings.contains(MaxSpeed.KEY))
osmParsers.addWayTagParser(new OSMMaxSpeedParser(encodingManager.getDecimalEncodedValue(MaxSpeed.KEY)));
if (!encodedValueStrings.contains(RoadAccess.KEY))
osmParsers.addWayTagParser(new OSMRoadAccessParser(encodingManager.getEnumEncodedValue(RoadAccess.KEY, RoadAccess.class), OSMRoadAccessParser.toOSMRestrictions(TransportationMode.CAR)));
DateRangeParser dateRangeParser = DateRangeParser.createInstance(dateRangeParserString);
flagEncodersMap.forEach((name, encoderStr) -> {
VehicleTagParser vehicleTagParser = vehicleTagParserFactory.createParser(encodingManager, name, new PMap(encoderStr));
vehicleTagParser.init(dateRangeParser);
if (vehicleTagParser instanceof BikeCommonTagParser) {
if (encodingManager.hasEncodedValue(BikeNetwork.KEY))
osmParsers.addRelationTagParser(relConfig -> new OSMBikeNetworkTagParser(encodingManager.getEnumEncodedValue(BikeNetwork.KEY, RouteNetwork.class), relConfig));
if (encodingManager.hasEncodedValue(GetOffBike.KEY))
osmParsers.addWayTagParser(new OSMGetOffBikeParser(encodingManager.getBooleanEncodedValue(GetOffBike.KEY)));
if (encodingManager.hasEncodedValue(Smoothness.KEY))
osmParsers.addWayTagParser(new OSMSmoothnessParser(encodingManager.getEnumEncodedValue(Smoothness.KEY, Smoothness.class)));
} else if (vehicleTagParser instanceof FootTagParser) {
if (encodingManager.hasEncodedValue(FootNetwork.KEY))
osmParsers.addRelationTagParser(relConfig -> new OSMFootNetworkTagParser(encodingManager.getEnumEncodedValue(FootNetwork.KEY, RouteNetwork.class), relConfig));
}
osmParsers.addVehicleTagParser(vehicleTagParser);
});
}
private static ElevationProvider createElevationProvider(GraphHopperConfig ghConfig) {
String eleProviderStr = toLowerCase(ghConfig.getString("graph.elevation.provider", "noop"));
if (ghConfig.has("graph.elevation.calcmean"))
throw new IllegalArgumentException("graph.elevation.calcmean is deprecated, use graph.elevation.interpolate");
String cacheDirStr = ghConfig.getString("graph.elevation.cache_dir", "");
if (cacheDirStr.isEmpty() && ghConfig.has("graph.elevation.cachedir"))
throw new IllegalArgumentException("use graph.elevation.cache_dir not cachedir in configuration");
ElevationProvider elevationProvider = ElevationProvider.NOOP;
if (eleProviderStr.equalsIgnoreCase("srtm")) {
elevationProvider = new SRTMProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("cgiar")) {
elevationProvider = new CGIARProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("gmted")) {
elevationProvider = new GMTEDProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("srtmgl1")) {
elevationProvider = new SRTMGL1Provider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("multi")) {
elevationProvider = new MultiSourceElevationProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("skadi")) {
elevationProvider = new SkadiProvider(cacheDirStr);
}
if (elevationProvider instanceof TileBasedElevationProvider) {
TileBasedElevationProvider provider = (TileBasedElevationProvider) elevationProvider;
String baseURL = ghConfig.getString("graph.elevation.base_url", "");
if (baseURL.isEmpty() && ghConfig.has("graph.elevation.baseurl"))
throw new IllegalArgumentException("use graph.elevation.base_url not baseurl in configuration");
DAType elevationDAType = DAType.fromString(ghConfig.getString("graph.elevation.dataaccess", "MMAP"));
boolean interpolate = ghConfig.has("graph.elevation.interpolate")
? "bilinear".equals(ghConfig.getString("graph.elevation.interpolate", "none"))
: ghConfig.getBool("graph.elevation.calc_mean", false);
boolean removeTempElevationFiles = ghConfig.getBool("graph.elevation.cgiar.clear", true);
removeTempElevationFiles = ghConfig.getBool("graph.elevation.clear", removeTempElevationFiles);
provider
.setAutoRemoveTemporaryFiles(removeTempElevationFiles)
.setInterpolate(interpolate)
.setDAType(elevationDAType);
if (!baseURL.isEmpty())
provider.setBaseURL(baseURL);
}
return elevationProvider;
}
private void printInfo() {
logger.info("version " + Constants.VERSION + "|" + Constants.BUILD_DATE + " (" + Constants.getVersions() + ")");
if (baseGraph != null)
logger.info("graph " + getBaseGraphString() + ", details:" + baseGraph.toDetailsString());
}
private String getBaseGraphString() {
return encodingManager
+ "|" + baseGraph.getDirectory().getDefaultType()
+ "|" + baseGraph.getNodeAccess().getDimension() + "D"
+ "|" + (baseGraph.getTurnCostStorage() != null ? baseGraph.getTurnCostStorage() : "no_turn_cost")
+ "|" + getVersionsString();
}
private String getVersionsString() {
return "nodes:" + Constants.VERSION_NODE +
",edges:" + Constants.VERSION_EDGE +
",geometry:" + Constants.VERSION_GEOMETRY +
",location_index:" + Constants.VERSION_LOCATION_IDX +
",string_index:" + Constants.VERSION_EDGEKV_STORAGE +
",nodesCH:" + Constants.VERSION_NODE_CH +
",shortcuts:" + Constants.VERSION_SHORTCUT;
}
/**
* Imports provided data from disc and creates graph. Depending on the settings the resulting
* graph will be stored to disc so on a second call this method will only load the graph from
* disc which is usually a lot faster.
*/
public GraphHopper importOrLoad() {
if (!load()) {
printInfo();
process(false);
} else {
printInfo();
}
return this;
}
/**
* Imports and processes data, storing it to disk when complete.
*/
public void importAndClose() {
if (!load()) {
printInfo();
process(true);
} else {
printInfo();
logger.info("Graph already imported into " + ghLocation);
}
close();
}
/**
* Creates the graph from OSM data.
*/
private void process(boolean closeEarly) {
GHDirectory directory = new GHDirectory(ghLocation, dataAccessDefaultType);
directory.configure(dataAccessConfig);
buildEncodingManagerAndOSMParsers(flagEncodersString, encodedValuesString, dateRangeParserString, profilesByName.values());
baseGraph = new BaseGraph.Builder(getEncodingManager())
.setDir(directory)
.set3D(hasElevation())
.withTurnCosts(encodingManager.needsTurnCostsSupport())
.setSegmentSize(defaultSegmentSize)
.build();
properties = new StorableProperties(directory);
checkProfilesConsistency();
GHLock lock = null;
try {
if (directory.getDefaultType().isStoring()) {
lockFactory.setLockDir(new File(ghLocation));
lock = lockFactory.create(fileLockName, true);
if (!lock.tryLock())
throw new RuntimeException("To avoid multiple writers we need to obtain a write lock but it failed. In " + ghLocation, lock.getObtainFailedReason());
}
ensureWriteAccess();
importOSM();
cleanUp();
postImport();
postProcessing(closeEarly);
flush();
} finally {
if (lock != null)
lock.release();
}
}
protected void postImport() {
if (sortGraph) {
BaseGraph newGraph = GHUtility.newGraph(baseGraph);
GHUtility.sortDFS(baseGraph, newGraph);
logger.info("graph sorted (" + getMemInfo() + ")");
baseGraph = newGraph;
}
if (hasElevation())
interpolateBridgesTunnelsAndFerries();
}
protected void importOSM() {
if (osmFile == null)
throw new IllegalStateException("Couldn't load from existing folder: " + ghLocation
+ " but also cannot use file for DataReader as it wasn't specified!");
List<CustomArea> customAreas = readCountries();
if (isEmpty(customAreasDirectory)) {
logger.info("No custom areas are used, custom_areas.directory not given");
} else {
logger.info("Creating custom area index, reading custom areas from: '" + customAreasDirectory + "'");
customAreas.addAll(readCustomAreas());
}
AreaIndex<CustomArea> areaIndex = new AreaIndex<>(customAreas);
if (countryRuleFactory == null || countryRuleFactory.getCountryToRuleMap().isEmpty()) {
logger.info("No country rules available");
} else {
logger.info("Applying rules for the following countries: {}", countryRuleFactory.getCountryToRuleMap().keySet());
}
logger.info("start creating graph from " + osmFile);
OSMReader reader = new OSMReader(baseGraph.getBaseGraph(), encodingManager, osmParsers, osmReaderConfig).setFile(_getOSMFile()).
setAreaIndex(areaIndex).
setElevationProvider(eleProvider).
setCountryRuleFactory(countryRuleFactory);
logger.info("using " + getBaseGraphString() + ", memory:" + getMemInfo());
createBaseGraphAndProperties();
try {
reader.readGraph();
} catch (IOException ex) {
throw new RuntimeException("Cannot read file " + getOSMFile(), ex);
}
DateFormat f = createFormatter();
properties.put("datareader.import.date", f.format(new Date()));
if (reader.getDataDate() != null)
properties.put("datareader.data.date", f.format(reader.getDataDate()));
}
protected void createBaseGraphAndProperties() {
baseGraph.getDirectory().create();
baseGraph.create(100);
properties.create(100);
properties.put("graph.em.version", Constants.VERSION_EM);
properties.put("graph.em.edge_config", encodingManager.toEdgeConfigAsString());
properties.put("graph.em.turn_cost_config", encodingManager.toTurnCostConfigAsString());
properties.put("graph.encoded_values", encodingManager.toEncodedValuesAsString());
}
private List<CustomArea> readCustomAreas() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JtsModule());
final Path bordersDirectory = Paths.get(customAreasDirectory);
List<JsonFeatureCollection> jsonFeatureCollections = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(bordersDirectory, "*.{geojson,json}")) {
for (Path borderFile : stream) {
try (BufferedReader reader = Files.newBufferedReader(borderFile, StandardCharsets.UTF_8)) {
JsonFeatureCollection jsonFeatureCollection = objectMapper.readValue(reader, JsonFeatureCollection.class);
jsonFeatureCollections.add(jsonFeatureCollection);
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return jsonFeatureCollections.stream().flatMap(j -> j.getFeatures().stream())
.map(CustomArea::fromJsonFeature)
.collect(Collectors.toList());
}
/**
* Currently we use this for a few tests where the dataReaderFile is loaded from the classpath
*/
protected File _getOSMFile() {
return new File(osmFile);
}
/**
* Load from existing graph folder.
*/
public boolean load() {
if (isEmpty(ghLocation))
throw new IllegalStateException("GraphHopperLocation is not specified. Call setGraphHopperLocation or init before");
if (fullyLoaded)
throw new IllegalStateException("graph is already successfully loaded");
File tmpFileOrFolder = new File(ghLocation);
if (!tmpFileOrFolder.isDirectory() && tmpFileOrFolder.exists()) {
throw new IllegalArgumentException("GraphHopperLocation cannot be an existing file. Has to be either non-existing or a folder.");
} else {
File compressed = new File(ghLocation + ".ghz");
if (compressed.exists() && !compressed.isDirectory()) {
try {
new Unzipper().unzip(compressed.getAbsolutePath(), ghLocation, removeZipped);
} catch (IOException ex) {
throw new RuntimeException("Couldn't extract file " + compressed.getAbsolutePath()
+ " to " + ghLocation, ex);
}
}
}
// todo: this does not really belong here, we abuse the load method to derive the dataAccessDefaultType setting from others
if (!allowWrites && dataAccessDefaultType.isMMap())
dataAccessDefaultType = DAType.MMAP_RO;
if (!new File(ghLocation).exists())
// there is just nothing to load
return false;
GHDirectory directory = new GHDirectory(ghLocation, dataAccessDefaultType);
directory.configure(dataAccessConfig);
GHLock lock = null;
try {
// create locks only if writes are allowed, if they are not allowed a lock cannot be created
// (e.g. on a read only filesystem locks would fail)
if (directory.getDefaultType().isStoring() && isAllowWrites()) {
lockFactory.setLockDir(new File(ghLocation));
lock = lockFactory.create(fileLockName, false);
if (!lock.tryLock())
throw new RuntimeException("To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation, lock.getObtainFailedReason());
}
properties = new StorableProperties(directory);
if (!properties.loadExisting())
// the -gh folder exists, but there is no properties file. it might be just empty, so let's act as if
// the import did not run yet or is not complete for some reason
return false;
loadEncodingManagerFromProperties(properties);
baseGraph = new BaseGraph.Builder(getEncodingManager())
.setDir(directory)
.set3D(hasElevation())
.withTurnCosts(encodingManager.needsTurnCostsSupport())
.setSegmentSize(defaultSegmentSize)
.build();
baseGraph.loadExisting();
checkProfilesConsistency();
String storedProfiles = properties.get("profiles");
String configuredProfiles = getProfilesString();
if (!storedProfiles.equals(configuredProfiles))
throw new IllegalStateException("Profiles do not match:"
+ "\nGraphhopper config: " + configuredProfiles
+ "\nGraph: " + storedProfiles
+ "\nChange configuration to match the graph or delete " + baseGraph.getDirectory().getLocation());
postProcessing(false);
directory.loadMMap();
setFullyLoaded();
return true;
} finally {
if (lock != null)
lock.release();
}
}
private void loadEncodingManagerFromProperties(StorableProperties properties) {
if (properties.containsVersion())
throw new IllegalStateException("The GraphHopper file format is not compatible with the data you are " +
"trying to load. You either need to use an older version of GraphHopper or run a new import");
String versionStr = properties.get("graph.em.version");
if (versionStr.isEmpty() || !String.valueOf(Constants.VERSION_EM).equals(versionStr))
throw new IllegalStateException("Incompatible encoding version. You need to use the same GraphHopper version you used to import the graph, or run a new import. "
+ " Stored encoding version: " + (versionStr.isEmpty() ? "missing" : versionStr) + ", used encoding version: " + Constants.VERSION_EM);
String encodedValueStr = properties.get("graph.encoded_values");
ArrayNode evList = deserializeEncodedValueList(encodedValueStr);
LinkedHashMap<String, EncodedValue> encodedValues = new LinkedHashMap<>();
evList.forEach(serializedEV -> {
EncodedValue encodedValue = EncodedValueSerializer.deserializeEncodedValue(serializedEV.textValue());
if (encodedValues.put(encodedValue.getName(), encodedValue) != null)
throw new IllegalStateException("Duplicate encoded value name: " + encodedValue.getName() + " in: graph.encoded_values=" + encodedValueStr);
});
EncodedValue.InitializerConfig edgeConfig = EncodedValueSerializer.deserializeInitializerConfig(properties.get("graph.em.edge_config"));
EncodedValue.InitializerConfig turnCostConfig = EncodedValueSerializer.deserializeInitializerConfig(properties.get("graph.em.turn_cost_config"));
encodingManager = new EncodingManager(encodedValues, edgeConfig, turnCostConfig);
}
private ArrayNode deserializeEncodedValueList(String encodedValueStr) {
try {
return Jackson.newObjectMapper().readValue(encodedValueStr, ArrayNode.class);
} catch (JsonProcessingException e) {
throw new UncheckedIOException(e);
}
}
private String getProfilesString() {
return profilesByName.values().stream().map(p -> p.getName() + "|" + p.getVersion()).collect(Collectors.joining(","));
}
private void checkProfilesConsistency() {
if (profilesByName.isEmpty())
throw new IllegalArgumentException("There has to be at least one profile");
EncodingManager encodingManager = getEncodingManager();
for (Profile profile : profilesByName.values()) {
String accessEncName = EncodingManager.getKey(profile.getVehicle(), "access");
String speedEncName = EncodingManager.getKey(profile.getVehicle(), "average_speed");
if (!encodingManager.hasEncodedValue(accessEncName) || !encodingManager.hasEncodedValue(speedEncName))
throw new IllegalArgumentException("Unknown vehicle '" + profile.getVehicle() + "' in profile: " + profile + ". " +
"Encoded values " + accessEncName + " and " + speedEncName + " are required");
DecimalEncodedValue turnCostEnc = encodingManager.hasEncodedValue(TurnCost.key(profile.getVehicle()))
? encodingManager.getDecimalEncodedValue(TurnCost.key(profile.getVehicle()))
: null;
if (profile.isTurnCosts() && turnCostEnc == null) {
throw new IllegalArgumentException("The profile '" + profile.getName() + "' was configured with " +
"'turn_costs=true', but the corresponding vehicle '" + profile.getVehicle() + "' does not support turn costs." +
"\nYou need to add `|turn_costs=true` to the vehicle in `graph.flag_encoders`");
}
try {
createWeighting(profile, new PMap());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Could not create weighting for profile: '" + profile.getName() + "'.\n" +
"Profile: " + profile + "\n" +
"Error: " + e.getMessage());
}
if (profile instanceof CustomProfile) {
CustomModel customModel = ((CustomProfile) profile).getCustomModel();
if (customModel == null)
throw new IllegalArgumentException("custom model for profile '" + profile.getName() + "' was empty");
if (!CustomWeighting.NAME.equals(profile.getWeighting()))
throw new IllegalArgumentException("profile '" + profile.getName() + "' has a custom model but " +
"weighting=" + profile.getWeighting() + " was defined");
}
}