Search in sources :

Example 11 with StopTimeUpdate

use of com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate in project OpenTripPlanner by opentripplanner.

the class TimetableSnapshotSource method addTripToGraphAndBuffer.

/**
 * Add a (new) trip to the graph and the buffer
 *
 * @param graph graph
 * @param trip trip
 * @param tripUpdate trip update containing stop time updates
 * @param stops list of stops corresponding to stop time updates
 * @param serviceDate service date of trip
 * @param realTimeState real-time state of new trip
 * @return true iff successful
 */
private boolean addTripToGraphAndBuffer(final String feedId, final Graph graph, final Trip trip, final TripUpdate tripUpdate, final List<Stop> stops, final ServiceDate serviceDate, final RealTimeState realTimeState) {
    // Preconditions
    Preconditions.checkNotNull(stops);
    Preconditions.checkArgument(tripUpdate.getStopTimeUpdateCount() == stops.size(), "number of stop should match the number of stop time updates");
    // Calculate seconds since epoch on GTFS midnight (noon minus 12h) of service date
    final Calendar serviceCalendar = serviceDate.getAsCalendar(timeZone);
    final long midnightSecondsSinceEpoch = serviceCalendar.getTimeInMillis() / MILLIS_PER_SECOND;
    // Create StopTimes
    final List<StopTime> stopTimes = new ArrayList<>(tripUpdate.getStopTimeUpdateCount());
    for (int index = 0; index < tripUpdate.getStopTimeUpdateCount(); ++index) {
        final StopTimeUpdate stopTimeUpdate = tripUpdate.getStopTimeUpdate(index);
        final Stop stop = stops.get(index);
        // Determine whether stop is skipped
        final boolean skippedStop = isStopSkipped(stopTimeUpdate);
        // Only create stop time for non-skipped stops
        if (!skippedStop) {
            // Create stop time
            final StopTime stopTime = new StopTime();
            stopTime.setTrip(trip);
            stopTime.setStop(stop);
            // Set arrival time
            if (stopTimeUpdate.hasArrival() && stopTimeUpdate.getArrival().hasTime()) {
                final long arrivalTime = stopTimeUpdate.getArrival().getTime() - midnightSecondsSinceEpoch;
                if (arrivalTime < 0 || arrivalTime > MAX_ARRIVAL_DEPARTURE_TIME) {
                    LOG.warn("ADDED trip has invalid arrival time (compared to start date in " + "TripDescriptor), skipping.");
                    return false;
                }
                stopTime.setArrivalTime((int) arrivalTime);
            }
            // Set departure time
            if (stopTimeUpdate.hasDeparture() && stopTimeUpdate.getDeparture().hasTime()) {
                final long departureTime = stopTimeUpdate.getDeparture().getTime() - midnightSecondsSinceEpoch;
                if (departureTime < 0 || departureTime > MAX_ARRIVAL_DEPARTURE_TIME) {
                    LOG.warn("ADDED trip has invalid departure time (compared to start date in " + "TripDescriptor), skipping.");
                    return false;
                }
                stopTime.setDepartureTime((int) departureTime);
            }
            // Exact time
            stopTime.setTimepoint(1);
            if (stopTimeUpdate.hasStopSequence()) {
                stopTime.setStopSequence(stopTimeUpdate.getStopSequence());
            }
            // Set different pickup type for last stop
            if (index == tripUpdate.getStopTimeUpdateCount() - 1) {
                // No pickup available
                stopTime.setPickupType(1);
            } else {
                // Regularly scheduled pickup
                stopTime.setPickupType(0);
            }
            // Set different drop off type for first stop
            if (index == 0) {
                // No drop off available
                stopTime.setDropOffType(1);
            } else {
                // Regularly scheduled drop off
                stopTime.setDropOffType(0);
            }
            // Add stop time to list
            stopTimes.add(stopTime);
        }
    }
    // TODO: filter/interpolate stop times like in GTFSPatternHopFactory?
    // Create StopPattern
    final StopPattern stopPattern = new StopPattern(stopTimes);
    // Get cached trip pattern or create one if it doesn't exist yet
    final TripPattern pattern = tripPatternCache.getOrCreateTripPattern(stopPattern, trip.getRoute(), graph);
    // Add service code to bitset of pattern if needed (using copy on write)
    final int serviceCode = graph.serviceCodes.get(trip.getServiceId());
    if (!pattern.getServices().get(serviceCode)) {
        final BitSet services = (BitSet) pattern.getServices().clone();
        services.set(serviceCode);
        pattern.setServices(services);
    }
    // Create new trip times
    final TripTimes newTripTimes = new TripTimes(trip, stopTimes, graph.deduplicator);
    // TODO: should we incorporate the delay field if present?
    for (int stopIndex = 0; stopIndex < newTripTimes.getNumStops(); stopIndex++) {
        newTripTimes.updateArrivalTime(stopIndex, newTripTimes.getScheduledArrivalTime(stopIndex));
        newTripTimes.updateDepartureTime(stopIndex, newTripTimes.getScheduledDepartureTime(stopIndex));
    }
    // Set service code of new trip times
    newTripTimes.serviceCode = serviceCode;
    // Make sure that updated trip times have the correct real time state
    newTripTimes.setRealTimeState(realTimeState);
    // Add new trip times to the buffer
    final boolean success = buffer.update(feedId, pattern, newTripTimes, serviceDate);
    return success;
}
Also used : StopPattern(org.opentripplanner.model.StopPattern) Stop(org.onebusaway.gtfs.model.Stop) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) BitSet(java.util.BitSet) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) StopTimeUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) StopTime(org.onebusaway.gtfs.model.StopTime)

Example 12 with StopTimeUpdate

use of com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate in project onebusaway-application-modules by camsys.

the class GtfsRealtimeTripLibraryTest method testCreateVehicleLocationRecordForUpdate_FutureDay.

// Ensure that if we get an update for a future day we propagate a prediction for that day.
// (This is equivalent to timestamp on feed being early incorrectly, since currentTime in
// GtfsRealtimeTripLibrary is set via the timestamp.)
@Test
public void testCreateVehicleLocationRecordForUpdate_FutureDay() {
    final long day = TimeUnit.DAYS.toMillis(1);
    StopTimeUpdate.Builder stopTimeUpdate = stopTimeUpdateWithDepartureDelay("stopA", 180);
    TripUpdate.Builder tripUpdate = tripUpdate("tripA", (_library.getCurrentTime() + day) / 1000, 120, stopTimeUpdate);
    TripEntryImpl tripA = trip("tripA");
    stopTime(0, stop("stopA", 0, 0), tripA, time(7, 30), 0.0);
    BlockEntryImpl blockA = block("blockA");
    BlockConfigurationEntry blockConfigA = blockConfiguration(blockA, serviceIds("s1"), tripA);
    BlockInstance blockInstanceA = new BlockInstance(blockConfigA, 0L);
    BlockInstance blockInstanceB = new BlockInstance(blockConfigA, day);
    Mockito.when(_entitySource.getTrip("tripA")).thenReturn(tripA);
    Mockito.when(_blockCalendarService.getActiveBlocks(Mockito.eq(blockA.getId()), Mockito.anyLong(), Mockito.longThat(new ArgumentMatcher<Long>() {

        @Override
        public boolean matches(Object argument) {
            return ((Long) argument) < day;
        }
    }))).thenReturn(Arrays.asList(blockInstanceA));
    Mockito.when(_blockCalendarService.getActiveBlocks(Mockito.eq(blockA.getId()), Mockito.anyLong(), Mockito.longThat(new ArgumentMatcher<Long>() {

        @Override
        public boolean matches(Object argument) {
            return ((Long) argument) >= day;
        }
    }))).thenReturn(Arrays.asList(blockInstanceB));
    FeedMessage.Builder TU = createFeed();
    TU.addEntity(feed(tripUpdate));
    FeedMessage.Builder VP = createFeed();
    List<CombinedTripUpdatesAndVehiclePosition> updates = _library.groupTripUpdatesAndVehiclePositions(TU.build(), VP.build());
    CombinedTripUpdatesAndVehiclePosition update = updates.get(0);
    VehicleLocationRecord record = _library.createVehicleLocationRecordForUpdate(update);
    TimepointPredictionRecord tpr = record.getTimepointPredictions().get(0);
    long departure = tpr.getTimepointPredictedDepartureTime();
    // 7:30 + 3 min delay + on next day
    assertEquals(departure, time(7, 33) * 1000 + day);
}
Also used : TripUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate) TripEntryImpl(org.onebusaway.transit_data_federation.impl.transit_graph.TripEntryImpl) FeedMessage(com.google.transit.realtime.GtfsRealtime.FeedMessage) BlockInstance(org.onebusaway.transit_data_federation.services.blocks.BlockInstance) ArgumentMatcher(org.mockito.ArgumentMatcher) StopTimeUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate) VehicleLocationRecord(org.onebusaway.realtime.api.VehicleLocationRecord) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord) BlockEntryImpl(org.onebusaway.transit_data_federation.impl.transit_graph.BlockEntryImpl) BlockConfigurationEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry) Test(org.junit.Test)

Example 13 with StopTimeUpdate

use of com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate in project onebusaway-application-modules by camsys.

the class GtfsRealtimeTripLibraryTest method testCreateVehicleLocationRecordForUpdate_WithStopTimeUpdates.

@Test
public void testCreateVehicleLocationRecordForUpdate_WithStopTimeUpdates() {
    StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder();
    stopTimeUpdate.setStopId("stopA");
    StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder();
    stopTimeEvent.setDelay(180);
    stopTimeUpdate.setDeparture(stopTimeEvent);
    TripUpdate tripUpdate = TripUpdate.newBuilder().setTrip(TripDescriptor.newBuilder().setTripId("tripA")).setDelay(120).setTimestamp(123456789).addStopTimeUpdate(stopTimeUpdate).build();
    TripEntryImpl tripA = trip("tripA");
    stopTime(0, stop("stopA", 0, 0), tripA, time(7, 30), 0.0);
    BlockEntryImpl blockA = block("blockA");
    BlockConfigurationEntry blockConfigA = blockConfiguration(blockA, serviceIds("s1"), tripA);
    BlockInstance blockInstanceA = new BlockInstance(blockConfigA, 0L);
    Mockito.when(_blockCalendarService.getActiveBlocks(Mockito.eq(blockA.getId()), Mockito.anyLong(), Mockito.anyLong())).thenReturn(Arrays.asList(blockInstanceA));
    CombinedTripUpdatesAndVehiclePosition update = new CombinedTripUpdatesAndVehiclePosition();
    update.block = new BlockDescriptor();
    update.block.setBlockInstance(blockInstanceA);
    update.tripUpdates = Arrays.asList(tripUpdate);
    VehicleLocationRecord record = _library.createVehicleLocationRecordForUpdate(update);
    TimepointPredictionRecord tpr = record.getTimepointPredictions().get(0);
    long departure = tpr.getTimepointPredictedDepartureTime();
    // 7:30 plus 3 min delay, + now we are in ms.
    assertEquals(departure, time(7, 33) * 1000);
}
Also used : TripUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate) TripEntryImpl(org.onebusaway.transit_data_federation.impl.transit_graph.TripEntryImpl) StopTimeEvent(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent) BlockInstance(org.onebusaway.transit_data_federation.services.blocks.BlockInstance) StopTimeUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate) VehicleLocationRecord(org.onebusaway.realtime.api.VehicleLocationRecord) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord) BlockEntryImpl(org.onebusaway.transit_data_federation.impl.transit_graph.BlockEntryImpl) BlockConfigurationEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry) Test(org.junit.Test)

Example 14 with StopTimeUpdate

use of com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate in project onebusaway-application-modules by camsys.

the class GtfsRealtimeTripLibraryTest method testTprInterpolation_2.

/**
 * Test that we do NOT create new timepoint prediction record when it
 * already exists.
 *
 * Current time = 7:25. Trip update delay = 2 minutes
 *          Schedule time    Real-time from feed  Timepoint predicted departure time
 * Stop A   7:30             7:33                 7:33 (and only one)
 */
@Test
public void testTprInterpolation_2() {
    _library.setCurrentTime(time(7, 25) * 1000);
    TripEntryImpl tripA = trip("tripA");
    stopTime(0, stop("stopA", 0, 0), tripA, time(7, 30), 0.0);
    BlockEntryImpl blockA = block("blockA");
    BlockConfigurationEntry blockConfigA = blockConfiguration(blockA, serviceIds("s1"), tripA);
    BlockInstance blockInstanceA = new BlockInstance(blockConfigA, 0L);
    StopTimeUpdate.Builder stopTimeUpdate = stopTimeUpdateWithDepartureDelay("stopA", 180);
    TripUpdate.Builder tripUpdate = tripUpdate("tripA", _library.getCurrentTime() / 1000, 120, stopTimeUpdate);
    Mockito.when(_entitySource.getTrip("tripA")).thenReturn(tripA);
    Mockito.when(_blockCalendarService.getActiveBlocks(Mockito.eq(blockA.getId()), Mockito.anyLong(), Mockito.anyLong())).thenReturn(Arrays.asList(blockInstanceA));
    VehicleLocationRecord record = vehicleLocationRecord(tripUpdate);
    long stopADept = getPredictedDepartureTimeByStopId(record, "stopA");
    assertEquals(stopADept, time(7, 33) * 1000);
    assertEquals(record.getTimepointPredictions().size(), 1);
}
Also used : TripUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate) BlockInstance(org.onebusaway.transit_data_federation.services.blocks.BlockInstance) StopTimeUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate) VehicleLocationRecord(org.onebusaway.realtime.api.VehicleLocationRecord) BlockEntryImpl(org.onebusaway.transit_data_federation.impl.transit_graph.BlockEntryImpl) BlockConfigurationEntry(org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry) TripEntryImpl(org.onebusaway.transit_data_federation.impl.transit_graph.TripEntryImpl) Test(org.junit.Test)

Example 15 with StopTimeUpdate

use of com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate in project onebusaway-application-modules by camsys.

the class GtfsRealtimeRetrieverImpl method writeStopTimeUpdate.

private StopTimeUpdate writeStopTimeUpdate(StopTimeUpdateModel stum) {
    if (stum == null)
        return null;
    StopTimeUpdate.Builder stu = StopTimeUpdate.newBuilder();
    if (stum.getStopSequence() != null) {
        stu.setStopSequence(stum.getStopSequence().intValue());
    }
    if (stum.getStopId() != null) {
        String parsedStopId = parseId(stum.getStopId());
        if (parsedStopId != null) {
            stu.setStopId(parseId(stum.getStopId()));
        } else {
            // parsing failed (invalid agency-and-id) but pass along as is
            stu.setStopId(stum.getStopId());
        }
    }
    if (stum.getArrivalDelay() != null || stum.getArrivalTime() != null) {
        StopTimeEvent arrival = writeStopTimeEvent(stum.getArrivalDelay(), stum.getArrivalTime(), stum.getArrivalUncertainty());
        stu.setArrival(arrival);
    }
    if (stum.getDepartureDelay() != null || stum.getDepartureTime() != null) {
        StopTimeEvent dept = writeStopTimeEvent(stum.getDepartureDelay(), stum.getDepartureTime(), stum.getDepartureUncertainty());
        stu.setDeparture(dept);
    }
    StopTimeUpdate.ScheduleRelationship sr = StopTimeUpdate.ScheduleRelationship.valueOf(stum.getScheduleRelationship());
    if (sr != null) {
        stu.setScheduleRelationship(sr);
    }
    return stu.build();
}
Also used : StopTimeEvent(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent) StopTimeUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate)

Aggregations

StopTimeUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate)15 TripUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate)9 BlockInstance (org.onebusaway.transit_data_federation.services.blocks.BlockInstance)8 Test (org.junit.Test)7 BlockConfigurationEntry (org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry)7 VehicleLocationRecord (org.onebusaway.realtime.api.VehicleLocationRecord)6 BlockEntryImpl (org.onebusaway.transit_data_federation.impl.transit_graph.BlockEntryImpl)6 TripEntryImpl (org.onebusaway.transit_data_federation.impl.transit_graph.TripEntryImpl)6 StopTimeEvent (com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent)5 TimepointPredictionRecord (org.onebusaway.realtime.api.TimepointPredictionRecord)5 ArrayList (java.util.ArrayList)4 Date (java.util.Date)4 TripDescriptor (com.google.transit.realtime.GtfsRealtime.TripDescriptor)3 FeedMessage (com.google.transit.realtime.GtfsRealtime.FeedMessage)2 VehicleDescriptor (com.google.transit.realtime.GtfsRealtime.VehicleDescriptor)2 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)2 Stop (org.onebusaway.gtfs.model.Stop)2 StopTimeUpdateModel (org.onebusaway.gtfs_realtime.model.StopTimeUpdateModel)2 TripTimes (org.opentripplanner.routing.trippattern.TripTimes)2 FeedEntity (com.google.transit.realtime.GtfsRealtime.FeedEntity)1