Search in sources :

Example 6 with TripPattern

use of org.opentripplanner.model.TripPattern in project OpenTripPlanner by opentripplanner.

the class SiriTimetableSnapshotSource method cancelPreviouslyAddedTrip.

/**
 * Cancel previously added trip from buffer if there is a previously added trip with given trip
 * id (without agency id) on service date
 *
 * @param feedId feed id the trip id belongs to
 * @param tripId trip id without agency id
 * @param serviceDate service date
 * @return true if a previously added trip was cancelled
 */
private boolean cancelPreviouslyAddedTrip(final String feedId, final String tripId, final ServiceDate serviceDate) {
    boolean success = false;
    final TripPattern pattern = buffer.getLastAddedTripPattern(new FeedScopedId(feedId, tripId), serviceDate);
    if (pattern != null) {
        // Cancel trip times for this trip in this pattern
        final Timetable timetable = buffer.resolve(pattern, serviceDate);
        final int tripIndex = timetable.getTripIndex(tripId);
        if (tripIndex == -1) {
            LOG.warn("Could not cancel previously added trip {}", tripId);
        } else {
            final TripTimes newTripTimes = new TripTimes(timetable.getTripTimes(tripIndex));
            newTripTimes.cancel();
            buffer.update(pattern, newTripTimes, serviceDate);
            // buffer.removeLastAddedTripPattern(feedId, tripId, serviceDate);
            success = true;
        }
    }
    return success;
}
Also used : Timetable(org.opentripplanner.model.Timetable) FeedScopedId(org.opentripplanner.model.FeedScopedId) TimetableHelper.createUpdatedTripTimes(org.opentripplanner.ext.siri.TimetableHelper.createUpdatedTripTimes) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) TripPattern(org.opentripplanner.model.TripPattern)

Example 7 with TripPattern

use of org.opentripplanner.model.TripPattern in project OpenTripPlanner by opentripplanner.

the class SiriTimetableSnapshotSource method handleAddedTrip.

private boolean handleAddedTrip(Graph graph, String feedId, EstimatedVehicleJourney estimatedVehicleJourney) {
    // Verifying values required in SIRI Profile
    // Added ServiceJourneyId
    String newServiceJourneyRef = estimatedVehicleJourney.getEstimatedVehicleJourneyCode();
    Preconditions.checkNotNull(newServiceJourneyRef, "EstimatedVehicleJourneyCode is required");
    // Replaced/duplicated ServiceJourneyId
    // VehicleJourneyRef existingServiceJourneyRef = estimatedVehicleJourney.getVehicleJourneyRef();
    // Preconditions.checkNotNull(existingServiceJourneyRef, "VehicleJourneyRef is required");
    // LineRef of added trip
    Preconditions.checkNotNull(estimatedVehicleJourney.getLineRef(), "LineRef is required");
    String lineRef = estimatedVehicleJourney.getLineRef().getValue();
    // OperatorRef of added trip
    Preconditions.checkNotNull(estimatedVehicleJourney.getOperatorRef(), "OperatorRef is required");
    String operatorRef = estimatedVehicleJourney.getOperatorRef().getValue();
    // Required in SIRI, but currently not in use by OTP
    // Preconditions.checkNotNull(estimatedVehicleJourney.getRouteRef(), "RouteRef is required");
    // String routeRef = estimatedVehicleJourney.getRouteRef().getValue();
    // Preconditions.checkNotNull(estimatedVehicleJourney.getGroupOfLinesRef(), "GroupOfLinesRef is required");
    // String groupOfLines = estimatedVehicleJourney.getGroupOfLinesRef().getValue();
    // Preconditions.checkNotNull(estimatedVehicleJourney.getExternalLineRef(), "ExternalLineRef is required");
    String externalLineRef = estimatedVehicleJourney.getExternalLineRef().getValue();
    // TODO - SIRI: Where is the Operator?
    // Operator operator = graphIndex.operatorForId.get(new FeedScopedId(feedId, operatorRef));
    // Preconditions.checkNotNull(operator, "Operator " + operatorRef + " is unknown");
    FeedScopedId tripId = new FeedScopedId(feedId, newServiceJourneyRef);
    FeedScopedId serviceId = new FeedScopedId(feedId, newServiceJourneyRef);
    Route replacedRoute = null;
    if (externalLineRef != null) {
        replacedRoute = graph.index.getRouteForId(new FeedScopedId(feedId, externalLineRef));
    }
    FeedScopedId routeId = new FeedScopedId(feedId, lineRef);
    Route route = graph.index.getRouteForId(routeId);
    if (route == null) {
        // Route is unknown - create new
        route = new Route();
        route.setId(routeId);
        route.setType(getRouteType(estimatedVehicleJourney.getVehicleModes()));
        // route.setOperator(operator);
        // TODO - SIRI: Is there a better way to find authority/Agency?
        // Finding first Route with same Operator, and using same Authority
        Agency agency = graph.index.getAllRoutes().stream().findFirst().get().getAgency();
        route.setAgency(agency);
        if (estimatedVehicleJourney.getPublishedLineNames() != null && !estimatedVehicleJourney.getPublishedLineNames().isEmpty()) {
            route.setShortName("" + estimatedVehicleJourney.getPublishedLineNames().get(0).getValue());
        }
        LOG.info("Adding route {} to graph.", routeId);
        graph.index.addRoutes(route);
    }
    Trip trip = new Trip();
    trip.setId(tripId);
    trip.setRoute(route);
    // TODO - SIRI: Set transport-submode based on replaced- and replacement-route
    if (replacedRoute != null) {
        if (replacedRoute.getType() >= 100 && replacedRoute.getType() < 200) {
            // Replaced-route is RAIL
            if (route.getType() == 100) {
            // Replacement-route is also RAIL
            // trip.setTransportSubmode(TransmodelTransportSubmode.REPLACEMENT_RAIL_SERVICE);
            } else if (route.getType() == 700) {
            // Replacement-route is BUS
            // trip.setTransportSubmode(TransmodelTransportSubmode.RAIL_REPLACEMENT_BUS);
            }
        }
    }
    trip.setServiceId(serviceId);
    // TODO - SIRI: PublishedLineName not defined in SIRI-profile
    if (estimatedVehicleJourney.getPublishedLineNames() != null && !estimatedVehicleJourney.getPublishedLineNames().isEmpty()) {
        trip.setRouteShortName("" + estimatedVehicleJourney.getPublishedLineNames().get(0).getValue());
    }
    // trip.setTripOperator(operator);
    // TODO - SIRI: Populate these?
    // Replacement-trip has different shape
    trip.setShapeId(null);
    // trip.setTripPrivateCode(null);
    // trip.setTripPublicCode(null);
    trip.setBlockId(null);
    trip.setTripShortName(null);
    trip.setTripHeadsign(null);
    // trip.setKeyValues(null);
    List<Stop> addedStops = new ArrayList<>();
    List<StopTime> aimedStopTimes = new ArrayList<>();
    List<EstimatedCall> estimatedCalls = estimatedVehicleJourney.getEstimatedCalls().getEstimatedCalls();
    for (int i = 0; i < estimatedCalls.size(); i++) {
        EstimatedCall estimatedCall = estimatedCalls.get(i);
        Stop stop = getStopForStopId(feedId, estimatedCall.getStopPointRef().getValue());
        StopTime stopTime = new StopTime();
        stopTime.setStop(stop);
        stopTime.setStopSequence(i);
        stopTime.setTrip(trip);
        ZonedDateTime aimedArrivalTime = estimatedCall.getAimedArrivalTime();
        ZonedDateTime aimedDepartureTime = estimatedCall.getAimedDepartureTime();
        if (aimedArrivalTime != null) {
            stopTime.setArrivalTime(calculateSecondsSinceMidnight(aimedArrivalTime));
        }
        if (aimedDepartureTime != null) {
            stopTime.setDepartureTime(calculateSecondsSinceMidnight(aimedDepartureTime));
        }
        if (estimatedCall.getArrivalBoardingActivity() == ArrivalBoardingActivityEnumeration.ALIGHTING) {
            stopTime.setDropOffType(PICKDROP_SCHEDULED);
        } else {
            stopTime.setDropOffType(PICKDROP_NONE);
        }
        if (estimatedCall.getDepartureBoardingActivity() == DepartureBoardingActivityEnumeration.BOARDING) {
            stopTime.setPickupType(PICKDROP_SCHEDULED);
        } else {
            stopTime.setPickupType(PICKDROP_NONE);
        }
        if (estimatedCall.getDestinationDisplaies() != null && !estimatedCall.getDestinationDisplaies().isEmpty()) {
            NaturalLanguageStringStructure destinationDisplay = estimatedCall.getDestinationDisplaies().get(0);
            stopTime.setStopHeadsign(destinationDisplay.getValue());
        }
        if (i == 0) {
            // Fake arrival on first stop
            stopTime.setArrivalTime(stopTime.getDepartureTime());
        } else if (i == (estimatedCalls.size() - 1)) {
            // Fake departure from last stop
            stopTime.setDepartureTime(stopTime.getArrivalTime());
        }
        addedStops.add(stop);
        aimedStopTimes.add(stopTime);
    }
    StopPattern stopPattern = new StopPattern(aimedStopTimes);
    TripPattern pattern = new TripPattern(trip.getRoute(), stopPattern);
    TripTimes tripTimes = new TripTimes(trip, aimedStopTimes, graph.deduplicator);
    boolean isJourneyPredictionInaccurate = (estimatedVehicleJourney.isPredictionInaccurate() != null && estimatedVehicleJourney.isPredictionInaccurate());
    // If added trip is updated with realtime - loop through and add delays
    for (int i = 0; i < estimatedCalls.size(); i++) {
        EstimatedCall estimatedCall = estimatedCalls.get(i);
        ZonedDateTime expectedArrival = estimatedCall.getExpectedArrivalTime();
        ZonedDateTime expectedDeparture = estimatedCall.getExpectedDepartureTime();
        int aimedArrivalTime = aimedStopTimes.get(i).getArrivalTime();
        int aimedDepartureTime = aimedStopTimes.get(i).getDepartureTime();
        if (expectedArrival != null) {
            int expectedArrivalTime = calculateSecondsSinceMidnight(expectedArrival);
            tripTimes.updateArrivalDelay(i, expectedArrivalTime - aimedArrivalTime);
        }
        if (expectedDeparture != null) {
            int expectedDepartureTime = calculateSecondsSinceMidnight(expectedDeparture);
            tripTimes.updateDepartureDelay(i, expectedDepartureTime - aimedDepartureTime);
        }
        if (estimatedCall.isCancellation() != null) {
            tripTimes.setCancelledStop(i, estimatedCall.isCancellation());
        }
        boolean isCallPredictionInaccurate = estimatedCall.isPredictionInaccurate() != null && estimatedCall.isPredictionInaccurate();
        tripTimes.setPredictionInaccurate(i, (isJourneyPredictionInaccurate | isCallPredictionInaccurate));
        if (i == 0) {
            // Fake arrival on first stop
            tripTimes.updateArrivalTime(i, tripTimes.getDepartureTime(i));
        } else if (i == (estimatedCalls.size() - 1)) {
            // Fake departure from last stop
            tripTimes.updateDepartureTime(i, tripTimes.getArrivalTime(i));
        }
    }
    // Adding trip to index necessary to include values in graphql-queries
    // TODO - SIRI: should more data be added to index?
    graph.index.getTripForId().put(tripId, trip);
    graph.index.getPatternForTrip().put(trip, pattern);
    if (estimatedVehicleJourney.isCancellation() != null && estimatedVehicleJourney.isCancellation()) {
        tripTimes.cancel();
    } else {
        tripTimes.setRealTimeState(RealTimeState.ADDED);
    }
    if (!graph.getServiceCodes().containsKey(serviceId)) {
        graph.getServiceCodes().put(serviceId, graph.getServiceCodes().size());
    }
    tripTimes.serviceCode = graph.getServiceCodes().get(serviceId);
    pattern.add(tripTimes);
    Preconditions.checkState(tripTimes.timesIncreasing(), "Non-increasing triptimes for added trip");
    ServiceDate serviceDate = getServiceDateForEstimatedVehicleJourney(estimatedVehicleJourney);
    if (graph.getCalendarService().getServiceDatesForServiceId(serviceId) == null || graph.getCalendarService().getServiceDatesForServiceId(serviceId).isEmpty()) {
        LOG.info("Adding serviceId {} to CalendarService", serviceId);
    // TODO - SIRI: Need to add the ExtraJourney as a Trip - alerts may be attached to it
    // graph.getCalendarService().addServiceIdAndServiceDates(serviceId, Arrays.asList(serviceDate));
    }
    return addTripToGraphAndBuffer(feedId, graph, trip, aimedStopTimes, addedStops, tripTimes, serviceDate);
}
Also used : NaturalLanguageStringStructure(uk.org.siri.siri20.NaturalLanguageStringStructure) StopPattern(org.opentripplanner.model.StopPattern) Trip(org.opentripplanner.model.Trip) Agency(org.opentripplanner.model.Agency) Stop(org.opentripplanner.model.Stop) ArrayList(java.util.ArrayList) TripPattern(org.opentripplanner.model.TripPattern) ServiceDate(org.opentripplanner.model.calendar.ServiceDate) ZonedDateTime(java.time.ZonedDateTime) FeedScopedId(org.opentripplanner.model.FeedScopedId) TimetableHelper.createUpdatedTripTimes(org.opentripplanner.ext.siri.TimetableHelper.createUpdatedTripTimes) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) EstimatedCall(uk.org.siri.siri20.EstimatedCall) Route(org.opentripplanner.model.Route) StopTime(org.opentripplanner.model.StopTime)

Example 8 with TripPattern

use of org.opentripplanner.model.TripPattern in project OpenTripPlanner by opentripplanner.

the class SiriTimetableSnapshotSource method cancelScheduledTrip.

/**
 * Cancel scheduled trip in buffer given trip id (without agency id) on service date
 *
 * @param tripId trip id without agency id
 * @param serviceDate service date
 * @return true if scheduled trip was cancelled
 */
private boolean cancelScheduledTrip(String feedId, String tripId, final ServiceDate serviceDate) {
    boolean success = false;
    final TripPattern pattern = getPatternForTripId(feedId, tripId);
    if (pattern != null) {
        // Cancel scheduled trip times for this trip in this pattern
        final Timetable timetable = pattern.scheduledTimetable;
        final int tripIndex = timetable.getTripIndex(tripId);
        if (tripIndex == -1) {
            LOG.warn("Could not cancel scheduled trip {}", tripId);
        } else {
            final TripTimes newTripTimes = new TripTimes(timetable.getTripTimes(tripIndex));
            newTripTimes.cancel();
            buffer.update(pattern, newTripTimes, serviceDate);
            success = true;
        }
    }
    return success;
}
Also used : Timetable(org.opentripplanner.model.Timetable) TimetableHelper.createUpdatedTripTimes(org.opentripplanner.ext.siri.TimetableHelper.createUpdatedTripTimes) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) TripPattern(org.opentripplanner.model.TripPattern)

Example 9 with TripPattern

use of org.opentripplanner.model.TripPattern in project OpenTripPlanner by opentripplanner.

the class SiriFuzzyTripMatcher method initCache.

private static void initCache(RoutingService index) {
    if (mappedTripsCache.isEmpty()) {
        Set<Trip> trips = index.getPatternForTrip().keySet();
        for (Trip trip : trips) {
            TripPattern tripPattern = index.getPatternForTrip().get(trip);
            String currentTripId = getUnpaddedTripId(trip.getId().getId());
            if (mappedTripsCache.containsKey(currentTripId)) {
                mappedTripsCache.get(currentTripId).add(trip);
            } else {
                Set<Trip> initialSet = new HashSet<>();
                initialSet.add(trip);
                mappedTripsCache.put(currentTripId, initialSet);
            }
            if (tripPattern != null && (tripPattern.getMode().equals(TraverseMode.RAIL))) {
                // TODO - SIRI: Add support for submode
                if (trip.getTripShortName() != null) {
                    String tripShortName = trip.getTripShortName();
                    if (mappedVehicleRefCache.containsKey(tripShortName)) {
                        mappedVehicleRefCache.get(tripShortName).add(trip);
                    } else {
                        Set<Trip> initialSet = new HashSet<>();
                        initialSet.add(trip);
                        mappedVehicleRefCache.put(tripShortName, initialSet);
                    }
                }
            }
            String lastStopId = tripPattern.getStops().get(tripPattern.getStops().size() - 1).getId().getId();
            TripTimes tripTimes = tripPattern.scheduledTimetable.getTripTimes(trip);
            if (tripTimes != null) {
                int arrivalTime = tripTimes.getArrivalTime(tripTimes.getNumStops() - 1);
                String key = createStartStopKey(lastStopId, arrivalTime);
                if (start_stop_tripCache.containsKey(key)) {
                    start_stop_tripCache.get(key).add(trip);
                } else {
                    Set<Trip> initialSet = new HashSet<>();
                    initialSet.add(trip);
                    start_stop_tripCache.put(key, initialSet);
                }
            }
        }
        Set<Route> routes = index.getPatternsForRoute().keySet();
        for (Route route : routes) {
            String currentRouteId = getUnpaddedTripId(route.getId().getId());
            if (mappedRoutesCache.containsKey(currentRouteId)) {
                mappedRoutesCache.get(currentRouteId).add(route);
            } else {
                Set<Route> initialSet = new HashSet<>();
                initialSet.add(route);
                mappedRoutesCache.put(currentRouteId, initialSet);
            }
        }
        LOG.info("Built route-cache [{}].", mappedRoutesCache.size());
        LOG.info("Built vehicleRef-cache [{}].", mappedVehicleRefCache.size());
        LOG.info("Built trips-cache [{}].", mappedTripsCache.size());
        LOG.info("Built start-stop-cache [{}].", start_stop_tripCache.size());
    }
    if (vehicleJourneyTripCache.isEmpty()) {
        index.getTripForId().values().forEach(trip -> vehicleJourneyTripCache.put(trip.getId().getId(), trip));
    }
}
Also used : Trip(org.opentripplanner.model.Trip) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) TripPattern(org.opentripplanner.model.TripPattern) Route(org.opentripplanner.model.Route) HashSet(java.util.HashSet)

Example 10 with TripPattern

use of org.opentripplanner.model.TripPattern in project OpenTripPlanner by opentripplanner.

the class LegacyGraphQLNodeTypeResolver method getType.

@Override
public GraphQLObjectType getType(TypeResolutionEnvironment environment) {
    Object o = environment.getObject();
    GraphQLSchema schema = environment.getSchema();
    if (o instanceof Agency)
        return schema.getObjectType("Agency");
    if (o instanceof TransitAlert)
        return schema.getObjectType("Alert");
    if (o instanceof BikePark)
        return schema.getObjectType("BikePark");
    if (o instanceof BikeRentalStation)
        return schema.getObjectType("BikeRentalStation");
    // if (o instanceof Cluster) return schema.getObjectType("Cluster");
    if (o instanceof PatternAtStop)
        return schema.getObjectType("DepartureRow");
    if (o instanceof TripPattern)
        return schema.getObjectType("Pattern");
    if (o instanceof PlaceAtDistance)
        return schema.getObjectType("placeAtDistance");
    if (o instanceof Route)
        return schema.getObjectType("Route");
    if (o instanceof Stop)
        return schema.getObjectType("Stop");
    if (o instanceof Station)
        return schema.getObjectType("Stop");
    if (o instanceof TripTimeShort)
        return schema.getObjectType("Stoptime");
    if (o instanceof StopAtDistance)
        return schema.getObjectType("stopAtDistance");
    if (o instanceof FareRuleSet)
        return schema.getObjectType("TicketType");
    if (o instanceof Trip)
        return schema.getObjectType("Trip");
    return null;
}
Also used : TransitAlert(org.opentripplanner.routing.alertpatch.TransitAlert) Trip(org.opentripplanner.model.Trip) Agency(org.opentripplanner.model.Agency) Stop(org.opentripplanner.model.Stop) PatternAtStop(org.opentripplanner.routing.graphfinder.PatternAtStop) PlaceAtDistance(org.opentripplanner.routing.graphfinder.PlaceAtDistance) FareRuleSet(org.opentripplanner.routing.core.FareRuleSet) BikePark(org.opentripplanner.routing.bike_park.BikePark) GraphQLSchema(graphql.schema.GraphQLSchema) BikeRentalStation(org.opentripplanner.routing.bike_rental.BikeRentalStation) TripPattern(org.opentripplanner.model.TripPattern) Station(org.opentripplanner.model.Station) BikeRentalStation(org.opentripplanner.routing.bike_rental.BikeRentalStation) TripTimeShort(org.opentripplanner.model.TripTimeShort) PatternAtStop(org.opentripplanner.routing.graphfinder.PatternAtStop) StopAtDistance(org.opentripplanner.routing.graphfinder.StopAtDistance) Route(org.opentripplanner.model.Route)

Aggregations

TripPattern (org.opentripplanner.model.TripPattern)61 Trip (org.opentripplanner.model.Trip)26 FeedScopedId (org.opentripplanner.model.FeedScopedId)23 Stop (org.opentripplanner.model.Stop)23 ArrayList (java.util.ArrayList)19 TripTimes (org.opentripplanner.routing.trippattern.TripTimes)19 Timetable (org.opentripplanner.model.Timetable)13 ServiceDate (org.opentripplanner.model.calendar.ServiceDate)13 Route (org.opentripplanner.model.Route)12 Test (org.junit.Test)11 HashSet (java.util.HashSet)8 RoutingService (org.opentripplanner.routing.RoutingService)8 List (java.util.List)7 StopPattern (org.opentripplanner.model.StopPattern)7 TimetableSnapshot (org.opentripplanner.model.TimetableSnapshot)7 GET (javax.ws.rs.GET)6 Path (javax.ws.rs.Path)6 StopTime (org.opentripplanner.model.StopTime)5 TripUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate)4 StopTimeUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate)4