Search in sources :

Example 1 with Tuple2

use of org.mapdb.Fun.Tuple2 in project OpenTripPlanner by opentripplanner.

the class RoundBasedProfileRouter method route.

public void route() {
    LOG.info("access modes: {}", request.accessModes);
    LOG.info("egress modes: {}", request.egressModes);
    LOG.info("direct modes: {}", request.directModes);
    // TimeWindow could constructed in the caller, which does have access to the graph index.
    this.window = new TimeWindow(request.fromTime, request.toTime, graph.index.servicesRunning(request.date));
    // Establish search timeouts
    long searchBeginTime = System.currentTimeMillis();
    long abortTime = searchBeginTime + TIMEOUT * 1000;
    LOG.info("Finding access/egress paths.");
    // Look for stops that are within a given time threshold of the origin and destination
    // Find the closest stop on each pattern near the origin and destination
    // TODO consider that some stops may be closer by one mode than another
    // and that some stops may be accessible by one mode but not another
    ProfileStateStore store = RETAIN_PATTERNS ? new MultiProfileStateStore() : new SingleProfileStateStore();
    for (ProfileState ps : findInitialStops(false)) {
        store.put(ps);
    }
    LOG.info("Found {} initial stops", store.size());
    // we don't want to generate trips that are artificially forced to go past a transit stop.
    ROUNDS: for (int round = 0; round < MAX_ROUNDS; round++) {
        long roundStart = System.currentTimeMillis();
        LOG.info("Begin round {}; {} stops to explore", round, store.size());
        ProfileStateStore previousStore = store;
        store = RETAIN_PATTERNS ? new MultiProfileStateStore((MultiProfileStateStore) store) : new SingleProfileStateStore((SingleProfileStateStore) store);
        Set<TripPattern> patternsToExplore = Sets.newHashSet();
        // explore all of the patterns at the stops visited on the previous round
        for (TransitStop tstop : previousStore.keys()) {
            Collection<TripPattern> patterns = graph.index.patternsForStop.get(tstop.getStop());
            patternsToExplore.addAll(patterns);
        }
        LOG.info("Exploring {} patterns", patternsToExplore.size());
        // propagate all of the bounds down each pattern
        PATTERNS: for (final TripPattern pattern : patternsToExplore) {
            STOPS: for (int i = 0; i < pattern.stopVertices.length; i++) {
                if (!previousStore.containsKey(pattern.stopVertices[i]))
                    continue STOPS;
                Collection<ProfileState> statesToPropagate;
                // only propagate nondominated states
                statesToPropagate = previousStore.get(pattern.stopVertices[i]);
                // don't propagate states that use the same pattern
                statesToPropagate = Collections2.filter(statesToPropagate, new Predicate<ProfileState>() {

                    @Override
                    public boolean apply(ProfileState input) {
                        // don't reboard same pattern, and don't board patterns that are better boarded elsewhere
                        return !input.containsPattern(pattern) && (input.targetPatterns == null || input.targetPatterns.contains(pattern));
                    }
                });
                if (statesToPropagate.isEmpty())
                    continue STOPS;
                int minWaitTime = Integer.MAX_VALUE;
                int maxWaitTime = Integer.MIN_VALUE;
                // (i.e. the transfer time is different for the initial boarding than transfers)
                for (FrequencyEntry freq : pattern.scheduledTimetable.frequencyEntries) {
                    if (freq.exactTimes) {
                        throw new IllegalStateException("Exact times not yet supported in profile routing.");
                    }
                    int overlap = window.overlap(freq.startTime, freq.endTime, freq.tripTimes.serviceCode);
                    if (overlap > 0) {
                        if (freq.headway > maxWaitTime)
                            maxWaitTime = freq.headway;
                        // if any frequency-based trips are running a wait of 0 is always possible, because it could come
                        // just as you show up at the stop.
                        minWaitTime = 0;
                    }
                }
                DESTSTOPS: for (int j = i + 1; j < pattern.stopVertices.length; j++) {
                    // how long does it take to ride this trip from i to j?
                    int minRideTime = Integer.MAX_VALUE;
                    int maxRideTime = Integer.MIN_VALUE;
                    // how long does it take to get to stop j from stop i?
                    for (TripTimes tripTimes : pattern.scheduledTimetable.tripTimes) {
                        int depart = tripTimes.getDepartureTime(i);
                        int arrive = tripTimes.getArrivalTime(j);
                        if (window.includes(depart) && window.includes(arrive) && window.servicesRunning.get(tripTimes.serviceCode)) {
                            int t = arrive - depart;
                            if (t < minRideTime)
                                minRideTime = t;
                            if (t > maxRideTime)
                                maxRideTime = t;
                        }
                    }
                    /* Do the same thing for any frequency-based trips. */
                    for (FrequencyEntry freq : pattern.scheduledTimetable.frequencyEntries) {
                        TripTimes tt = freq.tripTimes;
                        int overlap = window.overlap(freq.startTime, freq.endTime, tt.serviceCode);
                        if (overlap == 0)
                            continue;
                        int depart = tt.getDepartureTime(i);
                        int arrive = tt.getArrivalTime(j);
                        int t = arrive - depart;
                        if (t < minRideTime)
                            minRideTime = t;
                        if (t > maxRideTime)
                            maxRideTime = t;
                    }
                    if (minWaitTime == Integer.MAX_VALUE || maxWaitTime == Integer.MIN_VALUE || minRideTime == Integer.MAX_VALUE || maxRideTime == Integer.MIN_VALUE)
                        // no trips in window that arrive at stop
                        continue DESTSTOPS;
                    if (minRideTime < 0 || maxRideTime < 0) {
                        LOG.error("Pattern {} travels backwards in time between stop {} and {}", pattern, pattern.stopVertices[i].getStop(), pattern.stopVertices[j].getStop());
                        continue DESTSTOPS;
                    }
                    // we've already checked to ensure we're not reboarding the same pattern
                    for (ProfileState ps : statesToPropagate) {
                        ProfileState ps2 = ps.propagate(minWaitTime + minRideTime, maxWaitTime + maxRideTime);
                        if (ps2.upperBound > CUTOFF_SECONDS)
                            continue;
                        ps2.stop = pattern.stopVertices[j];
                        ps2.accessType = Type.TRANSIT;
                        if (RETAIN_PATTERNS)
                            ps2.patterns = new TripPattern[] { pattern };
                        store.put(ps2);
                    }
                }
            }
        }
        // merge states that came from the same stop.
        if (RETAIN_PATTERNS) {
            LOG.info("Round completed, merging similar states");
            ((MultiProfileStateStore) store).mergeStates();
        }
        for (ProfileState ps : store.getAll()) {
            retainedStates.put(ps.stop, ps);
        }
        if (round == MAX_ROUNDS - 1) {
            LOG.info("Finished round {} in {} seconds", round, (System.currentTimeMillis() - roundStart) / 1000);
            break ROUNDS;
        }
        // propagate states to nearby stops (transfers)
        LOG.info("Finding transfers . . .");
        // avoid concurrent modification
        Set<TransitStop> touchedStopKeys = new HashSet<TransitStop>(store.keys());
        for (TransitStop tstop : touchedStopKeys) {
            List<Tuple2<TransitStop, Integer>> accessTimes = Lists.newArrayList();
            // find transfers for the stop
            for (Edge e : tstop.getOutgoing()) {
                if (e instanceof SimpleTransfer) {
                    SimpleTransfer t = (SimpleTransfer) e;
                    int time = (int) (t.getDistance() / request.walkSpeed);
                    accessTimes.add(new Tuple2((TransitStop) e.getToVertex(), time));
                }
            }
            // only transfer from nondominated states. only transfer to each pattern once
            Collection<ProfileState> statesAtStop = store.get(tstop);
            TObjectIntHashMap<TripPattern> minBoardTime = new TObjectIntHashMap<TripPattern>(1000, .75f, Integer.MAX_VALUE);
            Map<TripPattern, ProfileState> optimalBoardState = Maps.newHashMap();
            List<ProfileState> xferStates = Lists.newArrayList();
            // make a hashset of the patterns that stop here, because we don't want to transfer to them at another stop
            HashSet<TripPattern> patternsAtSource = new HashSet<TripPattern>(graph.index.patternsForStop.get(tstop.getStop()));
            for (ProfileState ps : statesAtStop) {
                for (Tuple2<TransitStop, Integer> atime : accessTimes) {
                    ProfileState ps2 = ps.propagate(atime.b);
                    ps2.accessType = Type.TRANSFER;
                    ps2.stop = atime.a;
                    for (TripPattern patt : graph.index.patternsForStop.get(atime.a.getStop())) {
                        // don't transfer to patterns that we can board at this stop.
                        if (patternsAtSource.contains(patt))
                            continue;
                        if (atime.b < minBoardTime.get(patt)) {
                            minBoardTime.put(patt, atime.b);
                            optimalBoardState.put(patt, ps2);
                        }
                    }
                    xferStates.add(ps2);
                }
            }
            for (Entry<TripPattern, ProfileState> e : optimalBoardState.entrySet()) {
                ProfileState ps = e.getValue();
                if (ps.targetPatterns == null)
                    ps.targetPatterns = Sets.newHashSet();
                ps.targetPatterns.add(e.getKey());
            }
            for (ProfileState ps : xferStates) {
                if (ps.targetPatterns != null && !ps.targetPatterns.isEmpty()) {
                    store.put(ps);
                }
            }
        }
        LOG.info("Finished round {} in {} seconds", round, (System.currentTimeMillis() - roundStart) / 1000);
    }
    LOG.info("Finished profile routing in {} seconds", (System.currentTimeMillis() - searchBeginTime) / 1000);
    makeSurfaces();
    LOG.info("Finished analyst request in {} seconds total", (System.currentTimeMillis() - searchBeginTime) / 1000);
}
Also used : HashSet(java.util.HashSet) QualifiedModeSet(org.opentripplanner.api.parameter.QualifiedModeSet) Set(java.util.Set) RangeSet(org.opentripplanner.analyst.TimeSurface.RangeSet) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) Entry(java.util.Map.Entry) TObjectIntHashMap(gnu.trove.map.hash.TObjectIntHashMap) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) ArrayList(java.util.ArrayList) List(java.util.List) SimpleTransfer(org.opentripplanner.routing.edgetype.SimpleTransfer) HashSet(java.util.HashSet) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) Tuple2(org.mapdb.Fun.Tuple2) Collection(java.util.Collection) Edge(org.opentripplanner.routing.graph.Edge) TObjectIntMap(gnu.trove.map.TObjectIntMap) Map(java.util.Map) TObjectIntHashMap(gnu.trove.map.hash.TObjectIntHashMap)

Aggregations

TObjectIntMap (gnu.trove.map.TObjectIntMap)1 TObjectIntHashMap (gnu.trove.map.hash.TObjectIntHashMap)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Entry (java.util.Map.Entry)1 Set (java.util.Set)1 Tuple2 (org.mapdb.Fun.Tuple2)1 RangeSet (org.opentripplanner.analyst.TimeSurface.RangeSet)1 QualifiedModeSet (org.opentripplanner.api.parameter.QualifiedModeSet)1 SimpleTransfer (org.opentripplanner.routing.edgetype.SimpleTransfer)1 TripPattern (org.opentripplanner.routing.edgetype.TripPattern)1 Edge (org.opentripplanner.routing.graph.Edge)1 FrequencyEntry (org.opentripplanner.routing.trippattern.FrequencyEntry)1 TripTimes (org.opentripplanner.routing.trippattern.TripTimes)1 TransitStop (org.opentripplanner.routing.vertextype.TransitStop)1