Search in sources :

Example 61 with GHResponse

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

the class GraphHopperOSMTest method testGetPathsDirectionEnforcement4.

@Test
public void testGetPathsDirectionEnforcement4() {
    // Test straight via routing
    instance = createSquareGraphInstance(false);
    // Start in middle of edge 4-5
    GHPoint start = new GHPoint(0.0015, 0.002);
    // End at middle of edge 2-3
    GHPoint end = new GHPoint(0.002, 0.0005);
    // Via Point betweeen 8-3
    GHPoint via = new GHPoint(0.0015, 0.001);
    GHRequest req = new GHRequest().addPoint(start).addPoint(via).addPoint(end);
    req.getHints().put(Routing.PASS_THROUGH, true);
    GHResponse response = new GHResponse();
    List<Path> paths = instance.calcPaths(req, response);
    assertFalse(response.hasErrors());
    assertEquals(1, response.getAll().size());
    assertEquals(IntArrayList.from(9, 4, 3, 10), paths.get(0).calcNodes());
    assertEquals(IntArrayList.from(10, 8, 1, 2, 11), paths.get(1).calcNodes());
}
Also used : GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse) Test(org.junit.Test)

Example 62 with GHResponse

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

the class GraphHopperOSMTest method testGetPathsDirectionEnforcement2.

@Test
public void testGetPathsDirectionEnforcement2() {
    // Test enforce south start direction and east end direction
    instance = createSquareGraphInstance(false);
    // Start in middle of edge 4-5
    GHPoint start = new GHPoint(0.0015, 0.002);
    // End at middle of edge 2-3
    GHPoint end = new GHPoint(0.002, 0.0005);
    GHRequest req = new GHRequest().addPoint(start, 180.).addPoint(end, 90.);
    GHResponse response = new GHResponse();
    List<Path> paths = instance.calcPaths(req, response);
    assertFalse(response.hasErrors());
    assertArrayEquals(new int[] { 9, 5, 8, 1, 2, 10 }, paths.get(0).calcNodes().toArray());
    // Test uni-directional case
    req.setAlgorithm(DIJKSTRA);
    response = new GHResponse();
    paths = instance.calcPaths(req, response);
    assertFalse(response.hasErrors());
    assertArrayEquals(new int[] { 9, 5, 8, 1, 2, 10 }, paths.get(0).calcNodes().toArray());
}
Also used : GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse) Test(org.junit.Test)

Example 63 with GHResponse

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

the class Measurement method printTimeOfRouteQuery.

private void printTimeOfRouteQuery(final GraphHopper hopper, final boolean ch, final boolean lm, int count, String prefix, final String vehicle, final boolean withInstructions, final int activeLandmarks, final boolean sod) {
    final Graph g = hopper.getGraphHopperStorage();
    final AtomicLong maxDistance = new AtomicLong(0);
    final AtomicLong minDistance = new AtomicLong(Long.MAX_VALUE);
    final AtomicLong distSum = new AtomicLong(0);
    final AtomicLong airDistSum = new AtomicLong(0);
    final AtomicInteger failedCount = new AtomicInteger(0);
    final DistanceCalc distCalc = new DistanceCalcEarth();
    final AtomicLong visitedNodesSum = new AtomicLong(0);
    // final AtomicLong extractTimeSum = new AtomicLong(0);
    // final AtomicLong calcPointsTimeSum = new AtomicLong(0);
    // final AtomicLong calcDistTimeSum = new AtomicLong(0);
    // final AtomicLong tmpDist = new AtomicLong(0);
    final Random rand = new Random(seed);
    final NodeAccess na = g.getNodeAccess();
    MiniPerfTest miniPerf = new MiniPerfTest() {

        @Override
        public int doCalc(boolean warmup, int run) {
            int from = rand.nextInt(maxNode);
            int to = rand.nextInt(maxNode);
            double fromLat = na.getLatitude(from);
            double fromLon = na.getLongitude(from);
            double toLat = na.getLatitude(to);
            double toLon = na.getLongitude(to);
            GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).setWeighting("fastest").setVehicle(vehicle);
            req.getHints().put(CH.DISABLE, !ch).put("stall_on_demand", sod).put(Landmark.DISABLE, !lm).put(Landmark.ACTIVE_COUNT, activeLandmarks).put("instructions", withInstructions);
            if (withInstructions)
                req.setPathDetails(Arrays.asList(Parameters.DETAILS.AVERAGE_SPEED));
            // put(algo + ".approximation", "BeelineSimplification").
            // put(algo + ".epsilon", 2);
            GHResponse rsp;
            try {
                rsp = hopper.route(req);
            } catch (Exception ex) {
                // 'not found' can happen if import creates more than one subnetwork
                throw new RuntimeException("Error while calculating route! " + "nodes:" + from + " -> " + to + ", request:" + req, ex);
            }
            if (rsp.hasErrors()) {
                if (!warmup)
                    failedCount.incrementAndGet();
                if (rsp.getErrors().get(0).getMessage() == null)
                    rsp.getErrors().get(0).printStackTrace();
                else if (!toLowerCase(rsp.getErrors().get(0).getMessage()).contains("not found"))
                    logger.error("errors should NOT happen in Measurement! " + req + " => " + rsp.getErrors());
                return 0;
            }
            PathWrapper arsp = rsp.getBest();
            if (!warmup) {
                visitedNodesSum.addAndGet(rsp.getHints().getLong("visited_nodes.sum", 0));
                long dist = (long) arsp.getDistance();
                distSum.addAndGet(dist);
                airDistSum.addAndGet((long) distCalc.calcDist(fromLat, fromLon, toLat, toLon));
                if (dist > maxDistance.get())
                    maxDistance.set(dist);
                if (dist < minDistance.get())
                    minDistance.set(dist);
            // extractTimeSum.addAndGet(p.getExtractTime());
            // long start = System.nanoTime();
            // size = p.calcPoints().getSize();
            // calcPointsTimeSum.addAndGet(System.nanoTime() - start);
            }
            return arsp.getPoints().getSize();
        }
    }.setIterations(count).start();
    count -= failedCount.get();
    // if using non-bidirectional algorithm make sure you exclude CH routing
    String algoStr = ch ? Algorithms.DIJKSTRA_BI : Algorithms.ASTAR_BI;
    if (ch && !sod) {
        algoStr += "_no_sod";
    }
    put(prefix + ".guessed_algorithm", algoStr);
    put(prefix + ".failed_count", failedCount.get());
    put(prefix + ".distance_min", minDistance.get());
    put(prefix + ".distance_mean", (float) distSum.get() / count);
    put(prefix + ".air_distance_mean", (float) airDistSum.get() / count);
    put(prefix + ".distance_max", maxDistance.get());
    put(prefix + ".visited_nodes_mean", (float) visitedNodesSum.get() / count);
    // put(prefix + ".extractTime", (float) extractTimeSum.get() / count / 1000000f);
    // put(prefix + ".calcPointsTime", (float) calcPointsTimeSum.get() / count / 1000000f);
    // put(prefix + ".calcDistTime", (float) calcDistTimeSum.get() / count / 1000000f);
    print(prefix, miniPerf);
}
Also used : NodeAccess(com.graphhopper.storage.NodeAccess) GHResponse(com.graphhopper.GHResponse) IOException(java.io.IOException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Graph(com.graphhopper.storage.Graph) CHGraph(com.graphhopper.storage.CHGraph) PathWrapper(com.graphhopper.PathWrapper) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GHRequest(com.graphhopper.GHRequest)

Example 64 with GHResponse

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

the class GraphHopperServlet method doGet.

@Override
public void doGet(HttpServletRequest httpReq, HttpServletResponse httpRes) throws ServletException, IOException {
    List<GHPoint> requestPoints = getPoints(httpReq, "point");
    GHResponse ghRsp = new GHResponse();
    double minPathPrecision = getDoubleParam(httpReq, WAY_POINT_MAX_DISTANCE, 1d);
    boolean writeGPX = "gpx".equalsIgnoreCase(getParam(httpReq, "type", "json"));
    boolean enableInstructions = writeGPX || getBooleanParam(httpReq, INSTRUCTIONS, true);
    boolean calcPoints = getBooleanParam(httpReq, CALC_POINTS, true);
    boolean enableElevation = getBooleanParam(httpReq, "elevation", false);
    boolean pointsEncoded = getBooleanParam(httpReq, "points_encoded", true);
    String vehicleStr = getParam(httpReq, "vehicle", "car");
    String weighting = getParam(httpReq, "weighting", "fastest");
    String algoStr = getParam(httpReq, "algorithm", "");
    String localeStr = getParam(httpReq, "locale", "en");
    StopWatch sw = new StopWatch().start();
    if (!ghRsp.hasErrors()) {
        try {
            if (requestPoints.isEmpty()) {
                throw new IllegalArgumentException("You have to pass at least one point");
            }
            List<Double> favoredHeadings = Collections.EMPTY_LIST;
            try {
                favoredHeadings = getDoubleParamList(httpReq, "heading");
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("heading list in wrong format: " + e.getMessage());
            }
            if (!encodingManager.supports(vehicleStr)) {
                throw new IllegalArgumentException("Vehicle not supported: " + vehicleStr);
            } else if (enableElevation && !hasElevation) {
                throw new IllegalArgumentException("Elevation not supported!");
            } else if (favoredHeadings.size() > 1 && favoredHeadings.size() != requestPoints.size()) {
                throw new IllegalArgumentException("The number of 'heading' parameters must be <= 1 " + "or equal to the number of points (" + requestPoints.size() + ")");
            }
            List<String> pointHints = Arrays.asList(getParams(httpReq, POINT_HINT));
            if (pointHints.size() > 0 && pointHints.size() != requestPoints.size()) {
                throw new IllegalArgumentException("If you pass " + POINT_HINT + ", you need to pass a hint for every point, empty hints will be ignored");
            }
            List<String> pathDetails = Arrays.asList(getParams(httpReq, PATH_DETAILS));
            FlagEncoder algoVehicle = encodingManager.getEncoder(vehicleStr);
            GHRequest request;
            if (favoredHeadings.size() > 0) {
                // if only one favored heading is specified take as start heading
                if (favoredHeadings.size() == 1) {
                    List<Double> paddedHeadings = new ArrayList<Double>(Collections.nCopies(requestPoints.size(), Double.NaN));
                    paddedHeadings.set(0, favoredHeadings.get(0));
                    request = new GHRequest(requestPoints, paddedHeadings);
                } else {
                    request = new GHRequest(requestPoints, favoredHeadings);
                }
            } else {
                request = new GHRequest(requestPoints);
            }
            initHints(request.getHints(), httpReq.getParameterMap());
            request.setVehicle(algoVehicle.toString()).setWeighting(weighting).setAlgorithm(algoStr).setLocale(localeStr).setPointHints(pointHints).setPathDetails(pathDetails).getHints().put(CALC_POINTS, calcPoints).put(INSTRUCTIONS, enableInstructions).put(WAY_POINT_MAX_DISTANCE, minPathPrecision);
            ghRsp = graphHopper.route(request);
        } catch (IllegalArgumentException ex) {
            ghRsp.addError(ex);
        }
    }
    float took = sw.stop().getSeconds();
    String infoStr = httpReq.getRemoteAddr() + " " + httpReq.getLocale() + " " + httpReq.getHeader("User-Agent");
    String logStr = httpReq.getQueryString() + " " + infoStr + " " + requestPoints + ", took:" + took + ", " + algoStr + ", " + weighting + ", " + vehicleStr;
    httpRes.setHeader("X-GH-Took", "" + Math.round(took * 1000));
    int alternatives = ghRsp.getAll().size();
    if (writeGPX && alternatives > 1)
        ghRsp.addError(new IllegalArgumentException("Alternatives are currently not yet supported for GPX"));
    if (ghRsp.hasErrors()) {
        logger.error(logStr + ", errors:" + ghRsp.getErrors());
    } else {
        PathWrapper altRsp0 = ghRsp.getBest();
        logger.info(logStr + ", alternatives: " + alternatives + ", distance0: " + altRsp0.getDistance() + ", time0: " + Math.round(altRsp0.getTime() / 60000f) + "min" + ", points0: " + altRsp0.getPoints().getSize() + ", debugInfo: " + ghRsp.getDebugInfo());
    }
    if (writeGPX) {
        if (ghRsp.hasErrors()) {
            httpRes.setStatus(SC_BAD_REQUEST);
            httpRes.getWriter().append(errorsToXML(ghRsp.getErrors()));
        } else {
            // no error => we can now safely call getFirst
            String xml = createGPXString(httpReq, httpRes, ghRsp.getBest());
            writeResponse(httpRes, xml);
        }
    } else {
        Map<String, Object> map = routeSerializer.toJSON(ghRsp, calcPoints, pointsEncoded, enableElevation, enableInstructions);
        Object infoMap = map.get("info");
        if (infoMap != null)
            ((Map) infoMap).put("took", Math.round(took * 1000));
        if (ghRsp.hasErrors())
            writeJsonError(httpRes, SC_BAD_REQUEST, objectMapper.getNodeFactory().pojoNode(map));
        else {
            writeJson(httpReq, httpRes, objectMapper.getNodeFactory().pojoNode(map));
        }
    }
}
Also used : FlagEncoder(com.graphhopper.routing.util.FlagEncoder) GHResponse(com.graphhopper.GHResponse) GHPoint(com.graphhopper.util.shapes.GHPoint) StopWatch(com.graphhopper.util.StopWatch) PathWrapper(com.graphhopper.PathWrapper) GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint)

Example 65 with GHResponse

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

the class GraphHopperServletIT method testPathDetailsNoConnection.

@Test
public void testPathDetailsNoConnection() throws Exception {
    GraphHopperAPI hopper = new com.graphhopper.api.GraphHopperWeb();
    assertTrue(hopper.load(getTestRouteAPIUrl()));
    GHRequest request = new GHRequest(42.542078, 1.45586, 42.537841, 1.439981);
    request.setPathDetails(Arrays.asList("average_speed"));
    GHResponse rsp = hopper.route(request);
    assertTrue(rsp.getErrors().toString(), rsp.hasErrors());
}
Also used : GraphHopperAPI(com.graphhopper.GraphHopperAPI) GHRequest(com.graphhopper.GHRequest) GHResponse(com.graphhopper.GHResponse) Test(org.junit.Test)

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