use of org.opentripplanner.routing.edgetype.Timetable in project OpenTripPlanner by opentripplanner.
the class TimetableSnapshotSourceTest method testHandleModifiedTrip.
@Test
public void testHandleModifiedTrip() throws ParseException {
// TODO
// GIVEN
// Get service date of today because old dates will be purged after applying updates
ServiceDate serviceDate = new ServiceDate(Calendar.getInstance());
String modifiedTripId = "10.1";
TripUpdate tripUpdate;
{
final TripDescriptor.Builder tripDescriptorBuilder = TripDescriptor.newBuilder();
tripDescriptorBuilder.setTripId(modifiedTripId);
tripDescriptorBuilder.setScheduleRelationship(TripDescriptor.ScheduleRelationship.MODIFIED);
tripDescriptorBuilder.setStartDate(serviceDate.getAsString());
final Calendar calendar = serviceDate.getAsCalendar(graph.getTimeZone());
final long midnightSecondsSinceEpoch = calendar.getTimeInMillis() / 1000;
final TripUpdate.Builder tripUpdateBuilder = TripUpdate.newBuilder();
tripUpdateBuilder.setTrip(tripDescriptorBuilder);
{
// Stop O
final StopTimeUpdate.Builder stopTimeUpdateBuilder = tripUpdateBuilder.addStopTimeUpdateBuilder();
stopTimeUpdateBuilder.setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.SCHEDULED);
stopTimeUpdateBuilder.setStopId("O");
stopTimeUpdateBuilder.setStopSequence(10);
{
// Arrival
final StopTimeEvent.Builder arrivalBuilder = stopTimeUpdateBuilder.getArrivalBuilder();
arrivalBuilder.setTime(midnightSecondsSinceEpoch + (12 * 3600) + (30 * 60));
arrivalBuilder.setDelay(0);
}
{
// Departure
final StopTimeEvent.Builder departureBuilder = stopTimeUpdateBuilder.getDepartureBuilder();
departureBuilder.setTime(midnightSecondsSinceEpoch + (12 * 3600) + (30 * 60));
departureBuilder.setDelay(0);
}
}
{
// Stop C
final StopTimeUpdate.Builder stopTimeUpdateBuilder = tripUpdateBuilder.addStopTimeUpdateBuilder();
stopTimeUpdateBuilder.setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.SCHEDULED);
stopTimeUpdateBuilder.setStopId("C");
stopTimeUpdateBuilder.setStopSequence(30);
{
// Arrival
final StopTimeEvent.Builder arrivalBuilder = stopTimeUpdateBuilder.getArrivalBuilder();
arrivalBuilder.setTime(midnightSecondsSinceEpoch + (12 * 3600) + (40 * 60));
arrivalBuilder.setDelay(0);
}
{
// Departure
final StopTimeEvent.Builder departureBuilder = stopTimeUpdateBuilder.getDepartureBuilder();
departureBuilder.setTime(midnightSecondsSinceEpoch + (12 * 3600) + (45 * 60));
departureBuilder.setDelay(0);
}
}
{
// Stop D
final StopTimeUpdate.Builder stopTimeUpdateBuilder = tripUpdateBuilder.addStopTimeUpdateBuilder();
stopTimeUpdateBuilder.setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.SKIPPED);
stopTimeUpdateBuilder.setStopId("D");
stopTimeUpdateBuilder.setStopSequence(40);
{
// Arrival
final StopTimeEvent.Builder arrivalBuilder = stopTimeUpdateBuilder.getArrivalBuilder();
arrivalBuilder.setTime(midnightSecondsSinceEpoch + (12 * 3600) + (50 * 60));
arrivalBuilder.setDelay(0);
}
{
// Departure
final StopTimeEvent.Builder departureBuilder = stopTimeUpdateBuilder.getDepartureBuilder();
departureBuilder.setTime(midnightSecondsSinceEpoch + (12 * 3600) + (51 * 60));
departureBuilder.setDelay(0);
}
}
{
// Stop P
final StopTimeUpdate.Builder stopTimeUpdateBuilder = tripUpdateBuilder.addStopTimeUpdateBuilder();
stopTimeUpdateBuilder.setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.SCHEDULED);
stopTimeUpdateBuilder.setStopId("P");
stopTimeUpdateBuilder.setStopSequence(50);
{
// Arrival
final StopTimeEvent.Builder arrivalBuilder = stopTimeUpdateBuilder.getArrivalBuilder();
arrivalBuilder.setTime(midnightSecondsSinceEpoch + (12 * 3600) + (55 * 60));
arrivalBuilder.setDelay(0);
}
{
// Departure
final StopTimeEvent.Builder departureBuilder = stopTimeUpdateBuilder.getDepartureBuilder();
departureBuilder.setTime(midnightSecondsSinceEpoch + (12 * 3600) + (55 * 60));
departureBuilder.setDelay(0);
}
}
tripUpdate = tripUpdateBuilder.build();
}
// WHEN
updater.applyTripUpdates(graph, fullDataset, Arrays.asList(tripUpdate), feedId);
// THEN
final TimetableSnapshot snapshot = updater.getTimetableSnapshot();
// Original trip pattern
{
final AgencyAndId tripId = new AgencyAndId(feedId, modifiedTripId);
final Trip trip = graph.index.tripForId.get(tripId);
final TripPattern originalTripPattern = graph.index.patternForTrip.get(trip);
final Timetable originalTimetableForToday = snapshot.resolve(originalTripPattern, serviceDate);
final Timetable originalTimetableScheduled = snapshot.resolve(originalTripPattern, null);
assertNotSame(originalTimetableForToday, originalTimetableScheduled);
final int originalTripIndexScheduled = originalTimetableScheduled.getTripIndex(modifiedTripId);
assertTrue("Original trip should be found in scheduled time table", originalTripIndexScheduled > -1);
final TripTimes originalTripTimesScheduled = originalTimetableScheduled.getTripTimes(originalTripIndexScheduled);
assertFalse("Original trip times should not be canceled in scheduled time table", originalTripTimesScheduled.isCanceled());
assertEquals(RealTimeState.SCHEDULED, originalTripTimesScheduled.getRealTimeState());
final int originalTripIndexForToday = originalTimetableForToday.getTripIndex(modifiedTripId);
assertTrue("Original trip should be found in time table for service date", originalTripIndexForToday > -1);
final TripTimes originalTripTimesForToday = originalTimetableForToday.getTripTimes(originalTripIndexForToday);
assertTrue("Original trip times should be canceled in time table for service date", originalTripTimesForToday.isCanceled());
assertEquals(RealTimeState.CANCELED, originalTripTimesForToday.getRealTimeState());
}
// New trip pattern
{
final TripPattern newTripPattern = snapshot.getLastAddedTripPattern(feedId, modifiedTripId, serviceDate);
assertNotNull("New trip pattern should be found", newTripPattern);
final Timetable newTimetableForToday = snapshot.resolve(newTripPattern, serviceDate);
final Timetable newTimetableScheduled = snapshot.resolve(newTripPattern, null);
assertNotSame(newTimetableForToday, newTimetableScheduled);
final int newTimetableForTodayModifiedTripIndex = newTimetableForToday.getTripIndex(modifiedTripId);
assertTrue("New trip should be found in time table for service date", newTimetableForTodayModifiedTripIndex > -1);
assertEquals(RealTimeState.MODIFIED, newTimetableForToday.getTripTimes(newTimetableForTodayModifiedTripIndex).getRealTimeState());
assertEquals("New trip should not be found in scheduled time table", -1, newTimetableScheduled.getTripIndex(modifiedTripId));
}
}
use of org.opentripplanner.routing.edgetype.Timetable in project OpenTripPlanner by opentripplanner.
the class TimetableSnapshotSourceTest method testHandleCanceledTrip.
@Test
public void testHandleCanceledTrip() throws InvalidProtocolBufferException {
final AgencyAndId tripId = new AgencyAndId(feedId, "1.1");
final AgencyAndId tripId2 = new AgencyAndId(feedId, "1.2");
final Trip trip = graph.index.tripForId.get(tripId);
final TripPattern pattern = graph.index.patternForTrip.get(trip);
final int tripIndex = pattern.scheduledTimetable.getTripIndex(tripId);
final int tripIndex2 = pattern.scheduledTimetable.getTripIndex(tripId2);
updater.applyTripUpdates(graph, fullDataset, Arrays.asList(TripUpdate.parseFrom(cancellation)), feedId);
final TimetableSnapshot snapshot = updater.getTimetableSnapshot();
final Timetable forToday = snapshot.resolve(pattern, serviceDate);
final Timetable schedule = snapshot.resolve(pattern, null);
assertNotSame(forToday, schedule);
assertNotSame(forToday.getTripTimes(tripIndex), schedule.getTripTimes(tripIndex));
assertSame(forToday.getTripTimes(tripIndex2), schedule.getTripTimes(tripIndex2));
final TripTimes tripTimes = forToday.getTripTimes(tripIndex);
for (int i = 0; i < tripTimes.getNumStops(); i++) {
assertEquals(TripTimes.UNAVAILABLE, tripTimes.getDepartureTime(i));
assertEquals(TripTimes.UNAVAILABLE, tripTimes.getArrivalTime(i));
}
assertEquals(RealTimeState.CANCELED, tripTimes.getRealTimeState());
}
use of org.opentripplanner.routing.edgetype.Timetable in project OpenTripPlanner by opentripplanner.
the class TimetableSnapshotSourceTest method testHandleDelayedTrip.
@Test
public void testHandleDelayedTrip() {
final AgencyAndId tripId = new AgencyAndId(feedId, "1.1");
final AgencyAndId tripId2 = new AgencyAndId(feedId, "1.2");
final Trip trip = graph.index.tripForId.get(tripId);
final TripPattern pattern = graph.index.patternForTrip.get(trip);
final int tripIndex = pattern.scheduledTimetable.getTripIndex(tripId);
final int tripIndex2 = pattern.scheduledTimetable.getTripIndex(tripId2);
final TripDescriptor.Builder tripDescriptorBuilder = TripDescriptor.newBuilder();
tripDescriptorBuilder.setTripId("1.1");
tripDescriptorBuilder.setScheduleRelationship(TripDescriptor.ScheduleRelationship.SCHEDULED);
final TripUpdate.Builder tripUpdateBuilder = TripUpdate.newBuilder();
tripUpdateBuilder.setTrip(tripDescriptorBuilder);
final StopTimeUpdate.Builder stopTimeUpdateBuilder = tripUpdateBuilder.addStopTimeUpdateBuilder();
stopTimeUpdateBuilder.setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.SCHEDULED);
stopTimeUpdateBuilder.setStopSequence(2);
final StopTimeEvent.Builder arrivalBuilder = stopTimeUpdateBuilder.getArrivalBuilder();
final StopTimeEvent.Builder departureBuilder = stopTimeUpdateBuilder.getDepartureBuilder();
arrivalBuilder.setDelay(1);
departureBuilder.setDelay(1);
final TripUpdate tripUpdate = tripUpdateBuilder.build();
updater.applyTripUpdates(graph, fullDataset, Arrays.asList(tripUpdate), feedId);
final TimetableSnapshot snapshot = updater.getTimetableSnapshot();
final Timetable forToday = snapshot.resolve(pattern, serviceDate);
final Timetable schedule = snapshot.resolve(pattern, null);
assertNotSame(forToday, schedule);
assertNotSame(forToday.getTripTimes(tripIndex), schedule.getTripTimes(tripIndex));
assertSame(forToday.getTripTimes(tripIndex2), schedule.getTripTimes(tripIndex2));
assertEquals(1, forToday.getTripTimes(tripIndex).getArrivalDelay(1));
assertEquals(1, forToday.getTripTimes(tripIndex).getDepartureDelay(1));
assertEquals(RealTimeState.SCHEDULED, schedule.getTripTimes(tripIndex).getRealTimeState());
assertEquals(RealTimeState.UPDATED, forToday.getTripTimes(tripIndex).getRealTimeState());
assertEquals(RealTimeState.SCHEDULED, schedule.getTripTimes(tripIndex2).getRealTimeState());
assertEquals(RealTimeState.SCHEDULED, forToday.getTripTimes(tripIndex2).getRealTimeState());
}
use of org.opentripplanner.routing.edgetype.Timetable in project OpenTripPlanner by opentripplanner.
the class GTFSPatternHopFactory method interline.
/**
* Identify interlined trips (where a physical vehicle continues on to another logical trip)
* and update the TripPatterns accordingly. This must be called after all the pattern edges and vertices
* are already created, because it creates interline dwell edges between existing pattern arrive/depart vertices.
*/
private void interline(Collection<TripPattern> tripPatterns, Graph graph) {
/* Record which Pattern each interlined TripTimes belongs to. */
Map<TripTimes, TripPattern> patternForTripTimes = Maps.newHashMap();
/* TripTimes grouped by the block ID and service ID of their trips. Must be a ListMultimap to allow sorting. */
ListMultimap<BlockIdAndServiceId, TripTimes> tripTimesForBlock = ArrayListMultimap.create();
LOG.info("Finding interlining trips based on block IDs.");
for (TripPattern pattern : tripPatterns) {
Timetable timetable = pattern.scheduledTimetable;
/* TODO: Block semantics seem undefined for frequency trips, so skip them? */
for (TripTimes tripTimes : timetable.tripTimes) {
Trip trip = tripTimes.trip;
if (!Strings.isNullOrEmpty(trip.getBlockId())) {
tripTimesForBlock.put(new BlockIdAndServiceId(trip), tripTimes);
// For space efficiency, only record times that are part of a block.
patternForTripTimes.put(tripTimes, pattern);
}
}
}
/* Associate pairs of TripPatterns with lists of trips that continue from one pattern to the other. */
Multimap<P2<TripPattern>, P2<Trip>> interlines = ArrayListMultimap.create();
/*
Sort trips within each block by first departure time, then iterate over trips in this block and service,
linking them. Has no effect on single-trip blocks.
*/
SERVICE_BLOCK: for (BlockIdAndServiceId block : tripTimesForBlock.keySet()) {
List<TripTimes> blockTripTimes = tripTimesForBlock.get(block);
Collections.sort(blockTripTimes);
TripTimes prev = null;
for (TripTimes curr : blockTripTimes) {
if (prev != null) {
if (prev.getDepartureTime(prev.getNumStops() - 1) > curr.getArrivalTime(0)) {
LOG.error("Trip times within block {} are not increasing on service {} after trip {}.", block.blockId, block.serviceId, prev.trip.getId());
continue SERVICE_BLOCK;
}
TripPattern prevPattern = patternForTripTimes.get(prev);
TripPattern currPattern = patternForTripTimes.get(curr);
Stop fromStop = prevPattern.getStop(prevPattern.getStops().size() - 1);
Stop toStop = currPattern.getStop(0);
double teleportationDistance = SphericalDistanceLibrary.fastDistance(fromStop.getLat(), fromStop.getLon(), toStop.getLat(), toStop.getLon());
if (teleportationDistance > maxInterlineDistance) {
// FIXME Trimet data contains a lot of these -- in their data, two trips sharing a block ID just
// means that they are served by the same vehicle, not that interlining is automatically allowed.
// see #1654
// LOG.error(graph.addBuilderAnnotation(new InterliningTeleport(prev.trip, block.blockId, (int)teleportationDistance)));
// Only skip this particular interline edge; there may be other valid ones in the block.
} else {
interlines.put(new P2<TripPattern>(prevPattern, currPattern), new P2<Trip>(prev.trip, curr.trip));
}
}
prev = curr;
}
}
/*
Create the PatternInterlineDwell edges linking together TripPatterns.
All the pattern vertices and edges must already have been created.
*/
for (P2<TripPattern> patterns : interlines.keySet()) {
TripPattern prevPattern = patterns.first;
TripPattern nextPattern = patterns.second;
// This is a single (uni-directional) edge which may be traversed forward and backward.
PatternInterlineDwell edge = new PatternInterlineDwell(prevPattern, nextPattern);
for (P2<Trip> trips : interlines.get(patterns)) {
edge.add(trips.first, trips.second);
}
}
LOG.info("Done finding interlining trips and creating the corresponding edges.");
}
use of org.opentripplanner.routing.edgetype.Timetable in project OpenTripPlanner by opentripplanner.
the class OnBoardDepartServiceImpl method setupDepartOnBoard.
@Override
public Vertex setupDepartOnBoard(RoutingContext ctx) {
RoutingRequest opt = ctx.opt;
opt.rctx = ctx;
/* 1. Get the list of PatternHop for the given trip ID. */
AgencyAndId tripId = opt.startingTransitTripId;
Trip trip = ctx.graph.index.tripForId.get(tripId);
TripPattern tripPattern = ctx.graph.index.patternForTrip.get(trip);
if (tripPattern == null) {
// TODO Shouldn't we bailout on a normal trip plan here, returning null ?
throw new IllegalArgumentException("Unknown/invalid trip ID: " + tripId);
}
List<PatternHop> hops = tripPattern.getPatternHops();
// Origin point, optional
Double lon = opt.from.lng;
Double lat = opt.from.lat;
PatternStopVertex nextStop;
TripTimes bestTripTimes = null;
ServiceDay bestServiceDay = null;
int bestStopIndex = 0;
double fractionCovered;
LineString geomRemaining;
Coordinate point = lon == null || lat == null ? null : new Coordinate(lon, lat);
if (point != null) {
/*
* 2. Get the best hop from the list, given the parameters. Currently look for nearest hop,
* taking into account shape if available. If no shape are present, the computed hop and
* fraction may be a bit away from what it should be.
*/
PatternHop bestHop = null;
double minDist = Double.MAX_VALUE;
for (PatternHop hop : hops) {
LineString line = hop.getGeometry();
double dist = SphericalDistanceLibrary.fastDistance(point, line);
if (dist < minDist) {
minDist = dist;
bestHop = hop;
}
}
if (minDist > 1000)
LOG.warn("On-board depart: origin point suspiciously away from nearest trip shape ({} meters)", minDist);
else
LOG.info("On-board depart: origin point {} meters away from hop shape", minDist);
/*
* 3. Compute the fraction covered percentage of the current hop. This assume a constant
* trip speed alongside the whole hop: this should be quite precise for small hops
* (buses), a bit less for longer ones (long distance train). Shape linear distance is
* of no help here, as the unit is arbitrary (and probably usually a distance).
*/
LineString geometry = bestHop.getGeometry();
P2<LineString> geomPair = GeometryUtils.splitGeometryAtPoint(geometry, point);
geomRemaining = geomPair.second;
double total = SphericalDistanceLibrary.fastLength(geometry);
double remaining = SphericalDistanceLibrary.fastLength(geomRemaining);
fractionCovered = total > 0.0 ? (double) (1.0 - remaining / total) : 0.0;
nextStop = (PatternStopVertex) bestHop.getToVertex();
bestStopIndex = bestHop.getStopIndex();
/*
* 4. Compute service day based on given departure day/time relative to
* scheduled/real-time trip time for hop. This is needed as for some trips any service
* day can apply.
*/
int minDelta = Integer.MAX_VALUE;
int actDelta = 0;
for (ServiceDay serviceDay : ctx.serviceDays) {
TripPattern pattern = nextStop.getTripPattern();
Timetable timetable = pattern.getUpdatedTimetable(opt, serviceDay);
// Get the tripTimes including real-time updates for the serviceDay
TripTimes tripTimes = timetable.getTripTimes(timetable.getTripIndex(tripId));
int depTime = tripTimes.getDepartureTime(bestStopIndex);
int arrTime = tripTimes.getArrivalTime(bestStopIndex + 1);
int estTime = (int) Math.round(depTime * fractionCovered + arrTime * (1 - fractionCovered));
int time = serviceDay.secondsSinceMidnight(opt.dateTime);
/*
* TODO Weight differently early vs late time, as the probability of any transit
* being late is higher than being early. However, this has impact if your bus is
* more than 12h late, I don't think this would happen really often.
*/
int deltaTime = Math.abs(time - estTime);
if (deltaTime < minDelta) {
minDelta = deltaTime;
actDelta = time - estTime;
bestTripTimes = tripTimes;
bestServiceDay = serviceDay;
}
}
if (minDelta > 60000)
// Being more than 1h late should not happen often
LOG.warn("On-board depart: delta between scheduled/real-time and actual time suspiciously large: {} seconds.", actDelta);
else
LOG.info("On-board depart: delta between scheduled/real-time and actual time is {} seconds.", actDelta);
} else {
/* 2. Compute service day */
for (ServiceDay serviceDay : ctx.serviceDays) {
Timetable timetable = tripPattern.getUpdatedTimetable(opt, serviceDay);
// Get the tripTimes including real-time updates for the serviceDay
TripTimes tripTimes = timetable.getTripTimes(timetable.getTripIndex(tripId));
int depTime = tripTimes.getDepartureTime(0);
int arrTime = tripTimes.getArrivalTime(tripTimes.getNumStops() - 1);
int time = serviceDay.secondsSinceMidnight(opt.dateTime);
if (depTime <= time && time <= arrTime) {
bestTripTimes = tripTimes;
bestServiceDay = serviceDay;
}
}
if (bestServiceDay == null) {
throw new RuntimeException("Unable to determine on-board depart service day.");
}
int time = bestServiceDay.secondsSinceMidnight(opt.dateTime);
/*
* 3. Get the best hop from the list, given the parameters. This is done by finding the
* last hop that has not yet departed.
*/
PatternHop bestHop = null;
for (PatternHop hop : hops) {
int stopIndex = hop.getStopIndex();
int depTime = bestTripTimes.getDepartureTime(stopIndex);
int arrTime = bestTripTimes.getArrivalTime(stopIndex + 1);
if (time == arrTime) {
return ctx.graph.getVertex(hop.getEndStop().getId().toString());
} else if (depTime < time) {
bestHop = hop;
bestStopIndex = stopIndex;
} else if (time == depTime || bestTripTimes.getArrivalTime(bestStopIndex + 1) < time) {
return ctx.graph.getVertex(hop.getBeginStop().getId().toString());
} else {
break;
}
}
nextStop = (PatternStopVertex) bestHop.getToVertex();
LineString geometry = bestHop.getGeometry();
/*
* 4. Compute the fraction covered percentage of the current hop. Once again a constant
* trip speed is assumed. The linear distance of the shape is used, so the results are
* not 100% accurate. On the flip side, they are easy to compute and very well testable.
*/
int depTime = bestTripTimes.getDepartureTime(bestStopIndex);
int arrTime = bestTripTimes.getArrivalTime(bestStopIndex + 1);
fractionCovered = ((double) (time - depTime)) / ((double) (arrTime - depTime));
P2<LineString> geomPair = GeometryUtils.splitGeometryAtFraction(geometry, fractionCovered);
geomRemaining = geomPair.second;
if (geometry.isEmpty()) {
lon = Double.NaN;
lat = Double.NaN;
} else {
Coordinate start;
if (geomRemaining.isEmpty()) {
start = geometry.getCoordinateN(geometry.getNumPoints() - 1);
} else {
start = geomRemaining.getCoordinateN(0);
}
lon = start.x;
lat = start.y;
}
}
OnboardDepartVertex onboardDepart = new OnboardDepartVertex("on_board_depart", lon, lat);
OnBoardDepartPatternHop startHop = new OnBoardDepartPatternHop(onboardDepart, nextStop, bestTripTimes, bestServiceDay, bestStopIndex, fractionCovered);
startHop.setGeometry(geomRemaining);
return onboardDepart;
}
Aggregations