Search in sources :

Example 16 with PathWrapper

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

the class GraphHopperWebIT method testNoPoints.

@Test
public void testNoPoints() {
    GHRequest req = new GHRequest().addPoint(new GHPoint(49.6724, 11.3494)).addPoint(new GHPoint(49.6550, 11.4180));
    req.getHints().put("instructions", false);
    req.getHints().put("calc_points", false);
    GHResponse res = gh.route(req);
    assertFalse("errors:" + res.getErrors().toString(), res.hasErrors());
    PathWrapper alt = res.getBest();
    assertEquals(0, alt.getPoints().size());
    isBetween(11000, 12000, alt.getDistance());
}
Also used : PathWrapper(com.graphhopper.PathWrapper) GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse) Test(org.junit.Test)

Example 17 with PathWrapper

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

the class PathSimplificationTest method testScenario.

@Test
public void testScenario() {
    Graph g = new GraphBuilder(carManager).create();
    // 0-1-2
    // | | |
    // 3-4-5  9-10
    // | | |  |
    // 6-7-8--*
    NodeAccess na = g.getNodeAccess();
    na.setNode(0, 1.2, 1.0);
    na.setNode(1, 1.2, 1.1);
    na.setNode(2, 1.2, 1.2);
    na.setNode(3, 1.1, 1.0);
    na.setNode(4, 1.1, 1.1);
    na.setNode(5, 1.1, 1.2);
    na.setNode(9, 1.1, 1.3);
    na.setNode(10, 1.1, 1.4);
    na.setNode(6, 1.0, 1.0);
    na.setNode(7, 1.0, 1.1);
    na.setNode(8, 1.0, 1.2);
    ReaderWay w = new ReaderWay(1);
    w.setTag("highway", "tertiary");
    w.setTag("maxspeed", "10");
    EdgeIteratorState tmpEdge;
    tmpEdge = g.edge(0, 1, 10000, true).setName("0-1");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    tmpEdge = g.edge(1, 2, 11000, true).setName("1-2");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    w.setTag("maxspeed", "20");
    tmpEdge = g.edge(0, 3, 11000, true);
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    tmpEdge = g.edge(1, 4, 10000, true).setName("1-4");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    tmpEdge = g.edge(2, 5, 11000, true).setName("5-2");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    w.setTag("maxspeed", "30");
    tmpEdge = g.edge(3, 6, 11000, true).setName("3-6");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    tmpEdge = g.edge(4, 7, 10000, true).setName("4-7");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    tmpEdge = g.edge(5, 8, 10000, true).setName("5-8");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    w.setTag("maxspeed", "40");
    tmpEdge = g.edge(6, 7, 11000, true).setName("6-7");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    tmpEdge = g.edge(7, 8, 10000, true);
    PointList list = new PointList();
    list.add(1.0, 1.15);
    list.add(1.0, 1.16);
    tmpEdge.setWayGeometry(list);
    tmpEdge.setName("7-8");
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    w.setTag("maxspeed", "50");
    // missing edge name
    tmpEdge = g.edge(9, 10, 10000, true);
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    tmpEdge = g.edge(8, 9, 20000, true);
    list.clear();
    list.add(1.0, 1.3);
    list.add(1.0, 1.3001);
    list.add(1.0, 1.3002);
    list.add(1.0, 1.3003);
    tmpEdge.setName("8-9");
    tmpEdge.setWayGeometry(list);
    tmpEdge.setFlags(carManager.handleWayTags(w, carManager.acceptWay(w), 0));
    // Path is: [0 0-1, 3 1-4, 6 4-7, 9 7-8, 11 8-9, 10 9-10]
    Path p = new Dijkstra(g, new ShortestWeighting(carEncoder), tMode).calcPath(0, 10);
    InstructionList wayList = p.calcInstructions(usTR);
    Map<String, List<PathDetail>> details = p.calcDetails(Arrays.asList(DETAILS.AVERAGE_SPEED), new PathDetailsBuilderFactory(), 0);
    PathWrapper pathWrapper = new PathWrapper();
    pathWrapper.setInstructions(wayList);
    pathWrapper.addPathDetails(details);
    pathWrapper.setPoints(p.calcPoints());
    int numberOfPoints = p.calcPoints().size();
    DouglasPeucker douglasPeucker = new DouglasPeucker();
    // Do not simplify anything
    douglasPeucker.setMaxDistance(0);
    PathSimplification ps = new PathSimplification(pathWrapper, douglasPeucker, true);
    ps.simplify();
    assertEquals(numberOfPoints, pathWrapper.getPoints().size());
    pathWrapper = new PathWrapper();
    pathWrapper.setInstructions(wayList);
    pathWrapper.addPathDetails(details);
    pathWrapper.setPoints(p.calcPoints());
    douglasPeucker.setMaxDistance(100000000);
    ps = new PathSimplification(pathWrapper, douglasPeucker, true);
    ps.simplify();
    assertTrue(numberOfPoints > pathWrapper.getPoints().size());
}
Also used : Path(com.graphhopper.routing.Path) NodeAccess(com.graphhopper.storage.NodeAccess) ReaderWay(com.graphhopper.reader.ReaderWay) ShortestWeighting(com.graphhopper.routing.weighting.ShortestWeighting) Dijkstra(com.graphhopper.routing.Dijkstra) Graph(com.graphhopper.storage.Graph) PathWrapper(com.graphhopper.PathWrapper) PathDetailsBuilderFactory(com.graphhopper.util.details.PathDetailsBuilderFactory) GraphBuilder(com.graphhopper.storage.GraphBuilder) List(java.util.List) Test(org.junit.Test)

Example 18 with PathWrapper

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

the class TripFromLabel method createPathWrapper.

PathWrapper createPathWrapper(Translation tr, PointList waypoints, List<Trip.Leg> legs) {
    if (legs.size() > 1 && legs.get(0) instanceof Trip.WalkLeg) {
        final Trip.WalkLeg accessLeg = (Trip.WalkLeg) legs.get(0);
        legs.set(0, new Trip.WalkLeg(accessLeg.departureLocation, new Date(legs.get(1).getDepartureTime().getTime() - (accessLeg.getArrivalTime().getTime() - accessLeg.getDepartureTime().getTime())), accessLeg.edges, accessLeg.geometry, accessLeg.distance, accessLeg.instructions, legs.get(1).getDepartureTime()));
    }
    if (legs.size() > 1 && legs.get(legs.size() - 1) instanceof Trip.WalkLeg) {
        final Trip.WalkLeg egressLeg = (Trip.WalkLeg) legs.get(legs.size() - 1);
        legs.set(legs.size() - 1, new Trip.WalkLeg(egressLeg.departureLocation, legs.get(legs.size() - 2).getArrivalTime(), egressLeg.edges, egressLeg.geometry, egressLeg.distance, egressLeg.instructions, new Date(legs.get(legs.size() - 2).getArrivalTime().getTime() + (egressLeg.getArrivalTime().getTime() - egressLeg.getDepartureTime().getTime()))));
    }
    PathWrapper path = new PathWrapper();
    path.setWaypoints(waypoints);
    path.getLegs().addAll(legs);
    final InstructionList instructions = getInstructions(tr, path.getLegs());
    path.setInstructions(instructions);
    PointList pointsList = new PointList();
    for (Instruction instruction : instructions) {
        pointsList.add(instruction.getPoints());
    }
    path.setPoints(pointsList);
    path.setDistance(path.getLegs().stream().mapToDouble(Trip.Leg::getDistance).sum());
    path.setTime((legs.get(legs.size() - 1).getArrivalTime().toInstant().toEpochMilli() - legs.get(0).getDepartureTime().toInstant().toEpochMilli()));
    path.setNumChanges((int) path.getLegs().stream().filter(l -> l instanceof Trip.PtLeg).filter(l -> !((Trip.PtLeg) l).isInSameVehicleAsPrevious).count() - 1);
    com.graphhopper.gtfs.fare.Trip faresTrip = new com.graphhopper.gtfs.fare.Trip();
    path.getLegs().stream().filter(leg -> leg instanceof Trip.PtLeg).map(leg -> (Trip.PtLeg) leg).findFirst().ifPresent(firstPtLeg -> {
        LocalDateTime firstPtDepartureTime = GtfsHelper.localDateTimeFromDate(firstPtLeg.getDepartureTime());
        path.getLegs().stream().filter(leg -> leg instanceof Trip.PtLeg).map(leg -> (Trip.PtLeg) leg).map(ptLeg -> {
            final GTFSFeed gtfsFeed = gtfsStorage.getGtfsFeeds().get(ptLeg.feed_id);
            return new com.graphhopper.gtfs.fare.Trip.Segment(ptLeg.route_id, Duration.between(firstPtDepartureTime, GtfsHelper.localDateTimeFromDate(ptLeg.getDepartureTime())).getSeconds(), gtfsFeed.stops.get(ptLeg.stops.get(0).stop_id).zone_id, gtfsFeed.stops.get(ptLeg.stops.get(ptLeg.stops.size() - 1).stop_id).zone_id, ptLeg.stops.stream().map(s -> gtfsFeed.stops.get(s.stop_id).zone_id).collect(Collectors.toSet()));
        }).forEach(faresTrip.segments::add);
        Fares.cheapestFare(gtfsStorage.getFares(), faresTrip).ifPresent(amount -> path.setFare(amount.getAmount()));
    });
    return path;
}
Also used : java.util(java.util) Stop(com.conveyal.gtfs.model.Stop) LoggerFactory(org.slf4j.LoggerFactory) LocalDateTime(java.time.LocalDateTime) InstructionsFromEdges(com.graphhopper.routing.InstructionsFromEdges) Duration(java.time.Duration) Geometry(com.vividsolutions.jts.geom.Geometry) Fares(com.graphhopper.gtfs.fare.Fares) StreamSupport(java.util.stream.StreamSupport) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) GtfsRealtime(com.google.transit.realtime.GtfsRealtime) Coordinate(com.vividsolutions.jts.geom.Coordinate) SECONDS(java.time.temporal.ChronoUnit.SECONDS) com.graphhopper.util(com.graphhopper.util) Logger(org.slf4j.Logger) GTFSFeed(com.conveyal.gtfs.GTFSFeed) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Label.reverseEdges(com.graphhopper.reader.gtfs.Label.reverseEdges) Fun(org.mapdb.Fun) Stream(java.util.stream.Stream) StopTime(com.conveyal.gtfs.model.StopTime) PathWrapper(com.graphhopper.PathWrapper) Weighting(com.graphhopper.routing.weighting.Weighting) Trip(com.graphhopper.Trip) GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) LocalDateTime(java.time.LocalDateTime) Trip(com.graphhopper.Trip) PathWrapper(com.graphhopper.PathWrapper) GTFSFeed(com.conveyal.gtfs.GTFSFeed)

Example 19 with PathWrapper

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

the class GraphHopperOSMTest method testVia.

@Test
public void testVia() {
    instance = new GraphHopperOSM().setStoreOnFlush(true).init(new CmdArgs().put("datareader.file", testOsm3).put("prepare.min_network_size", "1").put("graph.flag_encoders", "car")).setGraphHopperLocation(ghLoc);
    instance.importOrLoad();
    // A -> B -> C
    GHPoint first = new GHPoint(11.1, 50);
    GHPoint second = new GHPoint(12, 51);
    GHPoint third = new GHPoint(11.2, 51.9);
    GHResponse rsp12 = instance.route(new GHRequest().addPoint(first).addPoint(second));
    assertFalse("should find 1->2", rsp12.hasErrors());
    assertEquals(147930.5, rsp12.getBest().getDistance(), .1);
    GHResponse rsp23 = instance.route(new GHRequest().addPoint(second).addPoint(third));
    assertFalse("should find 2->3", rsp23.hasErrors());
    assertEquals(176608.9, rsp23.getBest().getDistance(), .1);
    GHResponse grsp = instance.route(new GHRequest().addPoint(first).addPoint(second).addPoint(third));
    assertFalse("should find 1->2->3", grsp.hasErrors());
    PathWrapper rsp = grsp.getBest();
    assertEquals(rsp12.getBest().getDistance() + rsp23.getBest().getDistance(), rsp.getDistance(), 1e-6);
    assertEquals(4, rsp.getPoints().getSize());
    assertEquals(5, rsp.getInstructions().size());
    assertEquals(Instruction.REACHED_VIA, rsp.getInstructions().get(1).getSign());
}
Also used : PathWrapper(com.graphhopper.PathWrapper) CmdArgs(com.graphhopper.util.CmdArgs) GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint) GHResponse(com.graphhopper.GHResponse) Test(org.junit.Test)

Example 20 with PathWrapper

use of com.graphhopper.PathWrapper 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)

Aggregations

PathWrapper (com.graphhopper.PathWrapper)25 GHPoint (com.graphhopper.util.shapes.GHPoint)14 Test (org.junit.Test)14 GHRequest (com.graphhopper.GHRequest)13 GHResponse (com.graphhopper.GHResponse)13 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 Graph (com.graphhopper.storage.Graph)2 NodeAccess (com.graphhopper.storage.NodeAccess)2 PointList (com.graphhopper.util.PointList)2 PathDetail (com.graphhopper.util.details.PathDetail)2 JSONArray (org.json.JSONArray)2 JSONObject (org.json.JSONObject)2 GTFSFeed (com.conveyal.gtfs.GTFSFeed)1 Stop (com.conveyal.gtfs.model.Stop)1 StopTime (com.conveyal.gtfs.model.StopTime)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)1 GtfsRealtime (com.google.transit.realtime.GtfsRealtime)1 GraphHopperAPI (com.graphhopper.GraphHopperAPI)1 Trip (com.graphhopper.Trip)1