Search in sources :

Example 6 with ResponsePath

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

the class RoutingExampleTC method route.

private static void route(GraphHopper hopper, GHRequest req, int expectedDistance, int expectedTime) {
    GHResponse rsp = hopper.route(req);
    // handle errors
    if (rsp.hasErrors())
        // you either specify 'curbside=any' or Parameters.Routing.FORCE_CURBSIDE=false to ignore this situation
        throw new RuntimeException(rsp.getErrors().toString());
    ResponsePath path = rsp.getBest();
    assert Math.abs(expectedDistance - path.getDistance()) < 1 : "unexpected distance : " + path.getDistance() + " vs. " + expectedDistance;
    assert Math.abs(expectedTime - path.getTime()) < 1000 : "unexpected time : " + path.getTime() + " vs. " + expectedTime;
}
Also used : ResponsePath(com.graphhopper.ResponsePath) GHResponse(com.graphhopper.GHResponse)

Example 7 with ResponsePath

use of com.graphhopper.ResponsePath 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 8 with ResponsePath

use of com.graphhopper.ResponsePath 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 9 with ResponsePath

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

the class TripFromLabel method createResponsePath.

ResponsePath createResponsePath(Translation tr, PointList waypoints, Graph queryGraph, Weighting accessWeighting, Weighting egressWeighting, List<Label.Transition> solution, List<String> requestedPathDetails) {
    final List<List<Label.Transition>> partitions = parsePathToPartitions(solution);
    final List<Trip.Leg> legs = new ArrayList<>();
    for (int i = 0; i < partitions.size(); i++) {
        legs.addAll(parsePartitionToLegs(partitions.get(i), queryGraph, i == partitions.size() - 1 ? egressWeighting : accessWeighting, tr, requestedPathDetails));
    }
    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.geometry, accessLeg.distance, accessLeg.instructions, accessLeg.details, 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.geometry, egressLeg.distance, egressLeg.instructions, egressLeg.details, new Date(legs.get(legs.size() - 2).getArrivalTime().getTime() + (egressLeg.getArrivalTime().getTime() - egressLeg.getDepartureTime().getTime()))));
    }
    ResponsePath path = new ResponsePath();
    path.setWaypoints(waypoints);
    path.getLegs().addAll(legs);
    final InstructionList instructions = new InstructionList(tr);
    final PointList pointsList = new PointList();
    Map<String, List<PathDetail>> pathDetails = new HashMap<>();
    for (int i = 0; i < path.getLegs().size(); ++i) {
        Trip.Leg leg = path.getLegs().get(i);
        if (leg instanceof Trip.WalkLeg) {
            final Trip.WalkLeg walkLeg = ((Trip.WalkLeg) leg);
            List<Instruction> theseInstructions = walkLeg.instructions.subList(0, i < path.getLegs().size() - 1 ? walkLeg.instructions.size() - 1 : walkLeg.instructions.size());
            int previousPointsCount = pointsList.size();
            for (Instruction instruction : theseInstructions) {
                pointsList.add(instruction.getPoints());
            }
            instructions.addAll(theseInstructions);
            Map<String, List<PathDetail>> shiftedLegPathDetails = shift(((Trip.WalkLeg) leg).details, previousPointsCount);
            shiftedLegPathDetails.forEach((k, v) -> pathDetails.merge(k, shiftedLegPathDetails.get(k), (a, b) -> Lists.newArrayList(Iterables.concat(a, b))));
        } else if (leg instanceof Trip.PtLeg) {
            final Trip.PtLeg ptLeg = ((Trip.PtLeg) leg);
            final PointList pl;
            if (!ptLeg.isInSameVehicleAsPrevious) {
                pl = new PointList();
                final Instruction departureInstruction = new Instruction(Instruction.PT_START_TRIP, ptLeg.trip_headsign, pl);
                departureInstruction.setDistance(leg.getDistance());
                departureInstruction.setTime(ptLeg.travelTime);
                instructions.add(departureInstruction);
            } else {
                pl = instructions.get(instructions.size() - 2).getPoints();
            }
            pl.add(ptLeg.stops.get(0).geometry.getY(), ptLeg.stops.get(0).geometry.getX());
            pointsList.add(ptLeg.stops.get(0).geometry.getY(), ptLeg.stops.get(0).geometry.getX());
            for (Trip.Stop stop : ptLeg.stops.subList(0, ptLeg.stops.size() - 1)) {
                pl.add(stop.geometry.getY(), stop.geometry.getX());
                pointsList.add(stop.geometry.getY(), stop.geometry.getX());
            }
            final PointList arrivalPointList = new PointList();
            final Trip.Stop arrivalStop = ptLeg.stops.get(ptLeg.stops.size() - 1);
            arrivalPointList.add(arrivalStop.geometry.getY(), arrivalStop.geometry.getX());
            pointsList.add(arrivalStop.geometry.getY(), arrivalStop.geometry.getX());
            Instruction arrivalInstruction = new Instruction(Instruction.PT_END_TRIP, arrivalStop.stop_name, arrivalPointList);
            if (ptLeg.isInSameVehicleAsPrevious) {
                instructions.set(instructions.size() - 1, arrivalInstruction);
            } else {
                instructions.add(arrivalInstruction);
            }
        }
    }
    path.setInstructions(instructions);
    path.setPoints(pointsList);
    path.addPathDetails(pathDetails);
    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.feed_id, 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 : Iterables(com.google.common.collect.Iterables) java.util(java.util) Stop(com.conveyal.gtfs.model.Stop) LoggerFactory(org.slf4j.LoggerFactory) LocalDateTime(java.time.LocalDateTime) Coordinate(org.locationtech.jts.geom.Coordinate) GraphHopperStorage(com.graphhopper.storage.GraphHopperStorage) Lists(com.google.common.collect.Lists) ResponsePath(com.graphhopper.ResponsePath) InstructionsFromEdges(com.graphhopper.routing.InstructionsFromEdges) Duration(java.time.Duration) Graph(com.graphhopper.storage.Graph) Fares(com.graphhopper.gtfs.fare.Fares) StreamSupport(java.util.stream.StreamSupport) GtfsRealtime(com.google.transit.realtime.GtfsRealtime) SECONDS(java.time.temporal.ChronoUnit.SECONDS) com.graphhopper.util(com.graphhopper.util) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) Logger(org.slf4j.Logger) PathDetailsBuilderFactory(com.graphhopper.util.details.PathDetailsBuilderFactory) GTFSFeed(com.conveyal.gtfs.GTFSFeed) Path(com.graphhopper.routing.Path) Instant(java.time.Instant) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) PathDetailsFromEdges(com.graphhopper.util.details.PathDetailsFromEdges) Stream(java.util.stream.Stream) StopTime(com.conveyal.gtfs.model.StopTime) Weighting(com.graphhopper.routing.weighting.Weighting) Trip(com.graphhopper.Trip) Geometry(org.locationtech.jts.geom.Geometry) PathDetail(com.graphhopper.util.details.PathDetail) LocalDateTime(java.time.LocalDateTime) Stop(com.conveyal.gtfs.model.Stop) GTFSFeed(com.conveyal.gtfs.GTFSFeed) Trip(com.graphhopper.Trip) ResponsePath(com.graphhopper.ResponsePath)

Example 10 with ResponsePath

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

ResponsePath (com.graphhopper.ResponsePath)29 GHResponse (com.graphhopper.GHResponse)15 GHRequest (com.graphhopper.GHRequest)13 GHPoint (com.graphhopper.util.shapes.GHPoint)11 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)8 Test (org.junit.jupiter.api.Test)7 GraphHopperWeb (com.graphhopper.api.GraphHopperWeb)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 MapMatching (com.graphhopper.matching.MapMatching)4 MatchResult (com.graphhopper.matching.MatchResult)4 Observation (com.graphhopper.matching.Observation)4 EnumSource (org.junit.jupiter.params.provider.EnumSource)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 Path (com.graphhopper.routing.Path)3 QueryGraph (com.graphhopper.routing.querygraph.QueryGraph)3 Snap (com.graphhopper.storage.index.Snap)3 PathDetail (com.graphhopper.util.details.PathDetail)3 ArgumentsSource (org.junit.jupiter.params.provider.ArgumentsSource)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)2