Search in sources :

Example 41 with GHResponse

use of com.graphhopper.GHResponse in project graphhopper by graphhopper.

the class Router method route.

public GHResponse route(GHRequest request) {
    try {
        checkNoLegacyParameters(request);
        checkAtLeastOnePoint(request);
        checkIfPointsAreInBounds(request.getPoints());
        checkHeadings(request);
        checkPointHints(request);
        checkCurbsides(request);
        checkNoBlockAreaWithCustomModel(request);
        Solver solver = createSolver(request);
        solver.checkRequest();
        solver.init();
        if (ROUND_TRIP.equalsIgnoreCase(request.getAlgorithm())) {
            if (!(solver instanceof FlexSolver))
                throw new IllegalArgumentException("algorithm=round_trip only works with a flexible algorithm");
            return routeRoundTrip(request, (FlexSolver) solver);
        } else if (ALT_ROUTE.equalsIgnoreCase(request.getAlgorithm())) {
            return routeAlt(request, solver);
        } else {
            return routeVia(request, solver);
        }
    } catch (MultiplePointsNotFoundException ex) {
        GHResponse ghRsp = new GHResponse();
        for (IntCursor p : ex.getPointsNotFound()) {
            ghRsp.addError(new PointNotFoundException("Cannot find point " + p.value + ": " + request.getPoints().get(p.value), p.value));
        }
        return ghRsp;
    } catch (IllegalArgumentException ex) {
        GHResponse ghRsp = new GHResponse();
        ghRsp.addError(ex);
        return ghRsp;
    }
}
Also used : IntCursor(com.carrotsearch.hppc.cursors.IntCursor) PointNotFoundException(com.graphhopper.util.exceptions.PointNotFoundException) GHResponse(com.graphhopper.GHResponse)

Example 42 with GHResponse

use of com.graphhopper.GHResponse in project graphhopper by graphhopper.

the class Router method routeRoundTrip.

protected GHResponse routeRoundTrip(GHRequest request, FlexSolver solver) {
    GHResponse ghRsp = new GHResponse();
    StopWatch sw = new StopWatch().start();
    double startHeading = request.getHeadings().isEmpty() ? Double.NaN : request.getHeadings().get(0);
    RoundTripRouting.Params params = new RoundTripRouting.Params(request.getHints(), startHeading, routerConfig.getMaxRoundTripRetries());
    List<Snap> snaps = RoundTripRouting.lookup(request.getPoints(), solver.createSnapFilter(), locationIndex, params);
    ghRsp.addDebugInfo("idLookup:" + sw.stop().getSeconds() + "s");
    QueryGraph queryGraph = QueryGraph.create(ghStorage, snaps);
    FlexiblePathCalculator pathCalculator = solver.createPathCalculator(queryGraph);
    RoundTripRouting.Result result = RoundTripRouting.calcPaths(snaps, pathCalculator);
    // we merge the different legs of the roundtrip into one response path
    ResponsePath responsePath = concatenatePaths(request, solver.weighting, queryGraph, result.paths, getWaypoints(snaps));
    ghRsp.add(responsePath);
    ghRsp.getHints().putObject("visited_nodes.sum", result.visitedNodes);
    ghRsp.getHints().putObject("visited_nodes.average", (float) result.visitedNodes / (snaps.size() - 1));
    return ghRsp;
}
Also used : ResponsePath(com.graphhopper.ResponsePath) GHResponse(com.graphhopper.GHResponse) Snap(com.graphhopper.storage.index.Snap) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph)

Example 43 with GHResponse

use of com.graphhopper.GHResponse in project graphhopper by graphhopper.

the class Router method routeAlt.

protected GHResponse routeAlt(GHRequest request, Solver solver) {
    if (request.getPoints().size() > 2)
        throw new IllegalArgumentException("Currently alternative routes work only with start and end point. You tried to use: " + request.getPoints().size() + " points");
    GHResponse ghRsp = new GHResponse();
    StopWatch sw = new StopWatch().start();
    DirectedEdgeFilter directedEdgeFilter = solver.createDirectedEdgeFilter();
    List<Snap> snaps = ViaRouting.lookup(encodingManager, request.getPoints(), solver.createSnapFilter(), locationIndex, request.getSnapPreventions(), request.getPointHints(), directedEdgeFilter, request.getHeadings());
    ghRsp.addDebugInfo("idLookup:" + sw.stop().getSeconds() + "s");
    QueryGraph queryGraph = QueryGraph.create(ghStorage, snaps);
    PathCalculator pathCalculator = solver.createPathCalculator(queryGraph);
    boolean passThrough = getPassThrough(request.getHints());
    boolean forceCurbsides = getForceCurbsides(request.getHints());
    if (passThrough)
        throw new IllegalArgumentException("Alternative paths and " + PASS_THROUGH + " at the same time is currently not supported");
    if (!request.getCurbsides().isEmpty())
        throw new IllegalArgumentException("Alternative paths do not support the " + CURBSIDE + " parameter yet");
    ViaRouting.Result result = ViaRouting.calcPaths(request.getPoints(), queryGraph, snaps, directedEdgeFilter, pathCalculator, request.getCurbsides(), forceCurbsides, request.getHeadings(), passThrough);
    if (result.paths.isEmpty())
        throw new RuntimeException("Empty paths for alternative route calculation not expected");
    // each path represents a different alternative and we do the path merging for each of them
    PathMerger pathMerger = createPathMerger(request, solver.weighting, queryGraph);
    for (Path path : result.paths) {
        PointList waypoints = getWaypoints(snaps);
        ResponsePath responsePath = pathMerger.doWork(waypoints, Collections.singletonList(path), encodingManager, translationMap.getWithFallBack(request.getLocale()));
        ghRsp.add(responsePath);
    }
    ghRsp.getHints().putObject("visited_nodes.sum", result.visitedNodes);
    ghRsp.getHints().putObject("visited_nodes.average", (float) result.visitedNodes / (snaps.size() - 1));
    return ghRsp;
}
Also used : ResponsePath(com.graphhopper.ResponsePath) GHResponse(com.graphhopper.GHResponse) Snap(com.graphhopper.storage.index.Snap) ResponsePath(com.graphhopper.ResponsePath) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph)

Example 44 with GHResponse

use of com.graphhopper.GHResponse in project graphhopper by graphhopper.

the class CHMeasurement method runPerformanceTest.

private static void runPerformanceTest(final String algo, final GraphHopper graphHopper, final boolean withTurnCosts, long seed, final int iterations, final PMap results) {
    Graph g = graphHopper.getGraphHopperStorage();
    final int numNodes = g.getNodes();
    final NodeAccess nodeAccess = g.getNodeAccess();
    final Random random = new Random(seed);
    final boolean lm = "lm".equals(algo);
    LOGGER.info("Running performance test for {}, seed = {}", algo, seed);
    final long[] numVisitedNodes = { 0 };
    MiniPerfTest performanceTest = new MiniPerfTest();
    performanceTest.setIterations(iterations).start(new MiniPerfTest.Task() {

        private long queryTime;

        @Override
        public int doCalc(boolean warmup, int run) {
            if (!warmup && run % 100 == 0) {
                LOGGER.info("Finished {} of {} runs. {}", run, iterations, run > 0 ? String.format(Locale.ROOT, " Time: %6.2fms", queryTime * 1.e-6 / run) : "");
            }
            if (run == iterations - 1) {
                String avg = fmt(queryTime * 1.e-6 / run);
                LOGGER.info("Finished all ({}) runs, avg time: {}ms", iterations, avg);
                results.putObject("_" + algo + ".time_ch", avg);
            }
            GHRequest req = buildRandomRequest(random, numNodes, nodeAccess);
            req.putHint(Parameters.CH.DISABLE, lm);
            req.putHint(Parameters.Landmark.DISABLE, !lm);
            req.setProfile("car_profile");
            if (!lm) {
                req.setAlgorithm(algo);
            } else {
                req.putHint(Parameters.Landmark.ACTIVE_COUNT, 8);
            }
            long start = nanoTime();
            GHResponse route = graphHopper.route(req);
            numVisitedNodes[0] += route.getHints().getInt("visited_nodes.sum", 0);
            if (!warmup)
                queryTime += nanoTime() - start;
            return getRealErrors(route).size();
        }
    });
    if (performanceTest.getDummySum() > 0.01 * iterations) {
        throw new IllegalStateException("too many errors, probably something is wrong");
    }
    LOGGER.info("Average query time for {}: {}ms", algo, performanceTest.getMean());
    LOGGER.info("Visited nodes for {}: {}", algo, Helper.nf(numVisitedNodes[0]));
}
Also used : NodeAccess(com.graphhopper.storage.NodeAccess) GHResponse(com.graphhopper.GHResponse) Graph(com.graphhopper.storage.Graph) GHRequest(com.graphhopper.GHRequest)

Example 45 with GHResponse

use of com.graphhopper.GHResponse in project graphhopper by graphhopper.

the class GHResponseDeserializer method deserialize.

@Override
public GHResponse deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    GHResponse ghResponse = new GHResponse();
    JsonNode treeNode = p.readValueAsTree();
    for (JsonNode path : treeNode.get("paths")) {
        ResponsePath responsePath = ((ObjectMapper) p.getCodec()).convertValue(path, ResponsePath.class);
        ghResponse.add(responsePath);
    }
    return ghResponse;
}
Also used : ResponsePath(com.graphhopper.ResponsePath) JsonNode(com.fasterxml.jackson.databind.JsonNode) GHResponse(com.graphhopper.GHResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

GHResponse (com.graphhopper.GHResponse)100 GHRequest (com.graphhopper.GHRequest)86 GHPoint (com.graphhopper.util.shapes.GHPoint)52 Test (org.junit.Test)31 Test (org.junit.jupiter.api.Test)31 GraphHopperWeb (com.graphhopper.api.GraphHopperWeb)20 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)20 ResponsePath (com.graphhopper.ResponsePath)15 EnumSource (org.junit.jupiter.params.provider.EnumSource)11 JsonNode (com.fasterxml.jackson.databind.JsonNode)9 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)9 PathWrapper (com.graphhopper.PathWrapper)9 GraphHopper (com.graphhopper.GraphHopper)7 InstructionList (com.graphhopper.util.InstructionList)7 PathDetail (com.graphhopper.util.details.PathDetail)7 GraphHopperAPI (com.graphhopper.GraphHopperAPI)6 Profile (com.graphhopper.config.Profile)5 Graph (com.graphhopper.storage.Graph)5 NodeAccess (com.graphhopper.storage.NodeAccess)5 PointNotFoundException (com.graphhopper.util.exceptions.PointNotFoundException)5