Search in sources :

Example 41 with Stop

use of org.onebusaway.gtfs.model.Stop in project OpenTripPlanner by opentripplanner.

the class AnalystProfileRouterPrototype method route.

public TimeSurface.RangeSet route() {
    // NOT USED here, however FIXME this is not threadsafe, needs lock graph.index.clusterStopsAsNeeded();
    LOG.info("access modes: {}", request.accessModes);
    LOG.info("egress modes: {}", request.egressModes);
    LOG.info("direct modes: {}", request.directModes);
    // Establish search timeouts
    searchBeginTime = System.currentTimeMillis();
    abortTime = searchBeginTime + TIMEOUT * 1000;
    // 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));
    fromStops = findClosestStops(TraverseMode.WALK);
    LOG.info("From patterns/stops: {}", fromStops);
    /* Initialize time range tracker to begin the search. */
    TimeRange.Tracker times = new TimeRange.Tracker();
    for (Stop stop : fromStops.keySet()) {
        times.set(stop, fromStops.get(stop));
    }
    Set<Stop> stopsUpdated = fromStops.keySet();
    for (int round = 0; round < MAX_RIDES; round++) {
        // TODO maybe even loop until no updates happen? That should happen automatically if MAX_RIDES is high enough.
        /* Get all patterns passing through stops updated in the last round, then reinitialize the updated stops set. */
        Set<TripPattern> patternsUpdated = uniquePatternsVisiting(stopsUpdated);
        LOG.info("ROUND {} : {} stops and {} patterns to explore.", round, stopsUpdated.size(), patternsUpdated.size());
        stopsUpdated = Sets.newHashSet();
        /* RAPTOR style: iterate over each pattern once. */
        for (TripPattern pattern : patternsUpdated) {
            // checkTimeout();
            TimeRange rangeBeingPropagated = null;
            List<Stop> stops = pattern.getStops();
            FrequencyEntry freq = pattern.getSingleFrequencyEntry();
            if (freq == null)
                continue;
            TripTimes tt = freq.tripTimes;
            int headway = freq.headway;
            for (int sidx = 0; sidx < stops.size(); sidx++) {
                Stop stop = stops.get(sidx);
                TimeRange existingRange = times.get(stop);
                TimeRange reBoardRange = (existingRange != null) ? existingRange.wait(headway) : null;
                if (rangeBeingPropagated == null) {
                    // We do not yet have a range worth propagating
                    if (reBoardRange != null) {
                        // this is a fresh protective copy
                        rangeBeingPropagated = reBoardRange;
                    }
                } else {
                    // We already have a range that is being propagated along the pattern.
                    // We are certain sidx >= 1 here because we have already boarded in a previous iteration.
                    TimeRange arrivalRange = rangeBeingPropagated.shift(tt.getRunningTime(sidx - 1));
                    if (times.add(stop, arrivalRange)) {
                        // The propagated time improved the best known time in some way.
                        stopsUpdated.add(stop);
                    }
                    // TODO handle case where arrival and departure are different
                    rangeBeingPropagated = arrivalRange.shift(tt.getDwellTime(sidx));
                    if (reBoardRange != null) {
                        rangeBeingPropagated.mergeIn(reBoardRange);
                    }
                }
            }
        }
        /* Transfer from updated stops to adjacent stops before beginning the next round.
               Iterate over a protective copy because we add more stops to the updated list during iteration. */
        if (!graph.hasDirectTransfers) {
            throw new RuntimeException("Requires the SimpleTransfers generated in long distance mode.");
        }
        for (Stop stop : Lists.newArrayList(stopsUpdated)) {
            Collection<Edge> outgoingEdges = graph.index.stopVertexForStop.get(stop).getOutgoing();
            for (SimpleTransfer transfer : Iterables.filter(outgoingEdges, SimpleTransfer.class)) {
                Stop targetStop = ((TransitStop) transfer.getToVertex()).getStop();
                double walkTime = transfer.getDistance() / request.walkSpeed;
                TimeRange rangeAfterTransfer = times.get(stop).shift((int) walkTime);
                if (times.add(targetStop, rangeAfterTransfer)) {
                    stopsUpdated.add(targetStop);
                }
            }
        }
    }
    LOG.info("Done with transit.");
    LOG.info("Propagating from transit stops to the street network...");
    // Grab a cached map of distances to street intersections from each transit stop
    StopTreeCache stopTreeCache = graph.index.getStopTreeCache();
    // Iterate over all stops that were reached in the transit part of the search
    for (Stop stop : times) {
        TransitStop tstop = graph.index.stopVertexForStop.get(stop);
        // Iterate over street intersections in the vicinity of this particular transit stop.
        // Shift the time range at this transit stop, merging it into that for all reachable street intersections.
        TimeRange rangeAtTransitStop = times.get(stop);
        // FIXME stopTreeCache.getDistancesForStop(tstop);
        TObjectIntMap<Vertex> distanceToVertex = null;
        for (TObjectIntIterator<Vertex> iter = distanceToVertex.iterator(); iter.hasNext(); ) {
            iter.advance();
            Vertex vertex = iter.key();
            // distance in meters over walkspeed in meters per second --> seconds
            int egressWalkTimeSeconds = (int) (iter.value() / request.walkSpeed);
            if (egressWalkTimeSeconds > request.maxWalkTime * 60) {
                continue;
            }
            TimeRange propagatedRange = rangeAtTransitStop.shift(egressWalkTimeSeconds);
            TimeRange existingTimeRange = propagatedTimes.get(vertex);
            if (existingTimeRange == null) {
                propagatedTimes.put(vertex, propagatedRange);
            } else {
                existingTimeRange.mergeIn(propagatedRange);
            }
        }
    }
    LOG.info("Done with propagation.");
    TimeSurface.RangeSet result = TimeSurface.makeSurfaces(this);
    LOG.info("Done making time surfaces.");
    return result;
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) Stop(org.onebusaway.gtfs.model.Stop) TimeSurface(org.opentripplanner.analyst.TimeSurface) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) SimpleTransfer(org.opentripplanner.routing.edgetype.SimpleTransfer) Edge(org.opentripplanner.routing.graph.Edge)

Example 42 with Stop

use of org.onebusaway.gtfs.model.Stop in project OpenTripPlanner by opentripplanner.

the class AlertPatch method remove.

public void remove(Graph graph) {
    Agency agency = null;
    if (feedId != null) {
        Map<String, Agency> agencies = graph.index.agenciesForFeedId.get(feedId);
        agency = this.agency != null ? agencies.get(this.agency) : null;
    }
    Route route = this.route != null ? graph.index.routeForId.get(this.route) : null;
    Stop stop = this.stop != null ? graph.index.stopForId.get(this.stop) : null;
    Trip trip = this.trip != null ? graph.index.tripForId.get(this.trip) : null;
    if (route != null || trip != null || agency != null) {
        Collection<TripPattern> tripPatterns = null;
        if (trip != null) {
            tripPatterns = new LinkedList<TripPattern>();
            TripPattern tripPattern = graph.index.patternForTrip.get(trip);
            if (tripPattern != null) {
                tripPatterns.add(tripPattern);
            }
        } else if (route != null) {
            tripPatterns = graph.index.patternsForRoute.get(route);
        } else {
            // Find patterns for the feed.
            tripPatterns = graph.index.patternsForFeedId.get(feedId);
        }
        if (tripPatterns != null) {
            for (TripPattern tripPattern : tripPatterns) {
                if (direction != null && !direction.equals(tripPattern.getDirection())) {
                    continue;
                }
                if (directionId != -1 && directionId != tripPattern.directionId) {
                    continue;
                }
                for (int i = 0; i < tripPattern.stopPattern.stops.length; i++) {
                    if (stop == null || stop.equals(tripPattern.stopPattern.stops[i])) {
                        graph.removeAlertPatch(tripPattern.boardEdges[i], this);
                        graph.removeAlertPatch(tripPattern.alightEdges[i], this);
                    }
                }
            }
        }
    } else if (stop != null) {
        TransitStop transitStop = graph.index.stopVertexForStop.get(stop);
        for (Edge edge : transitStop.getOutgoing()) {
            if (edge instanceof PreBoardEdge) {
                graph.removeAlertPatch(edge, this);
                break;
            }
        }
        for (Edge edge : transitStop.getIncoming()) {
            if (edge instanceof PreAlightEdge) {
                graph.removeAlertPatch(edge, this);
                break;
            }
        }
    }
}
Also used : Trip(org.onebusaway.gtfs.model.Trip) PreBoardEdge(org.opentripplanner.routing.edgetype.PreBoardEdge) Agency(org.onebusaway.gtfs.model.Agency) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) Stop(org.onebusaway.gtfs.model.Stop) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) PreAlightEdge(org.opentripplanner.routing.edgetype.PreAlightEdge) PreAlightEdge(org.opentripplanner.routing.edgetype.PreAlightEdge) PreBoardEdge(org.opentripplanner.routing.edgetype.PreBoardEdge) Edge(org.opentripplanner.routing.graph.Edge) Route(org.onebusaway.gtfs.model.Route)

Example 43 with Stop

use of org.onebusaway.gtfs.model.Stop in project OpenTripPlanner by opentripplanner.

the class TransferTable method getTransferTime.

/**
 * Get the transfer time that should be used when transferring from a trip to another trip.
 * Note that this function does not check whether another specific transfer exists with the
 * same specificity, what is forbidden by the specifications.
 * @param fromStop is the arriving stop
 * @param toStop is the departing stop
 * @param fromTrip is the arriving trip
 * @param toTrip is the departing trip
 * @param forwardInTime is true when moving forward in time; false when moving
 *   backwards in time (usually this will be the variable "boarding")
 * @return the transfer time in seconds. May contain special (negative) values which meaning
 *   can be found in the StopTransfer.*_TRANSFER constants. If no transfer is found,
 *   StopTransfer.UNKNOWN_TRANSFER is returned.
 */
public int getTransferTime(Stop fromStop, Stop toStop, Trip fromTrip, Trip toTrip, boolean forwardInTime) {
    checkNotNull(fromStop);
    checkNotNull(toStop);
    // Reverse from and to if we are moving backwards in time
    if (!forwardInTime) {
        Stop tempStop = fromStop;
        fromStop = toStop;
        toStop = tempStop;
        Trip tempTrip = fromTrip;
        fromTrip = toTrip;
        toTrip = tempTrip;
    }
    // Get transfer time between the two stops
    int transferTime = getTransferTime(fromStop.getId(), toStop.getId(), fromTrip, toTrip);
    // Check parents of stops if no transfer was found
    if (transferTime == StopTransfer.UNKNOWN_TRANSFER) {
        // Find parent ids
        AgencyAndId fromStopParentId = null;
        AgencyAndId toStopParentId = null;
        if (fromStop.getParentStation() != null && !fromStop.getParentStation().isEmpty()) {
            // From stop has a parent
            fromStopParentId = new AgencyAndId(fromStop.getId().getAgencyId(), fromStop.getParentStation());
        }
        if (toStop.getParentStation() != null && !toStop.getParentStation().isEmpty()) {
            // To stop has a parent
            toStopParentId = new AgencyAndId(toStop.getId().getAgencyId(), toStop.getParentStation());
        }
        // Check parent of from stop if no transfer was found
        if (fromStopParentId != null) {
            transferTime = getTransferTime(fromStopParentId, toStop.getId(), fromTrip, toTrip);
        }
        // Check parent of to stop if still no transfer was found
        if (transferTime == StopTransfer.UNKNOWN_TRANSFER && toStopParentId != null) {
            transferTime = getTransferTime(fromStop.getId(), toStopParentId, fromTrip, toTrip);
        }
        // Check parents of both stops if still no transfer was found
        if (transferTime == StopTransfer.UNKNOWN_TRANSFER && fromStopParentId != null && toStopParentId != null) {
            transferTime = getTransferTime(fromStopParentId, toStopParentId, fromTrip, toTrip);
        }
    }
    return transferTime;
}
Also used : Trip(org.onebusaway.gtfs.model.Trip) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) Stop(org.onebusaway.gtfs.model.Stop)

Example 44 with Stop

use of org.onebusaway.gtfs.model.Stop in project OpenTripPlanner by opentripplanner.

the class RepeatedRaptorTestResource method profileRoute.

@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response profileRoute(@QueryParam("from") LatLon from, @QueryParam("fromStop") String fromStopString, @QueryParam("banAgency") String banAgency, @QueryParam("banRoute") String banRouteString) {
    if (from != null) {
        oneOrigin(from.lat, from.lon, banAgency);
    } else {
        Collection<Stop> originStops = new ArrayList<>();
        if (fromStopString != null) {
            String[] fields = fromStopString.split(":");
            originStops.add(graph.index.stopForId.get(new AgencyAndId(fields[0], fields[1])));
        } else {
            originStops = graph.index.stopForId.values();
        }
        LOG.info("from stops {}", originStops);
        for (Stop stop : originStops) {
            LOG.info("{}/{}: {}", 0, originStops.size(), stop);
            // Shift slightly so we don't always search right on top of a transit stop.
            oneOrigin(stop.getLat() + 0.001, stop.getLon() + 0.001, banAgency);
        }
    }
    return Response.ok().entity("OK\n").build();
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) Stop(org.onebusaway.gtfs.model.Stop) ArrayList(java.util.ArrayList) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 45 with Stop

use of org.onebusaway.gtfs.model.Stop in project OpenTripPlanner by opentripplanner.

the class FakeGraph method addPerpendicularRoutes.

public static void addPerpendicularRoutes(Graph graph) throws Exception {
    GTFSFeed feed = new GTFSFeed();
    Agency agencyA = createDummyAgency("agencyA", "Agency A", "America/New_York");
    feed.agency.put("agencyA", agencyA);
    Agency agencyB = createDummyAgency("agencyB", "Agency B", "America/New_York");
    feed.agency.put("agencyB", agencyB);
    Service s = createDummyService();
    feed.services.put(s.service_id, s);
    int stopIdX = 0;
    int stopIdY = 0;
    for (double lat = 39.9058; lat < 40.0281; lat += 0.005) {
        stopIdX = 0;
        for (double lon = -83.1341; lon < -82.8646; lon += 0.005) {
            com.conveyal.gtfs.model.Stop stop = new com.conveyal.gtfs.model.Stop();
            stop.stop_id = stop.stop_name = String.format("s-%d-%d", stopIdX, stopIdY);
            stop.stop_lat = lat;
            stop.stop_lon = lon;
            feed.stops.put(stop.stop_id, stop);
            stopIdX++;
        }
        stopIdY++;
    }
    for (int i = 0; i < stopIdY; i++) {
        Route route = new Route();
        route.route_short_name = "hr" + i;
        route.route_long_name = i + "th Horizontal Street";
        route.route_type = Route.BUS;
        route.agency = agencyA;
        route.route_id = "horizontalroute" + i;
        feed.routes.put(route.route_id, route);
    }
    for (int i = 0; i < stopIdX; i++) {
        Route route = new Route();
        route.route_short_name = "vr" + i;
        route.route_long_name = i + "th Vertical Street";
        route.route_type = Route.TRAM;
        route.agency = agencyB;
        route.route_id = "verticalroute" + i;
        feed.routes.put(route.route_id, route);
    }
    Map<String, Route> routes = feed.routes;
    com.conveyal.gtfs.model.Stop stop;
    for (Route route : routes.values()) {
        int routeId = Integer.parseInt(route.route_short_name.substring(2));
        int x, y;
        boolean isHorizontal = route.route_short_name.startsWith("hr");
        for (int departure = 7 * 3600; departure < 20 * 3600; departure += FREQUENCY) {
            Trip t = new Trip();
            t.trip_id = "trip:" + route.route_id + ":" + departure;
            t.service = s;
            t.route = route;
            feed.trips.put(t.trip_id, t);
            int departureTime = departure;
            int nrOfStops = (isHorizontal ? stopIdX : stopIdY);
            for (int stopSequenceNr = 0; stopSequenceNr < nrOfStops; stopSequenceNr++) {
                x = (isHorizontal ? stopSequenceNr : routeId);
                y = (isHorizontal ? routeId : stopSequenceNr);
                stop = feed.stops.get(String.format("s-%d-%d", x, y));
                StopTime st1 = new StopTime();
                st1.trip_id = t.trip_id;
                st1.arrival_time = departureTime;
                st1.departure_time = departureTime;
                st1.stop_id = stop.stop_id;
                st1.stop_sequence = stopSequenceNr + 1;
                feed.stop_times.put(new Fun.Tuple2(st1.trip_id, st1.stop_sequence), st1);
                // connect last stop to first so graph is fully reachable
                if (stopSequenceNr == 0) {
                    StopTime stopTime = new StopTime();
                    stopTime.trip_id = t.trip_id;
                    stopTime.arrival_time = departureTime + nrOfStops * 120 + 30 * 60;
                    stopTime.departure_time = departureTime + nrOfStops * 120 + 30 * 60;
                    stopTime.stop_id = stop.stop_id;
                    stopTime.stop_sequence = stopSequenceNr + 1 + nrOfStops;
                    feed.stop_times.put(new Fun.Tuple2(stopTime.trip_id, stopTime.stop_sequence), stopTime);
                }
                departureTime += 120;
            }
        }
    }
    File tempFile = File.createTempFile("gtfs", ".zip");
    feed.toFile(tempFile.getAbsolutePath());
    // phew. load it into the graph.
    GtfsModule gtfs = new GtfsModule(Arrays.asList(new GtfsBundle(tempFile)));
    gtfs.buildGraph(graph, new HashMap<>());
}
Also used : TransitStop(org.opentripplanner.routing.vertextype.TransitStop) Stop(org.onebusaway.gtfs.model.Stop) GtfsBundle(org.opentripplanner.graph_builder.model.GtfsBundle) com.conveyal.gtfs.model(com.conveyal.gtfs.model) GTFSFeed(com.conveyal.gtfs.GTFSFeed) File(java.io.File) Fun(org.mapdb.Fun)

Aggregations

Stop (org.onebusaway.gtfs.model.Stop)160 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)75 TransitStop (org.opentripplanner.routing.vertextype.TransitStop)49 Trip (org.onebusaway.gtfs.model.Trip)40 Test (org.junit.Test)39 ArrayList (java.util.ArrayList)33 StopTime (org.onebusaway.gtfs.model.StopTime)33 Route (org.onebusaway.gtfs.model.Route)28 TripPattern (org.opentripplanner.routing.edgetype.TripPattern)23 Agency (org.onebusaway.gtfs.model.Agency)19 Vertex (org.opentripplanner.routing.graph.Vertex)18 HashMap (java.util.HashMap)14 TripTimes (org.opentripplanner.routing.trippattern.TripTimes)13 GtfsMutableRelationalDao (org.onebusaway.gtfs.services.GtfsMutableRelationalDao)11 LineString (com.vividsolutions.jts.geom.LineString)10 List (java.util.List)10 GET (javax.ws.rs.GET)10 ShapePoint (org.onebusaway.gtfs.model.ShapePoint)10 GraphPath (org.opentripplanner.routing.spt.GraphPath)10 Coordinate (com.vividsolutions.jts.geom.Coordinate)9