use of com.graphhopper.routing.ch.PrepareContractionHierarchies in project graphhopper by graphhopper.
the class GraphHopper method calcPaths.
/**
* This method calculates the alternative path list using the low level Path objects.
*/
public List<Path> calcPaths(GHRequest request, GHResponse ghRsp) {
if (ghStorage == null || !fullyLoaded)
throw new IllegalStateException("Do a successful call to load or importOrLoad before routing");
if (ghStorage.isClosed())
throw new IllegalStateException("You need to create a new GraphHopper instance as it is already closed");
// default handling
String vehicle = request.getVehicle();
if (vehicle.isEmpty()) {
vehicle = getDefaultVehicle().toString();
request.setVehicle(vehicle);
}
Lock readLock = readWriteLock.readLock();
readLock.lock();
try {
if (!encodingManager.supports(vehicle))
throw new IllegalArgumentException("Vehicle " + vehicle + " unsupported. " + "Supported are: " + getEncodingManager());
HintsMap hints = request.getHints();
String tModeStr = hints.get("traversal_mode", traversalMode.toString());
TraversalMode tMode = TraversalMode.fromString(tModeStr);
if (hints.has(Routing.EDGE_BASED))
tMode = hints.getBool(Routing.EDGE_BASED, false) ? TraversalMode.EDGE_BASED_2DIR : TraversalMode.NODE_BASED;
FlagEncoder encoder = encodingManager.getEncoder(vehicle);
boolean forceFlexibleMode = hints.getBool(CH.DISABLE, false);
if (!chFactoryDecorator.isDisablingAllowed() && forceFlexibleMode)
throw new IllegalArgumentException("Flexible mode not enabled on the server-side");
String algoStr = request.getAlgorithm();
if (algoStr.isEmpty())
algoStr = chFactoryDecorator.isEnabled() && !forceFlexibleMode && !(lmFactoryDecorator.isEnabled() && !hints.getBool(Landmark.DISABLE, false)) ? DIJKSTRA_BI : ASTAR_BI;
List<GHPoint> points = request.getPoints();
// TODO Maybe we should think about a isRequestValid method that checks all that stuff that we could do to fail fast
// For example see #734
checkIfPointsAreInBounds(points);
RoutingTemplate routingTemplate;
if (ROUND_TRIP.equalsIgnoreCase(algoStr))
routingTemplate = new RoundTripRoutingTemplate(request, ghRsp, locationIndex, maxRoundTripRetries);
else if (ALT_ROUTE.equalsIgnoreCase(algoStr))
routingTemplate = new AlternativeRoutingTemplate(request, ghRsp, locationIndex);
else
routingTemplate = new ViaRoutingTemplate(request, ghRsp, locationIndex);
List<Path> altPaths = null;
int maxRetries = routingTemplate.getMaxRetries();
Locale locale = request.getLocale();
Translation tr = trMap.getWithFallBack(locale);
for (int i = 0; i < maxRetries; i++) {
StopWatch sw = new StopWatch().start();
List<QueryResult> qResults = routingTemplate.lookup(points, encoder);
ghRsp.addDebugInfo("idLookup:" + sw.stop().getSeconds() + "s");
if (ghRsp.hasErrors())
return Collections.emptyList();
RoutingAlgorithmFactory tmpAlgoFactory = getAlgorithmFactory(hints);
Weighting weighting;
QueryGraph queryGraph;
if (chFactoryDecorator.isEnabled() && !forceFlexibleMode) {
boolean forceCHHeading = hints.getBool(CH.FORCE_HEADING, false);
if (!forceCHHeading && request.hasFavoredHeading(0))
throw new IllegalArgumentException("Heading is not (fully) supported for CHGraph. See issue #483");
// if LM is enabled we have the LMFactory with the CH algo!
RoutingAlgorithmFactory chAlgoFactory = tmpAlgoFactory;
if (tmpAlgoFactory instanceof LMAlgoFactoryDecorator.LMRAFactory)
chAlgoFactory = ((LMAlgoFactoryDecorator.LMRAFactory) tmpAlgoFactory).getDefaultAlgoFactory();
if (chAlgoFactory instanceof PrepareContractionHierarchies)
weighting = ((PrepareContractionHierarchies) chAlgoFactory).getWeighting();
else
throw new IllegalStateException("Although CH was enabled a non-CH algorithm factory was returned " + tmpAlgoFactory);
tMode = getCHFactoryDecorator().getNodeBase();
queryGraph = new QueryGraph(ghStorage.getGraph(CHGraph.class, weighting));
queryGraph.lookup(qResults);
} else {
checkNonChMaxWaypointDistance(points);
queryGraph = new QueryGraph(ghStorage);
queryGraph.lookup(qResults);
weighting = createWeighting(hints, encoder, queryGraph);
ghRsp.addDebugInfo("tmode:" + tMode.toString());
}
int maxVisitedNodesForRequest = hints.getInt(Routing.MAX_VISITED_NODES, maxVisitedNodes);
if (maxVisitedNodesForRequest > maxVisitedNodes)
throw new IllegalArgumentException("The max_visited_nodes parameter has to be below or equal to:" + maxVisitedNodes);
weighting = createTurnWeighting(queryGraph, weighting, tMode);
AlgorithmOptions algoOpts = AlgorithmOptions.start().algorithm(algoStr).traversalMode(tMode).weighting(weighting).maxVisitedNodes(maxVisitedNodesForRequest).hints(hints).build();
altPaths = routingTemplate.calcPaths(queryGraph, tmpAlgoFactory, algoOpts);
boolean tmpEnableInstructions = hints.getBool(Routing.INSTRUCTIONS, enableInstructions);
boolean tmpCalcPoints = hints.getBool(Routing.CALC_POINTS, calcPoints);
double wayPointMaxDistance = hints.getDouble(Routing.WAY_POINT_MAX_DISTANCE, 1d);
DouglasPeucker peucker = new DouglasPeucker().setMaxDistance(wayPointMaxDistance);
PathMerger pathMerger = new PathMerger().setCalcPoints(tmpCalcPoints).setDouglasPeucker(peucker).setEnableInstructions(tmpEnableInstructions).setSimplifyResponse(simplifyResponse && wayPointMaxDistance > 0);
if (routingTemplate.isReady(pathMerger, tr))
break;
}
return altPaths;
} catch (IllegalArgumentException ex) {
ghRsp.addError(ex);
return Collections.emptyList();
} finally {
readLock.unlock();
}
}
use of com.graphhopper.routing.ch.PrepareContractionHierarchies in project graphhopper by graphhopper.
the class GraphHopperOSMTest method testMultipleCHPreparationsInParallel.
@Test
public void testMultipleCHPreparationsInParallel() {
HashMap<String, Integer> shortcutCountMap = new HashMap<String, Integer>();
// try all parallelization modes
for (int threadCount = 1; threadCount < 6; threadCount++) {
EncodingManager em = new EncodingManager(Arrays.asList(new CarFlagEncoder(), new MotorcycleFlagEncoder(), new MountainBikeFlagEncoder(), new RacingBikeFlagEncoder(), new FootFlagEncoder()), 8);
GraphHopper tmpGH = new GraphHopperOSM().setStoreOnFlush(false).setEncodingManager(em).setGraphHopperLocation(ghLoc).setDataReaderFile(testOsm);
tmpGH.getCHFactoryDecorator().setPreparationThreads(threadCount);
tmpGH.importOrLoad();
assertEquals(5, tmpGH.getCHFactoryDecorator().getPreparations().size());
for (RoutingAlgorithmFactory raf : tmpGH.getCHFactoryDecorator().getPreparations()) {
PrepareContractionHierarchies pch = (PrepareContractionHierarchies) raf;
assertTrue("Preparation wasn't run! [" + threadCount + "]", pch.isPrepared());
String name = AbstractWeighting.weightingToFileName(pch.getWeighting());
Integer singleThreadShortcutCount = shortcutCountMap.get(name);
if (singleThreadShortcutCount == null)
shortcutCountMap.put(name, pch.getShortcuts());
else
assertEquals((int) singleThreadShortcutCount, pch.getShortcuts());
String keyError = Parameters.CH.PREPARE + "error." + name;
String valueError = tmpGH.getGraphHopperStorage().getProperties().get(keyError);
assertTrue("Properties for " + name + " should NOT contain error " + valueError + " [" + threadCount + "]", valueError.isEmpty());
String key = Parameters.CH.PREPARE + "date." + name;
String value = tmpGH.getGraphHopperStorage().getProperties().get(key);
assertTrue("Properties for " + name + " did NOT contain finish date [" + threadCount + "]", !value.isEmpty());
}
tmpGH.close();
}
}
use of com.graphhopper.routing.ch.PrepareContractionHierarchies in project graphhopper by graphhopper.
the class GraphHopperOSMTest method testLoadOSMNoCH.
@Test
public void testLoadOSMNoCH() {
GraphHopper gh = new GraphHopperOSM().setStoreOnFlush(true).setCHEnabled(false).setEncodingManager(new EncodingManager("car")).setGraphHopperLocation(ghLoc).setDataReaderFile(testOsm);
gh.importOrLoad();
assertFalse(gh.getAlgorithmFactory(new HintsMap("fastest")) instanceof PrepareContractionHierarchies);
GHResponse rsp = gh.route(new GHRequest(51.2492152, 9.4317166, 51.2, 9.4));
assertFalse(rsp.hasErrors());
assertEquals(3, rsp.getBest().getPoints().getSize());
gh.close();
gh = new GraphHopperOSM().setStoreOnFlush(true).setCHEnabled(false).setEncodingManager(new EncodingManager("car"));
assertTrue(gh.load(ghLoc));
rsp = gh.route(new GHRequest(51.2492152, 9.4317166, 51.2, 9.4));
assertFalse(rsp.hasErrors());
assertEquals(3, rsp.getBest().getPoints().getSize());
gh.close();
gh = new GraphHopperOSM().setGraphHopperLocation(ghLoc).setDataReaderFile(testOsm).init(new CmdArgs().put("graph.flag_encoders", "car").put(Parameters.CH.PREPARE + "weightings", "no"));
assertFalse(gh.getAlgorithmFactory(new HintsMap("fastest")) instanceof PrepareContractionHierarchies);
gh.close();
}
use of com.graphhopper.routing.ch.PrepareContractionHierarchies in project graphhopper by graphhopper.
the class GraphHopperOSMTest method testGetWeightingForCH.
@Test
public void testGetWeightingForCH() {
TestEncoder truck = new TestEncoder("truck");
TestEncoder simpleTruck = new TestEncoder("simple_truck");
// use simple truck first
EncodingManager em = new EncodingManager(simpleTruck, truck);
CHAlgoFactoryDecorator decorator = new CHAlgoFactoryDecorator();
Weighting fwSimpleTruck = new FastestWeighting(simpleTruck);
Weighting fwTruck = new FastestWeighting(truck);
RAMDirectory ramDir = new RAMDirectory();
GraphHopperStorage storage = new GraphHopperStorage(Arrays.asList(fwSimpleTruck, fwTruck), ramDir, em, false, new GraphExtension.NoOpExtension());
decorator.addWeighting(fwSimpleTruck);
decorator.addWeighting(fwTruck);
decorator.addPreparation(new PrepareContractionHierarchies(ramDir, storage, storage.getGraph(CHGraph.class, fwSimpleTruck), fwSimpleTruck, TraversalMode.NODE_BASED));
decorator.addPreparation(new PrepareContractionHierarchies(ramDir, storage, storage.getGraph(CHGraph.class, fwTruck), fwTruck, TraversalMode.NODE_BASED));
HintsMap wMap = new HintsMap("fastest");
wMap.put("vehicle", "truck");
assertEquals("fastest|truck", ((PrepareContractionHierarchies) decorator.getDecoratedAlgorithmFactory(null, wMap)).getWeighting().toString());
wMap.put("vehicle", "simple_truck");
assertEquals("fastest|simple_truck", ((PrepareContractionHierarchies) decorator.getDecoratedAlgorithmFactory(null, wMap)).getWeighting().toString());
// make sure weighting cannot be mixed
decorator.addWeighting(fwTruck);
decorator.addWeighting(fwSimpleTruck);
try {
decorator.addPreparation(new PrepareContractionHierarchies(ramDir, storage, storage.getGraph(CHGraph.class, fwSimpleTruck), fwSimpleTruck, TraversalMode.NODE_BASED));
assertTrue(false);
} catch (Exception ex) {
}
}
Aggregations