Search in sources :

Example 66 with ServiceDate

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

the class CalendarServiceDataFactoryImpl method addDatesFromCalendar.

private void addDatesFromCalendar(ServiceCalendar calendar, TimeZone timeZone, Set<ServiceDate> activeDates) {
    /**
     * We calculate service dates relative to noon so as to avoid any weirdness
     * relative to DST.
     */
    Date startDate = getServiceDateAsNoon(calendar.getStartDate(), timeZone);
    Date endDate = getServiceDateAsNoon(calendar.getEndDate(), timeZone);
    java.util.Calendar c = java.util.Calendar.getInstance(timeZone);
    c.setTime(startDate);
    while (true) {
        Date date = c.getTime();
        if (date.after(endDate))
            break;
        int day = c.get(java.util.Calendar.DAY_OF_WEEK);
        boolean active = false;
        switch(day) {
            case java.util.Calendar.MONDAY:
                active = calendar.getMonday() == 1;
                break;
            case java.util.Calendar.TUESDAY:
                active = calendar.getTuesday() == 1;
                break;
            case java.util.Calendar.WEDNESDAY:
                active = calendar.getWednesday() == 1;
                break;
            case java.util.Calendar.THURSDAY:
                active = calendar.getThursday() == 1;
                break;
            case java.util.Calendar.FRIDAY:
                active = calendar.getFriday() == 1;
                break;
            case java.util.Calendar.SATURDAY:
                active = calendar.getSaturday() == 1;
                break;
            case java.util.Calendar.SUNDAY:
                active = calendar.getSunday() == 1;
                break;
        }
        if (active) {
            addServiceDate(activeDates, new ServiceDate(c), timeZone);
        }
        c.add(java.util.Calendar.DAY_OF_YEAR, 1);
    }
}
Also used : ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate) Calendar(java.util.Calendar) ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate) Date(java.util.Date) ServiceCalendarDate(org.onebusaway.gtfs.model.ServiceCalendarDate)

Example 67 with ServiceDate

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

the class CalendarServiceDataFactoryImpl method addAndRemoveDatesFromCalendarDate.

private void addAndRemoveDatesFromCalendarDate(ServiceCalendarDate calendarDate, TimeZone serviceIdTimeZone, Set<ServiceDate> activeDates) {
    ServiceDate serviceDate = calendarDate.getDate();
    Date targetDate = calendarDate.getDate().getAsDate();
    Calendar c = Calendar.getInstance();
    c.setTime(targetDate);
    switch(calendarDate.getExceptionType()) {
        case ServiceCalendarDate.EXCEPTION_TYPE_ADD:
            addServiceDate(activeDates, serviceDate, serviceIdTimeZone);
            break;
        case ServiceCalendarDate.EXCEPTION_TYPE_REMOVE:
            activeDates.remove(serviceDate);
            break;
        default:
            _log.warn("unknown CalendarDate exception type: " + calendarDate.getExceptionType());
            break;
    }
}
Also used : ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate) ServiceCalendar(org.onebusaway.gtfs.model.ServiceCalendar) Calendar(java.util.Calendar) ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate) Date(java.util.Date) ServiceCalendarDate(org.onebusaway.gtfs.model.ServiceCalendarDate)

Example 68 with ServiceDate

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

the class GraphIndex method stopTimesForStop.

/**
 * Fetch upcoming vehicle departures from a stop.
 * It goes though all patterns passing the stop for the previous, current and next service date.
 * It uses a priority queue to keep track of the next departures. The queue is shared between all dates, as services
 * from the previous service date can visit the stop later than the current service date's services. This happens
 * eg. with sleeper trains.
 *
 * TODO: Add frequency based trips
 * @param stop Stop object to perform the search for
 * @param startTime Start time for the search. Seconds from UNIX epoch
 * @param timeRange Searches forward for timeRange seconds from startTime
 * @param numberOfDepartures Number of departures to fetch per pattern
 * @param omitNonPickups If true, do not include vehicles that will not pick up passengers.
 * @return
 */
public List<StopTimesInPattern> stopTimesForStop(Stop stop, long startTime, int timeRange, int numberOfDepartures, boolean omitNonPickups) {
    if (startTime == 0) {
        startTime = System.currentTimeMillis() / 1000;
    }
    List<StopTimesInPattern> ret = new ArrayList<>();
    TimetableSnapshot snapshot = null;
    if (graph.timetableSnapshotSource != null) {
        snapshot = graph.timetableSnapshotSource.getTimetableSnapshot();
    }
    Date date = new Date(startTime * 1000);
    ServiceDate[] serviceDates = { new ServiceDate(date).previous(), new ServiceDate(date), new ServiceDate(date).next() };
    for (TripPattern pattern : patternsForStop.get(stop)) {
        // Use the Lucene PriorityQueue, which has a fixed size
        PriorityQueue<TripTimeShort> pq = new PriorityQueue<TripTimeShort>(numberOfDepartures) {

            @Override
            protected boolean lessThan(TripTimeShort tripTimeShort, TripTimeShort t1) {
                // Calculate exact timestamp
                return (tripTimeShort.serviceDay + tripTimeShort.realtimeDeparture) > (t1.serviceDay + t1.realtimeDeparture);
            }
        };
        // Loop through all possible days
        for (ServiceDate serviceDate : serviceDates) {
            ServiceDay sd = new ServiceDay(graph, serviceDate, calendarService, pattern.route.getAgency().getId());
            Timetable tt;
            if (snapshot != null) {
                tt = snapshot.resolve(pattern, serviceDate);
            } else {
                tt = pattern.scheduledTimetable;
            }
            if (!tt.temporallyViable(sd, startTime, timeRange, true))
                continue;
            int secondsSinceMidnight = sd.secondsSinceMidnight(startTime);
            int sidx = 0;
            for (Stop currStop : pattern.stopPattern.stops) {
                if (currStop == stop) {
                    if (omitNonPickups && pattern.stopPattern.pickups[sidx] == pattern.stopPattern.PICKDROP_NONE)
                        continue;
                    for (TripTimes t : tt.tripTimes) {
                        if (!sd.serviceRunning(t.serviceCode))
                            continue;
                        if (t.getDepartureTime(sidx) != -1 && t.getDepartureTime(sidx) >= secondsSinceMidnight) {
                            pq.insertWithOverflow(new TripTimeShort(t, sidx, stop, sd));
                        }
                    }
                    // TODO: This needs to be adapted after #1647 is merged
                    for (FrequencyEntry freq : tt.frequencyEntries) {
                        if (!sd.serviceRunning(freq.tripTimes.serviceCode))
                            continue;
                        int departureTime = freq.nextDepartureTime(sidx, secondsSinceMidnight);
                        if (departureTime == -1)
                            continue;
                        int lastDeparture = freq.endTime + freq.tripTimes.getArrivalTime(sidx) - freq.tripTimes.getDepartureTime(0);
                        int i = 0;
                        while (departureTime <= lastDeparture && i < numberOfDepartures) {
                            pq.insertWithOverflow(new TripTimeShort(freq.materialize(sidx, departureTime, true), sidx, stop, sd));
                            departureTime += freq.headway;
                            i++;
                        }
                    }
                }
                sidx++;
            }
        }
        if (pq.size() != 0) {
            StopTimesInPattern stopTimes = new StopTimesInPattern(pattern);
            while (pq.size() != 0) {
                stopTimes.times.add(0, pq.pop());
            }
            ret.add(stopTimes);
        }
    }
    return ret;
}
Also used : Timetable(org.opentripplanner.routing.edgetype.Timetable) ServiceDay(org.opentripplanner.routing.core.ServiceDay) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) Stop(org.onebusaway.gtfs.model.Stop) ArrayList(java.util.ArrayList) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) TimetableSnapshot(org.opentripplanner.routing.edgetype.TimetableSnapshot) PriorityQueue(org.apache.lucene.util.PriorityQueue) Date(java.util.Date) ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate) LocalDate(org.joda.time.LocalDate) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) TripTimeShort(org.opentripplanner.index.model.TripTimeShort) ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) StopTimesInPattern(org.opentripplanner.index.model.StopTimesInPattern)

Example 69 with ServiceDate

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

the class GtfsRealtimeFuzzyTripMatcher method match.

public TripDescriptor match(String feedId, TripDescriptor trip) {
    if (trip.hasTripId()) {
        // trip_id already exists
        return trip;
    }
    if (!trip.hasRouteId() || !trip.hasDirectionId() || !trip.hasStartTime() || !trip.hasStartDate()) {
        // Could not determine trip_id, returning original TripDescriptor
        return trip;
    }
    AgencyAndId routeId = new AgencyAndId(feedId, trip.getRouteId());
    int time = StopTimeFieldMappingFactory.getStringAsSeconds(trip.getStartTime());
    ServiceDate date;
    try {
        date = ServiceDate.parseString(trip.getStartDate());
    } catch (ParseException e) {
        return trip;
    }
    Route route = index.routeForId.get(routeId);
    if (route == null) {
        return trip;
    }
    int direction = trip.getDirectionId();
    Trip matchedTrip = getTrip(route, direction, time, date);
    if (matchedTrip == null) {
        // Check if the trip is carried over from previous day
        date = date.previous();
        time += 24 * 60 * 60;
        matchedTrip = getTrip(route, direction, time, date);
    }
    if (matchedTrip == null) {
        return trip;
    }
    // If everything succeeds, build a new TripDescriptor with the matched trip_id
    return trip.toBuilder().setTripId(matchedTrip.getId().getId()).build();
}
Also used : ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate) Trip(org.onebusaway.gtfs.model.Trip) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) ParseException(java.text.ParseException) Route(org.onebusaway.gtfs.model.Route)

Example 70 with ServiceDate

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

the class TestTransfers method testTimedStopToStopTransfer.

public void testTimedStopToStopTransfer() throws Exception {
    ServiceDate serviceDate = new ServiceDate(2009, 07, 11);
    // Replace the transfer table with an empty table
    TransferTable table = new TransferTable();
    when(graph.getTransferTable()).thenReturn(table);
    // Compute a normal path between two stops
    Vertex origin = graph.getVertex(feedId + ":N");
    Vertex destination = graph.getVertex(feedId + ":H");
    // Set options like time and routing context
    RoutingRequest options = new RoutingRequest();
    options.dateTime = TestUtils.dateInSeconds("America/New_York", 2009, 7, 11, 11, 11, 0);
    options.setRoutingContext(graph, origin, destination);
    // Plan journey
    GraphPath path;
    List<Trip> trips;
    path = planJourney(options);
    trips = extractTrips(path);
    // Validate result
    assertEquals("8.1", trips.get(0).getId().getId());
    assertEquals("4.2", trips.get(1).getId().getId());
    // Add timed transfer to table
    Stop stopK = new Stop();
    stopK.setId(new AgencyAndId(feedId, "K"));
    Stop stopF = new Stop();
    stopF.setId(new AgencyAndId(feedId, "F"));
    table.addTransferTime(stopK, stopF, null, null, null, null, StopTransfer.TIMED_TRANSFER);
    // Don't forget to also add a TimedTransferEdge
    Vertex fromVertex = graph.getVertex(feedId + ":K_arrive");
    Vertex toVertex = graph.getVertex(feedId + ":F_depart");
    TimedTransferEdge timedTransferEdge = new TimedTransferEdge(fromVertex, toVertex);
    // Plan journey
    path = planJourney(options);
    trips = extractTrips(path);
    // Check whether the trips are still the same
    assertEquals("8.1", trips.get(0).getId().getId());
    assertEquals("4.2", trips.get(1).getId().getId());
    // Now apply a real-time update: let the to-trip be early by 27600 seconds,
    // resulting in a transfer time of 0 seconds
    Trip trip = graph.index.tripForId.get(new AgencyAndId("agency", "4.2"));
    TripPattern pattern = graph.index.patternForTrip.get(trip);
    applyUpdateToTripPattern(pattern, "4.2", "F", 1, 55200, 55200, ScheduleRelationship.SCHEDULED, 0, serviceDate);
    // Plan journey
    path = planJourney(options);
    trips = extractTrips(path);
    // Check whether the trips are still the same
    assertEquals("8.1", trips.get(0).getId().getId());
    assertEquals("4.2", trips.get(1).getId().getId());
    // Now apply a real-time update: let the to-trip be early by 27601 seconds,
    // resulting in a transfer time of -1 seconds
    applyUpdateToTripPattern(pattern, "4.2", "F", 1, 55199, 55199, ScheduleRelationship.SCHEDULED, 0, serviceDate);
    // Plan journey
    path = planJourney(options);
    trips = extractTrips(path);
    // Check whether a later second trip was taken
    assertEquals("8.1", trips.get(0).getId().getId());
    assertEquals("4.3", trips.get(1).getId().getId());
    // "Revert" the real-time update
    applyUpdateToTripPattern(pattern, "4.2", "F", 1, 82800, 82800, ScheduleRelationship.SCHEDULED, 0, serviceDate);
    // Remove the timed transfer from the graph
    graph.removeEdge(timedTransferEdge);
    // Revert the graph, thus using the original transfer table again
    reset(graph);
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) ServiceDate(org.onebusaway.gtfs.model.calendar.ServiceDate) Trip(org.onebusaway.gtfs.model.Trip) TimedTransferEdge(org.opentripplanner.routing.edgetype.TimedTransferEdge) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) Stop(org.onebusaway.gtfs.model.Stop) GraphPath(org.opentripplanner.routing.spt.GraphPath) TripPattern(org.opentripplanner.routing.edgetype.TripPattern)

Aggregations

ServiceDate (org.onebusaway.gtfs.model.calendar.ServiceDate)134 Test (org.junit.Test)49 Date (java.util.Date)46 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)45 ArrayList (java.util.ArrayList)23 ServiceCalendar (org.onebusaway.gtfs.model.ServiceCalendar)23 Calendar (java.util.Calendar)22 ServiceCalendarDate (org.onebusaway.gtfs.model.ServiceCalendarDate)22 HashSet (java.util.HashSet)17 ServiceIdActivation (org.onebusaway.transit_data_federation.services.transit_graph.ServiceIdActivation)14 CalendarServiceData (org.onebusaway.gtfs.model.calendar.CalendarServiceData)13 CalendarService (org.onebusaway.gtfs.services.calendar.CalendarService)13 Set (java.util.Set)11 Trip (org.onebusaway.gtfs.model.Trip)11 TimeZone (java.util.TimeZone)10 GtfsMutableRelationalDao (org.onebusaway.gtfs.services.GtfsMutableRelationalDao)10 TripUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate)9 LocalizedServiceId (org.onebusaway.gtfs.model.calendar.LocalizedServiceId)9 Agency (org.onebusaway.gtfs.model.Agency)8 TripDescriptor (com.google.transit.realtime.GtfsRealtime.TripDescriptor)7