Search in sources :

Example 1 with TrivialRemainingWeightHeuristic

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

the class GraphPathFinder method getPaths.

/**
 * Repeatedly build shortest path trees, retaining the best path to the destination after each try.
 * For search N, all trips used in itineraries retained from trips 0..(N-1) are "banned" to create variety.
 * The goal direction heuristic is reused between tries, which means the later tries have more information to
 * work with (in the case of the more sophisticated bidirectional heuristic, which improves over time).
 */
public List<GraphPath> getPaths(RoutingRequest options) {
    RoutingRequest originalReq = options.clone();
    if (options == null) {
        LOG.error("PathService was passed a null routing request.");
        return null;
    }
    // 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
    }
    // Without transit, we'd just just return multiple copies of the same on-street itinerary.
    if (!options.modes.isTransit()) {
        options.numItineraries = 1;
    }
    // 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;
    RemainingWeightHeuristic reversedSearchHeuristic;
    if (options.disableRemainingWeightHeuristic) {
        heuristic = new TrivialRemainingWeightHeuristic();
        reversedSearchHeuristic = new TrivialRemainingWeightHeuristic();
    } else if (options.modes.isTransit()) {
        // Only use the BiDi heuristic for transit. It is not very useful for on-street modes.
        // heuristic = new InterleavedBidirectionalHeuristic(options.rctx.graph);
        // Use a simplistic heuristic until BiDi heuristic is improved, see #2153
        heuristic = new InterleavedBidirectionalHeuristic();
        reversedSearchHeuristic = new InterleavedBidirectionalHeuristic();
    } else {
        heuristic = new EuclideanRemainingWeightHeuristic();
        reversedSearchHeuristic = new EuclideanRemainingWeightHeuristic();
    }
    options.rctx.remainingWeightHeuristic = heuristic;
    /* In RoutingRequest, maxTransfers defaults to 2. Over long distances, we may see
         * itineraries with far more transfers. We do not expect transfer limiting to improve
         * search times on the LongDistancePathService, so we set it to the maximum we ever expect
         * to see. Because people may use either the traditional path services or the 
         * LongDistancePathService, we do not change the global default but override it here. */
    options.maxTransfers = 4;
    // Now we always use what used to be called longDistance mode. Non-longDistance mode is no longer supported.
    options.longDistance = true;
    /* In long distance mode, 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.
         * If no value is provided, max walk defaults to the largest double-precision float.
         * This would cause long distance mode to do unbounded street searches and consider the whole graph walkable. */
    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");
    List<GraphPath> paths = Lists.newArrayList();
    while (paths.size() < options.numItineraries) {
        // TODO pull all this timeout logic into a function near org.opentripplanner.util.DateUtils.absoluteTimeout()
        int timeoutIndex = paths.size();
        if (timeoutIndex >= router.timeouts.length) {
            timeoutIndex = router.timeouts.length - 1;
        }
        double timeout = searchBeginTime + (router.timeouts[timeoutIndex] * 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;
            break;
        }
        // Don't dig through the SPT object, just ask the A star algorithm for the states that reached the target.
        aStar.getShortestPathTree(options, timeout);
        if (options.rctx.aborted) {
            // Search timed out or was gracefully aborted for some other reason.
            break;
        }
        List<GraphPath> newPaths = aStar.getPathsToTarget();
        if (newPaths.isEmpty()) {
            break;
        }
        // Do a full reversed search to compact the legs
        if (options.compactLegsByReversedSearch) {
            newPaths = compactLegsByReversedSearch(aStar, originalReq, options, newPaths, timeout, reversedSearchHeuristic);
        }
        // Find all trips used in this path and ban them for the remaining searches
        for (GraphPath path : newPaths) {
            // path.dump();
            List<AgencyAndId> tripIds = path.getTrips();
            for (AgencyAndId tripId : tripIds) {
                options.banTrip(tripId);
            }
            if (tripIds.isEmpty()) {
                // This path does not use transit (is entirely on-street). Do not repeatedly find the same one.
                options.onlyTransitTrips = true;
            }
        }
        paths.addAll(newPaths.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, new PathComparator(options.arriveBy));
    return paths;
}
Also used : RemainingWeightHeuristic(org.opentripplanner.routing.algorithm.strategies.RemainingWeightHeuristic) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.strategies.TrivialRemainingWeightHeuristic) EuclideanRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.strategies.EuclideanRemainingWeightHeuristic) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) AStar(org.opentripplanner.routing.algorithm.AStar) GraphPath(org.opentripplanner.routing.spt.GraphPath) EuclideanRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.strategies.EuclideanRemainingWeightHeuristic) InterleavedBidirectionalHeuristic(org.opentripplanner.routing.algorithm.strategies.InterleavedBidirectionalHeuristic) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.strategies.TrivialRemainingWeightHeuristic) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction)

Example 2 with TrivialRemainingWeightHeuristic

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

the class AStar method startSearch.

/**
 * set up the search, optionally not adding the initial state to the queue (for multi-state Dijkstra)
 */
private void startSearch(RoutingRequest options, SearchTerminationStrategy terminationStrategy, long abortTime, boolean addToQueue) {
    runState = new RunState(options, terminationStrategy);
    runState.rctx = options.getRoutingContext();
    runState.spt = options.getNewShortestPathTree();
    // We want to reuse the heuristic instance in a series of requests for the same target to avoid repeated work.
    // "Batch" means one-to-many mode, where there is no goal to reach so we use a trivial heuristic.
    runState.heuristic = options.batch ? new TrivialRemainingWeightHeuristic() : runState.rctx.remainingWeightHeuristic;
    // Since initial states can be multiple, heuristic cannot depend on the initial state.
    // Initializing the bidirectional heuristic is a pretty complicated operation that involves searching through
    // the streets around the origin and destination.
    runState.heuristic.initialize(runState.options, abortTime);
    if (abortTime < Long.MAX_VALUE && System.currentTimeMillis() > abortTime) {
        LOG.warn("Timeout during initialization of goal direction heuristic.");
        options.rctx.debugOutput.timedOut = true;
        // Search timed out
        runState = null;
        return;
    }
    // Priority Queue.
    // The queue is self-resizing, so we initialize it to have size = O(sqrt(|V|)) << |V|.
    // For reference, a random, undirected search on a uniform 2d grid will examine roughly sqrt(|V|) vertices
    // before reaching its target.
    int initialSize = runState.rctx.graph.getVertices().size();
    initialSize = (int) Math.ceil(2 * (Math.sqrt((double) initialSize + 1)));
    runState.pq = new BinHeap<>(initialSize);
    runState.nVisited = 0;
    runState.targetAcceptedStates = Lists.newArrayList();
    if (addToQueue) {
        State initialState = new State(options);
        runState.spt.add(initialState);
        runState.pq.insert(initialState, 0);
    }
}
Also used : State(org.opentripplanner.routing.core.State) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.strategies.TrivialRemainingWeightHeuristic)

Aggregations

TrivialRemainingWeightHeuristic (org.opentripplanner.routing.algorithm.strategies.TrivialRemainingWeightHeuristic)2 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)1 AStar (org.opentripplanner.routing.algorithm.AStar)1 EuclideanRemainingWeightHeuristic (org.opentripplanner.routing.algorithm.strategies.EuclideanRemainingWeightHeuristic)1 InterleavedBidirectionalHeuristic (org.opentripplanner.routing.algorithm.strategies.InterleavedBidirectionalHeuristic)1 RemainingWeightHeuristic (org.opentripplanner.routing.algorithm.strategies.RemainingWeightHeuristic)1 RoutingRequest (org.opentripplanner.routing.core.RoutingRequest)1 State (org.opentripplanner.routing.core.State)1 DominanceFunction (org.opentripplanner.routing.spt.DominanceFunction)1 GraphPath (org.opentripplanner.routing.spt.GraphPath)1