Search in sources :

Example 76 with GHRequest

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

the class GraphHopperServletIT method testPathDetailsSamePoint.

@Test
public void testPathDetailsSamePoint() throws Exception {
    GraphHopperAPI hopper = new com.graphhopper.api.GraphHopperWeb();
    assertTrue(hopper.load(getTestRouteAPIUrl()));
    GHRequest request = new GHRequest(42.554851, 1.536198, 42.554851, 1.536198);
    request.setPathDetails(Arrays.asList("average_speed", "edge_id", "time"));
    GHResponse rsp = hopper.route(request);
    assertFalse(rsp.getErrors().toString(), rsp.hasErrors());
    assertTrue(rsp.getErrors().toString(), rsp.getErrors().isEmpty());
}
Also used : GraphHopperAPI(com.graphhopper.GraphHopperAPI) GHRequest(com.graphhopper.GHRequest) GHResponse(com.graphhopper.GHResponse) Test(org.junit.Test)

Example 77 with GHRequest

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

the class GraphHopperServletIT method testGraphHopperWebRealExceptions.

@Test
public void testGraphHopperWebRealExceptions() {
    GraphHopperAPI hopper = new com.graphhopper.api.GraphHopperWeb();
    assertTrue(hopper.load(getTestRouteAPIUrl()));
    // IllegalArgumentException (Wrong Request)
    GHResponse rsp = hopper.route(new GHRequest());
    assertFalse("Errors expected but not found.", rsp.getErrors().isEmpty());
    Throwable ex = rsp.getErrors().get(0);
    assertTrue("Wrong exception found: " + ex.getClass().getName() + ", IllegalArgumentException expected.", ex instanceof IllegalArgumentException);
    // IllegalArgumentException (Wrong Points)
    rsp = hopper.route(new GHRequest(0.0, 0.0, 0.0, 0.0));
    assertFalse("Errors expected but not found.", rsp.getErrors().isEmpty());
    List<Throwable> errs = rsp.getErrors();
    for (int i = 0; i < errs.size(); i++) {
        assertEquals(((PointOutOfBoundsException) errs.get(i)).getPointIndex(), i);
    }
    // IllegalArgumentException (Vehicle not supported)
    rsp = hopper.route(new GHRequest(42.554851, 1.536198, 42.510071, 1.548128).setVehicle("SPACE-SHUTTLE"));
    assertFalse("Errors expected but not found.", rsp.getErrors().isEmpty());
    ex = rsp.getErrors().get(0);
    assertTrue("Wrong exception found: " + ex.getClass().getName() + ", IllegalArgumentException expected.", ex instanceof IllegalArgumentException);
}
Also used : GraphHopperAPI(com.graphhopper.GraphHopperAPI) GHRequest(com.graphhopper.GHRequest) GHResponse(com.graphhopper.GHResponse) GHPoint(com.graphhopper.util.shapes.GHPoint) Test(org.junit.Test)

Example 78 with GHRequest

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

the class CHImportTest method runQueries.

private static void runQueries(GraphHopper hopper, String profile) {
    // Bavaria, but trying to avoid regions that are not covered
    BBox bounds = new BBox(10.508422, 12.326602, 47.713457, 49.940615);
    int numQueries = 10_000;
    long seed = 123;
    Random rnd = new Random(seed);
    AtomicInteger notFoundCount = new AtomicInteger();
    MiniPerfTest test = new MiniPerfTest().setIterations(numQueries).start((warmup, run) -> {
        GHPoint from = getRandomPoint(rnd, bounds);
        GHPoint to = getRandomPoint(rnd, bounds);
        GHRequest req = new GHRequest(from, to).setProfile(profile);
        GHResponse rsp = hopper.route(req);
        if (rsp.hasErrors()) {
            if (rsp.getErrors().stream().anyMatch(t -> !(t instanceof PointNotFoundException || t instanceof ConnectionNotFoundException)))
                throw new IllegalStateException("Unexpected error: " + rsp.getErrors().toString());
            notFoundCount.incrementAndGet();
            return 0;
        } else {
            return (int) rsp.getBest().getRouteWeight();
        }
    });
    System.out.println("Total queries: " + numQueries + ", Failed queries: " + notFoundCount.get());
    System.out.println(test.getReport());
}
Also used : ConnectionNotFoundException(com.graphhopper.util.exceptions.ConnectionNotFoundException) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BBox(com.graphhopper.util.shapes.BBox) PointNotFoundException(com.graphhopper.util.exceptions.PointNotFoundException) GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse) GHPoint(com.graphhopper.util.shapes.GHPoint) MiniPerfTest(com.graphhopper.util.MiniPerfTest)

Example 79 with GHRequest

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

the class CHMeasurement method runCompareTest.

private static void runCompareTest(final String algo, final GraphHopper graphHopper, final boolean withTurnCosts, final int uTurnCosts, long seed, final int iterations, final double threshold, final PMap results) {
    LOGGER.info("Running compare test for {}, using seed {}", algo, seed);
    Graph g = graphHopper.getGraphHopperStorage();
    final int numNodes = g.getNodes();
    final NodeAccess nodeAccess = g.getNodeAccess();
    final Random random = new Random(seed);
    MiniPerfTest compareTest = new MiniPerfTest();
    compareTest.setIterations(iterations).start(new MiniPerfTest.Task() {

        long chTime = 0;

        long noChTime = 0;

        long chErrors = 0;

        long noChErrors = 0;

        long chDeviations = 0;

        @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, " CH: %6.2fms, without CH: %6.2fms", chTime * 1.e-6 / run, noChTime * 1.e-6 / run) : "");
            }
            if (run == iterations - 1) {
                String avgChTime = fmt(chTime * 1.e-6 / run);
                String avgNoChTime = fmt(noChTime * 1.e-6 / run);
                LOGGER.info("Finished all ({}) runs, CH: {}ms, without CH: {}ms", iterations, avgChTime, avgNoChTime);
                results.putObject("_" + algo + ".time_comp_ch", avgChTime);
                results.putObject("_" + algo + ".time_comp", avgNoChTime);
                results.putObject("_" + algo + ".errors_ch", chErrors);
                results.putObject("_" + algo + ".errors", noChErrors);
                results.putObject("_" + algo + ".deviations", chDeviations);
            }
            GHRequest req = buildRandomRequest(random, numNodes, nodeAccess);
            req.setProfile("car_profile");
            req.getHints().putObject(Parameters.CH.DISABLE, false);
            req.getHints().putObject(Parameters.Landmark.DISABLE, true);
            req.getHints().putObject(Parameters.Routing.U_TURN_COSTS, uTurnCosts);
            req.setAlgorithm(algo);
            long start = nanoTime();
            GHResponse chRoute = graphHopper.route(req);
            if (!warmup)
                chTime += (nanoTime() - start);
            req.getHints().putObject(Parameters.CH.DISABLE, true);
            start = nanoTime();
            GHResponse nonChRoute = graphHopper.route(req);
            if (!warmup)
                noChTime += nanoTime() - start;
            if (connectionNotFound(chRoute) && connectionNotFound(nonChRoute)) {
                // random query was not well defined -> ignore
                return 0;
            }
            if (!chRoute.getErrors().isEmpty() || !nonChRoute.getErrors().isEmpty()) {
                LOGGER.warn("there were errors for {}: \n with CH: {} \n without CH: {}", algo, chRoute.getErrors(), nonChRoute.getErrors());
                if (!chRoute.getErrors().isEmpty()) {
                    chErrors++;
                }
                if (!nonChRoute.getErrors().isEmpty()) {
                    noChErrors++;
                }
                return chRoute.getErrors().size();
            }
            double chWeight = chRoute.getBest().getRouteWeight();
            double nonCHWeight = nonChRoute.getBest().getRouteWeight();
            if (Math.abs(chWeight - nonCHWeight) > threshold) {
                LOGGER.warn("error for {}: difference between best paths with and without CH is above threshold ({}), {}", algo, threshold, getWeightDifferenceString(chWeight, nonCHWeight));
                chDeviations++;
            }
            if (!chRoute.getBest().getPoints().equals(nonChRoute.getBest().getPoints())) {
                // small negative deviations are due to weight truncation when shortcuts are stored
                LOGGER.warn("error for {}: found different points for query from {} to {}, {}", algo, req.getPoints().get(0).toShortString(), req.getPoints().get(1).toShortString(), getWeightDifferenceString(chWeight, nonCHWeight));
            }
            return chRoute.getErrors().size();
        }
    });
}
Also used : NodeAccess(com.graphhopper.storage.NodeAccess) Graph(com.graphhopper.storage.Graph) GHRequest(com.graphhopper.GHRequest) GHResponse(com.graphhopper.GHResponse)

Example 80 with GHRequest

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

the class RoutingExample method customizableRouting.

public static void customizableRouting(String ghLoc) {
    GraphHopper hopper = new GraphHopper();
    hopper.setOSMFile(ghLoc);
    hopper.setGraphHopperLocation("target/routing-custom-graph-cache");
    hopper.setProfiles(new CustomProfile("car_custom").setCustomModel(new CustomModel()).setVehicle("car"));
    // The hybrid mode uses the "landmark algorithm" and is up to 15x faster than the flexible mode (Dijkstra).
    // Still it is slower than the speed mode ("contraction hierarchies algorithm") ...
    hopper.getLMPreparationHandler().setLMProfiles(new LMProfile("car_custom"));
    hopper.importOrLoad();
    // ... but for the hybrid mode we can customize the route calculation even at request time:
    // 1. a request with default preferences
    GHRequest req = new GHRequest().setProfile("car_custom").addPoint(new GHPoint(42.506472, 1.522475)).addPoint(new GHPoint(42.513108, 1.536005));
    GHResponse res = hopper.route(req);
    if (res.hasErrors())
        throw new RuntimeException(res.getErrors().toString());
    assert Math.round(res.getBest().getTime() / 1000d) == 96;
    // 2. now avoid primary roads and reduce maximum speed, see docs/core/custom-models.md for an in-depth explanation
    // and also the blog posts https://www.graphhopper.com/?s=customizable+routing
    CustomModel model = new CustomModel();
    model.addToPriority(If("road_class == PRIMARY", MULTIPLY, 0.5));
    // unconditional limit to 100km/h
    model.addToPriority(If("true", LIMIT, 100));
    req.setCustomModel(model);
    res = hopper.route(req);
    if (res.hasErrors())
        throw new RuntimeException(res.getErrors().toString());
    assert Math.round(res.getBest().getTime() / 1000d) == 165;
}
Also used : GHRequest(com.graphhopper.GHRequest) CustomProfile(com.graphhopper.routing.weighting.custom.CustomProfile) LMProfile(com.graphhopper.config.LMProfile) GraphHopper(com.graphhopper.GraphHopper) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse)

Aggregations

GHRequest (com.graphhopper.GHRequest)106 GHResponse (com.graphhopper.GHResponse)86 GHPoint (com.graphhopper.util.shapes.GHPoint)59 Test (org.junit.Test)35 Test (org.junit.jupiter.api.Test)35 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)26 GraphHopperWeb (com.graphhopper.api.GraphHopperWeb)22 ResponsePath (com.graphhopper.ResponsePath)13 EnumSource (org.junit.jupiter.params.provider.EnumSource)11 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)9 JsonNode (com.fasterxml.jackson.databind.JsonNode)8 PathWrapper (com.graphhopper.PathWrapper)8 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 LMProfile (com.graphhopper.config.LMProfile)4