Search in sources :

Example 1 with TrivialRemainingWeightHeuristic

use of org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic in project OpenTripPlanner by opentripplanner.

the class NearbyStopFinder method findNearbyStopsViaStreets.

/**
 * Return all stops within a certain radius of the given vertex, using network distance along streets.
 * If the origin vertex is a StopVertex, the result will include it.
 *
 * @param originVertices the origin point of the street search
 * @param reverseDirection if true the paths returned instead originate at the nearby stops and have the
 *                         originVertex as the destination
 * @param removeTempEdges after creating a new routing request and routing context, remove all the temporary
 *                        edges that are part of that context. NOTE: this will remove _all_ temporary edges
 *                        coming out of the origin and destination vertices, including those in any other
 *                        RoutingContext referencing them, making routing from/to them totally impossible.
 *                        This is a stopgap solution until we rethink the lifecycle of RoutingContext.
 */
public List<StopAtDistance> findNearbyStopsViaStreets(Set<Vertex> originVertices, boolean reverseDirection, boolean removeTempEdges, RoutingRequest routingRequest) {
    routingRequest.arriveBy = reverseDirection;
    if (!reverseDirection) {
        routingRequest.setRoutingContext(graph, originVertices, null);
    } else {
        routingRequest.setRoutingContext(graph, null, originVertices);
    }
    int walkTime = (int) (radiusMeters / new RoutingRequest().walkSpeed);
    routingRequest.worstTime = routingRequest.dateTime + (reverseDirection ? -walkTime : walkTime);
    routingRequest.disableRemainingWeightHeuristic = true;
    routingRequest.rctx.remainingWeightHeuristic = new TrivialRemainingWeightHeuristic();
    routingRequest.dominanceFunction = new DominanceFunction.MinimumWeight();
    ShortestPathTree spt = astar.getShortestPathTree(routingRequest);
    List<StopAtDistance> stopsFound = Lists.newArrayList();
    Multimap<FlexStopLocation, State> locationsMap = ArrayListMultimap.create();
    if (spt != null) {
        // TODO use GenericAStar and a traverseVisitor? Add an earliestArrival switch to genericAStar?
        for (State state : spt.getAllStates()) {
            Vertex targetVertex = state.getVertex();
            if (originVertices.contains(targetVertex))
                continue;
            if (targetVertex instanceof TransitStopVertex && state.isFinal()) {
                stopsFound.add(StopAtDistance.stopAtDistanceForState(state, ((TransitStopVertex) targetVertex).getStop()));
            }
            if (OTPFeature.FlexRouting.isOn() && targetVertex instanceof StreetVertex && ((StreetVertex) targetVertex).flexStopLocations != null) {
                for (FlexStopLocation flexStopLocation : ((StreetVertex) targetVertex).flexStopLocations) {
                    // This is for a simplification, so that we only return one vertex from each
                    // stop location. All vertices are added to the multimap, which is filtered
                    // below, so that only the closest vertex is added to stopsFound
                    locationsMap.put(flexStopLocation, state);
                }
            }
        }
    }
    for (var locationStates : locationsMap.asMap().entrySet()) {
        FlexStopLocation flexStopLocation = locationStates.getKey();
        Collection<State> states = locationStates.getValue();
        // Select the vertex from all vertices that are reachable per FlexStopLocation by taking
        // the minimum walking distance
        State min = Collections.min(states, (s1, s2) -> (int) (s1.walkDistance - s2.walkDistance));
        stopsFound.add(StopAtDistance.stopAtDistanceForState(min, flexStopLocation));
    }
    /* Add the origin vertices if needed. The SPT does not include the initial state. FIXME shouldn't it? */
    for (Vertex vertex : originVertices) {
        if (vertex instanceof TransitStopVertex) {
            stopsFound.add(new StopAtDistance((TransitStopVertex) vertex, 0, Collections.emptyList(), null, new State(vertex, routingRequest)));
        }
    }
    if (removeTempEdges) {
        routingRequest.cleanup();
    }
    return stopsFound;
}
Also used : TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) Vertex(org.opentripplanner.routing.graph.Vertex) StreetVertex(org.opentripplanner.routing.vertextype.StreetVertex) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) State(org.opentripplanner.routing.core.State) TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest) StopAtDistance(org.opentripplanner.routing.graphfinder.StopAtDistance) FlexStopLocation(org.opentripplanner.model.FlexStopLocation) StreetVertex(org.opentripplanner.routing.vertextype.StreetVertex) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction)

Example 2 with TrivialRemainingWeightHeuristic

use of org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic in project OpenTripPlanner by opentripplanner.

the class WalkableAreaBuilder method pruneAreaEdges.

/**
 * Do an all-pairs shortest path search from a list of vertices over a specified set of edges,
 * and retain only those edges which are actually used in some shortest path.
 *
 * @param startingVertices
 * @param edges
 */
private void pruneAreaEdges(Collection<Vertex> startingVertices, Set<Edge> edges) {
    if (edges.size() == 0)
        return;
    TraverseMode mode;
    StreetEdge firstEdge = (StreetEdge) edges.iterator().next();
    if (firstEdge.getPermission().allows(StreetTraversalPermission.PEDESTRIAN)) {
        mode = TraverseMode.WALK;
    } else if (firstEdge.getPermission().allows(StreetTraversalPermission.BICYCLE)) {
        mode = TraverseMode.BICYCLE;
    } else {
        mode = TraverseMode.CAR;
    }
    RoutingRequest options = new RoutingRequest(mode);
    options.dominanceFunction = new DominanceFunction.EarliestArrival();
    options.setDummyRoutingContext(graph);
    AStar search = new AStar();
    search.setSkipEdgeStrategy(new ListedEdgesOnly(edges));
    Set<Edge> usedEdges = new HashSet<Edge>();
    for (Vertex vertex : startingVertices) {
        options.setRoutingContext(graph, vertex, null);
        options.rctx.remainingWeightHeuristic = new TrivialRemainingWeightHeuristic();
        ShortestPathTree spt = search.getShortestPathTree(options);
        for (Vertex endVertex : startingVertices) {
            GraphPath path = spt.getPath(endVertex, false);
            if (path != null) {
                for (Edge edge : path.edges) {
                    usedEdges.add(edge);
                }
            }
        }
    }
    for (Edge edge : edges) {
        if (!usedEdges.contains(edge)) {
            graph.removeEdge(edge);
        }
    }
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) IntersectionVertex(org.opentripplanner.routing.vertextype.IntersectionVertex) AStar(org.opentripplanner.routing.algorithm.astar.AStar) GraphPath(org.opentripplanner.routing.spt.GraphPath) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic) TraverseMode(org.opentripplanner.routing.core.TraverseMode) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction) AreaEdge(org.opentripplanner.routing.edgetype.AreaEdge) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) Edge(org.opentripplanner.routing.graph.Edge) HashSet(java.util.HashSet)

Example 3 with TrivialRemainingWeightHeuristic

use of org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic in project OpenTripPlanner by opentripplanner.

the class GraphPathFinder method getPaths.

/**
 * This no longer does "trip banning" to find multiple itineraries.
 * It just searches once trying to find a non-transit path.
 */
public List<GraphPath> getPaths(RoutingRequest options) {
    if (options == null) {
        LOG.error("PathService was passed a null routing request.");
        return null;
    }
    if (options.streetSubRequestModes.isTransit()) {
        throw new UnsupportedOperationException("Transit search not supported");
    }
    // Reuse one instance of AStar for all N requests, which are carried out sequentially
    AStar aStar = new AStar();
    if (options.rctx == null) {
        options.setRoutingContext(router.graph);
    // The special long-distance heuristic should be sufficient to constrain the search to the right area.
    }
    // If this Router has a GraphVisualizer attached to it, set it as a callback for the AStar search
    if (router.graphVisualizer != null) {
        aStar.setTraverseVisitor(router.graphVisualizer.traverseVisitor);
    // options.disableRemainingWeightHeuristic = true; // DEBUG
    }
    // FORCING the dominance function to weight only
    options.dominanceFunction = new DominanceFunction.MinimumWeight();
    LOG.debug("rreq={}", options);
    // Choose an appropriate heuristic for goal direction.
    RemainingWeightHeuristic heuristic;
    if (options.disableRemainingWeightHeuristic || options.oneToMany) {
        heuristic = new TrivialRemainingWeightHeuristic();
    } else {
        heuristic = new EuclideanRemainingWeightHeuristic();
    }
    options.rctx.remainingWeightHeuristic = heuristic;
    /* maxWalk has a different meaning than it used to. It's the radius around the origin or destination within
         * which you can walk on the streets. An unlimited value would cause the bidi heuristic to do unbounded street
         * searches and consider the whole graph walkable.
         *
         * After the limited areas of the street network around the origin and destination are explored, the
         * options.maxWalkDistance will be set to unlimited for similar reasons to maxTransfers above. That happens
         * in method org.opentripplanner.routing.algorithm.astar.strategies.InterleavedBidirectionalHeuristic.initialize
         */
    if (options.maxWalkDistance == Double.MAX_VALUE)
        options.maxWalkDistance = DEFAULT_MAX_WALK;
    if (options.maxWalkDistance > CLAMP_MAX_WALK)
        options.maxWalkDistance = CLAMP_MAX_WALK;
    long searchBeginTime = System.currentTimeMillis();
    LOG.debug("BEGIN SEARCH");
    double timeout = searchBeginTime + router.streetRoutingTimeoutSeconds() * 1000;
    // Convert from absolute to relative time
    timeout -= System.currentTimeMillis();
    // Convert milliseconds to seconds
    timeout /= 1000;
    if (timeout <= 0) {
        // Catch the case where advancing to the next (lower) timeout value means the search is timed out
        // before it even begins. Passing a negative relative timeout in the SPT call would mean "no timeout".
        options.rctx.aborted = true;
        return null;
    }
    // Don't dig through the SPT object, just ask the A star algorithm for the states that reached the target.
    aStar.getShortestPathTree(options, timeout);
    List<GraphPath> paths = aStar.getPathsToTarget().stream().filter(path -> {
        double duration = options.useRequestedDateTimeInMaxHours ? options.arriveBy ? options.dateTime - path.getStartTime() : path.getEndTime() - options.dateTime : path.getDuration();
        return duration < options.maxHours * 60 * 60;
    }).collect(Collectors.toList());
    LOG.debug("we have {} paths", paths.size());
    LOG.debug("END SEARCH ({} msec)", System.currentTimeMillis() - searchBeginTime);
    Collections.sort(paths, options.getPathComparator(options.arriveBy));
    return paths;
}
Also used : Logger(org.slf4j.Logger) Iterator(java.util.Iterator) PathNotFoundException(org.opentripplanner.routing.error.PathNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) GraphPath(org.opentripplanner.routing.spt.GraphPath) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic) Collectors(java.util.stream.Collectors) RoutingValidationException(org.opentripplanner.routing.error.RoutingValidationException) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction) List(java.util.List) EuclideanRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.EuclideanRemainingWeightHeuristic) Router(org.opentripplanner.standalone.server.Router) RemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.RemainingWeightHeuristic) RoutingErrorCode(org.opentripplanner.routing.api.response.RoutingErrorCode) AStar(org.opentripplanner.routing.algorithm.astar.AStar) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest) Collections(java.util.Collections) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic) EuclideanRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.EuclideanRemainingWeightHeuristic) RemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.RemainingWeightHeuristic) AStar(org.opentripplanner.routing.algorithm.astar.AStar) GraphPath(org.opentripplanner.routing.spt.GraphPath) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic) EuclideanRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.EuclideanRemainingWeightHeuristic) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction)

Example 4 with TrivialRemainingWeightHeuristic

use of org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic in project OpenTripPlanner by opentripplanner.

the class StreetGraphFinder method findClosestUsingStreets.

private void findClosestUsingStreets(double lat, double lon, double radius, TraverseVisitor visitor, SearchTerminationStrategy terminationStrategy) {
    // Make a normal OTP routing request so we can traverse edges and use GenericAStar
    // TODO make a function that builds normal routing requests from profile requests
    RoutingRequest rr = new RoutingRequest(TraverseMode.WALK);
    rr.from = new GenericLocation(null, null, lat, lon);
    rr.oneToMany = true;
    rr.setRoutingContext(graph);
    rr.walkSpeed = 1;
    rr.dominanceFunction = new DominanceFunction.LeastWalk();
    rr.rctx.remainingWeightHeuristic = new TrivialRemainingWeightHeuristic();
    // RR dateTime defaults to currentTime.
    // If elapsed time is not capped, searches are very slow.
    rr.worstTime = (rr.dateTime + (int) radius);
    AStar astar = new AStar();
    rr.setNumItineraries(1);
    astar.setTraverseVisitor(visitor);
    // timeout in seconds
    astar.getShortestPathTree(rr, 1, terminationStrategy);
    // Destroy the routing context, to clean up the temporary edges & vertices
    rr.rctx.destroy();
}
Also used : AStar(org.opentripplanner.routing.algorithm.astar.AStar) GenericLocation(org.opentripplanner.model.GenericLocation) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction)

Aggregations

TrivialRemainingWeightHeuristic (org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic)4 RoutingRequest (org.opentripplanner.routing.api.request.RoutingRequest)4 DominanceFunction (org.opentripplanner.routing.spt.DominanceFunction)4 AStar (org.opentripplanner.routing.algorithm.astar.AStar)3 Vertex (org.opentripplanner.routing.graph.Vertex)2 GraphPath (org.opentripplanner.routing.spt.GraphPath)2 ShortestPathTree (org.opentripplanner.routing.spt.ShortestPathTree)2 Collections (java.util.Collections)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Collectors (java.util.stream.Collectors)1 FlexStopLocation (org.opentripplanner.model.FlexStopLocation)1 GenericLocation (org.opentripplanner.model.GenericLocation)1 EuclideanRemainingWeightHeuristic (org.opentripplanner.routing.algorithm.astar.strategies.EuclideanRemainingWeightHeuristic)1 RemainingWeightHeuristic (org.opentripplanner.routing.algorithm.astar.strategies.RemainingWeightHeuristic)1 RoutingErrorCode (org.opentripplanner.routing.api.response.RoutingErrorCode)1 State (org.opentripplanner.routing.core.State)1 TraverseMode (org.opentripplanner.routing.core.TraverseMode)1 AreaEdge (org.opentripplanner.routing.edgetype.AreaEdge)1