Search in sources :

Example 1 with BannedStopSet

use of org.opentripplanner.routing.request.BannedStopSet in project OpenTripPlanner by opentripplanner.

the class RoutingResource method makeBannedTripMap.

/**
 * Take a string in the format agency:id or agency:id:1:2:3:4.
 * TODO Improve Javadoc. What does this even mean? Why are there so many colons and numbers?
 * Convert to a Map from trip --> set of int.
 */
private HashMap<AgencyAndId, BannedStopSet> makeBannedTripMap(String banned) {
    if (banned == null) {
        return null;
    }
    HashMap<AgencyAndId, BannedStopSet> bannedTripMap = new HashMap<AgencyAndId, BannedStopSet>();
    String[] tripStrings = banned.split(",");
    for (String tripString : tripStrings) {
        // TODO this apparently allows banning stops within a trip with integers. Why?
        String[] parts = tripString.split(":");
        // throw exception?
        if (parts.length < 2)
            continue;
        String agencyIdString = parts[0];
        String tripIdString = parts[1];
        AgencyAndId tripId = new AgencyAndId(agencyIdString, tripIdString);
        BannedStopSet bannedStops;
        if (parts.length == 2) {
            bannedStops = BannedStopSet.ALL;
        } else {
            bannedStops = new BannedStopSet();
            for (int i = 2; i < parts.length; ++i) {
                bannedStops.add(Integer.parseInt(parts[i]));
            }
        }
        bannedTripMap.put(tripId, bannedStops);
    }
    return bannedTripMap;
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) BannedStopSet(org.opentripplanner.routing.request.BannedStopSet)

Example 2 with BannedStopSet

use of org.opentripplanner.routing.request.BannedStopSet in project OpenTripPlanner by opentripplanner.

the class RoutingResource method buildRequest.

/**
 * Range/sanity check the query parameter fields and build a Request object from them.
 *
 * @throws ParameterException when there is a problem interpreting a query parameter
 */
protected RoutingRequest buildRequest() throws ParameterException {
    Router router = otpServer.getRouter(routerId);
    RoutingRequest request = router.defaultRoutingRequest.clone();
    request.routerId = routerId;
    // router configuration and cloned. We check whether each parameter was supplied before overwriting the default.
    if (fromPlace != null)
        request.setFromString(fromPlace);
    if (toPlace != null)
        request.setToString(toPlace);
    {
        // FIXME: move into setter method on routing request
        TimeZone tz;
        tz = router.graph.getTimeZone();
        if (date == null && time != null) {
            // Time was provided but not date
            LOG.debug("parsing ISO datetime {}", time);
            try {
                // If the time query param doesn't specify a timezone, use the graph's default. See issue #1373.
                DatatypeFactory df = javax.xml.datatype.DatatypeFactory.newInstance();
                XMLGregorianCalendar xmlGregCal = df.newXMLGregorianCalendar(time);
                GregorianCalendar gregCal = xmlGregCal.toGregorianCalendar();
                if (xmlGregCal.getTimezone() == DatatypeConstants.FIELD_UNDEFINED) {
                    gregCal.setTimeZone(tz);
                }
                Date d2 = gregCal.getTime();
                request.setDateTime(d2);
            } catch (DatatypeConfigurationException e) {
                request.setDateTime(date, time, tz);
            }
        } else {
            request.setDateTime(date, time, tz);
        }
    }
    if (wheelchair != null)
        request.setWheelchairAccessible(wheelchair);
    if (numItineraries != null)
        request.setNumItineraries(numItineraries);
    if (maxWalkDistance != null) {
        request.setMaxWalkDistance(maxWalkDistance);
        request.maxTransferWalkDistance = maxWalkDistance;
    }
    if (maxPreTransitTime != null)
        request.setMaxPreTransitTime(maxPreTransitTime);
    if (walkReluctance != null)
        request.setWalkReluctance(walkReluctance);
    if (waitReluctance != null)
        request.setWaitReluctance(waitReluctance);
    if (waitAtBeginningFactor != null)
        request.setWaitAtBeginningFactor(waitAtBeginningFactor);
    if (walkSpeed != null)
        request.walkSpeed = walkSpeed;
    if (bikeSpeed != null)
        request.bikeSpeed = bikeSpeed;
    if (bikeSwitchTime != null)
        request.bikeSwitchTime = bikeSwitchTime;
    if (bikeSwitchCost != null)
        request.bikeSwitchCost = bikeSwitchCost;
    if (optimize != null) {
        // Optimize types are basically combined presets of routing parameters, except for triangle
        request.setOptimize(optimize);
        if (optimize == OptimizeType.TRIANGLE) {
            if (triangleSafetyFactor == null || triangleSlopeFactor == null || triangleTimeFactor == null) {
                throw new ParameterException(Message.UNDERSPECIFIED_TRIANGLE);
            }
            if (triangleSafetyFactor == null && triangleSlopeFactor == null && triangleTimeFactor == null) {
                throw new ParameterException(Message.TRIANGLE_VALUES_NOT_SET);
            }
            // FIXME couldn't this be simplified by only specifying TWO of the values?
            if (Math.abs(triangleSafetyFactor + triangleSlopeFactor + triangleTimeFactor - 1) > Math.ulp(1) * 3) {
                throw new ParameterException(Message.TRIANGLE_NOT_AFFINE);
            }
            request.setTriangleSafetyFactor(triangleSafetyFactor);
            request.setTriangleSlopeFactor(triangleSlopeFactor);
            request.setTriangleTimeFactor(triangleTimeFactor);
        }
    }
    if (arriveBy != null)
        request.setArriveBy(arriveBy);
    if (showIntermediateStops != null)
        request.showIntermediateStops = showIntermediateStops;
    if (intermediatePlaces != null)
        request.setIntermediatePlacesFromStrings(intermediatePlaces);
    if (preferredRoutes != null)
        request.setPreferredRoutes(preferredRoutes);
    if (otherThanPreferredRoutesPenalty != null)
        request.setOtherThanPreferredRoutesPenalty(otherThanPreferredRoutesPenalty);
    if (preferredAgencies != null)
        request.setPreferredAgencies(preferredAgencies);
    if (unpreferredRoutes != null)
        request.setUnpreferredRoutes(unpreferredRoutes);
    if (unpreferredAgencies != null)
        request.setUnpreferredAgencies(unpreferredAgencies);
    if (walkBoardCost != null)
        request.setWalkBoardCost(walkBoardCost);
    if (bikeBoardCost != null)
        request.setBikeBoardCost(bikeBoardCost);
    if (bannedRoutes != null)
        request.setBannedRoutes(bannedRoutes);
    if (bannedAgencies != null)
        request.setBannedAgencies(bannedAgencies);
    HashMap<AgencyAndId, BannedStopSet> bannedTripMap = makeBannedTripMap(bannedTrips);
    if (bannedTripMap != null)
        request.bannedTrips = bannedTripMap;
    if (bannedStops != null)
        request.setBannedStops(bannedStops);
    if (bannedStopsHard != null)
        request.setBannedStopsHard(bannedStopsHard);
    // See comment on RoutingRequest.transferPentalty.
    if (transferPenalty != null)
        request.transferPenalty = transferPenalty;
    if (optimize == OptimizeType.TRANSFERS) {
        optimize = OptimizeType.QUICK;
        request.transferPenalty += 1800;
    }
    if (batch != null)
        request.batch = batch;
    if (optimize != null)
        request.setOptimize(optimize);
    /* Temporary code to get bike/car parking and renting working. */
    if (modes != null) {
        modes.applyToRoutingRequest(request);
        request.setModes(request.modes);
    }
    if (request.allowBikeRental && bikeSpeed == null) {
        // slower bike speed for bike sharing, based on empirical evidence from DC.
        request.bikeSpeed = 4.3;
    }
    if (boardSlack != null)
        request.boardSlack = boardSlack;
    if (alightSlack != null)
        request.alightSlack = alightSlack;
    if (minTransferTime != null)
        // TODO rename field in routingrequest
        request.transferSlack = minTransferTime;
    if (nonpreferredTransferPenalty != null)
        request.nonpreferredTransferPenalty = nonpreferredTransferPenalty;
    if (request.boardSlack + request.alightSlack > request.transferSlack) {
        throw new RuntimeException("Invalid parameters: " + "transfer slack must be greater than or equal to board slack plus alight slack");
    }
    if (maxTransfers != null)
        request.maxTransfers = maxTransfers;
    final long NOW_THRESHOLD_MILLIS = 15 * 60 * 60 * 1000;
    boolean tripPlannedForNow = Math.abs(request.getDateTime().getTime() - new Date().getTime()) < NOW_THRESHOLD_MILLIS;
    // TODO the same thing for GTFS-RT
    request.useBikeRentalAvailabilityInformation = (tripPlannedForNow);
    if (startTransitStopId != null && !startTransitStopId.isEmpty())
        request.startingTransitStopId = AgencyAndId.convertFromString(startTransitStopId);
    if (startTransitTripId != null && !startTransitTripId.isEmpty())
        request.startingTransitTripId = AgencyAndId.convertFromString(startTransitTripId);
    if (clampInitialWait != null)
        request.clampInitialWait = clampInitialWait;
    if (reverseOptimizeOnTheFly != null)
        request.reverseOptimizeOnTheFly = reverseOptimizeOnTheFly;
    if (ignoreRealtimeUpdates != null)
        request.ignoreRealtimeUpdates = ignoreRealtimeUpdates;
    if (disableRemainingWeightHeuristic != null)
        request.disableRemainingWeightHeuristic = disableRemainingWeightHeuristic;
    if (maxHours != null)
        request.maxHours = maxHours;
    if (useRequestedDateTimeInMaxHours != null)
        request.useRequestedDateTimeInMaxHours = useRequestedDateTimeInMaxHours;
    if (disableAlertFiltering != null)
        request.disableAlertFiltering = disableAlertFiltering;
    if (geoidElevation != null)
        request.geoidElevation = geoidElevation;
    // getLocale function returns defaultLocale if locale is null
    request.locale = ResourceBundleSingleton.INSTANCE.getLocale(locale);
    return request;
}
Also used : DatatypeFactory(javax.xml.datatype.DatatypeFactory) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) BannedStopSet(org.opentripplanner.routing.request.BannedStopSet) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) Router(org.opentripplanner.standalone.Router) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) DatatypeConfigurationException(javax.xml.datatype.DatatypeConfigurationException) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest)

Example 3 with BannedStopSet

use of org.opentripplanner.routing.request.BannedStopSet in project OpenTripPlanner by opentripplanner.

the class TripTimes method tripAcceptable.

/**
 * Once a trip has been found departing or arriving at an appropriate time, check whether that
 * trip fits other restrictive search criteria such as bicycle and wheelchair accessibility
 * and transfers with minimum time or forbidden transfers.
 */
public boolean tripAcceptable(final State state0, final int stopIndex) {
    final RoutingRequest options = state0.getOptions();
    final BannedStopSet banned = options.bannedTrips.get(trip.getId());
    if (banned != null && banned.contains(stopIndex)) {
        return false;
    }
    if (options.wheelchairAccessible && trip.getWheelchairAccessible() != 1) {
        return false;
    }
    // Establish whether we have a rented _or_ owned bicycle.
    final boolean bicycle = state0.getNonTransitMode() == TraverseMode.BICYCLE;
    if (bicycle && BikeAccess.fromTrip(trip) != BikeAccess.ALLOWED) {
        return false;
    }
    return true;
}
Also used : BannedStopSet(org.opentripplanner.routing.request.BannedStopSet) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest)

Example 4 with BannedStopSet

use of org.opentripplanner.routing.request.BannedStopSet in project OpenTripPlanner by opentripplanner.

the class TestBanning method doTestBannedTrips.

/**
 * Test trip banning. We compute a set of shortest routes between two random stops in the Portland graph. We then ban, for each route, up to a
 * certain amount of trips used in this route, one by one, and recompute the path. The banned trips must not appear in the new computed route.
 *
 * This is using a seeded random generator to easily make a reproducible and arbitrary list
 * of start/end points and trip to ban. It allow for a (bit) more coverage than doing a
 * single hand-picked test only.
 *
 * @param partial True to test partial trip banning, false for complete trip
 * @param seed Value to use for random generator seed -- Keep the same value for consistency.
 */
public void doTestBannedTrips(boolean partial, int seed) {
    Graph graph = ConstantsForTests.getInstance().getPortlandGraph();
    String feedId = graph.getFeedIds().iterator().next();
    Random rand = new Random(seed);
    for (int i = 0; i < 20; i++) {
        RoutingRequest options = new RoutingRequest();
        options.dateTime = TestUtils.dateInSeconds("America/Los_Angeles", 2009, 11, 1, 12, 34, 25);
        // Pick two random locations
        Vertex start = null;
        Vertex end = null;
        while (start == null) start = graph.getVertex(feedId + ":" + rand.nextInt(10000));
        while (end == null) end = graph.getVertex(feedId + ":" + rand.nextInt(10000));
        options.setRoutingContext(graph, start, end);
        ShortestPathTree spt = null;
        int n = rand.nextInt(5) + 3;
        for (int j = 0; j < n; j++) {
            spt = aStar.getShortestPathTree(options);
            GraphPath path = spt.getPath(end, true);
            if (path == null || spt == null)
                // No path found
                break;
            // List of used [trip,stop index] in the path
            Set<T2<AgencyAndId, BannedStopSet>> usedTripDefs = new HashSet<T2<AgencyAndId, BannedStopSet>>();
            for (State s : path.states) {
                if (s.getBackEdge() instanceof TransitBoardAlight) {
                    TransitBoardAlight tbae = (TransitBoardAlight) s.getBackEdge();
                    int boardingStopIndex = tbae.getStopIndex();
                    AgencyAndId tripId = s.getTripId();
                    BannedStopSet stopSet;
                    if (partial) {
                        stopSet = new BannedStopSet();
                        stopSet.add(boardingStopIndex);
                    } else {
                        stopSet = BannedStopSet.ALL;
                    }
                    if (tripId != null)
                        usedTripDefs.add(new T2<AgencyAndId, BannedStopSet>(tripId, stopSet));
                }
            }
            // Used trips should not contains a banned trip
            for (T2<AgencyAndId, BannedStopSet> usedTripDef : usedTripDefs) {
                BannedStopSet bannedStopSet = options.bannedTrips.get(usedTripDef.first);
                if (bannedStopSet != null) {
                    for (Integer stopIndex : usedTripDef.second) {
                        assertFalse(bannedStopSet.contains(stopIndex));
                    }
                }
            }
            if (usedTripDefs.size() == 0)
                // Not a transit trip, no sense to ban trip any longer
                break;
            // Pick a random used trip + stop set to ban
            List<T2<AgencyAndId, BannedStopSet>> usedTripDefsList = new ArrayList<T2<AgencyAndId, BannedStopSet>>(usedTripDefs);
            T2<AgencyAndId, BannedStopSet> tripDefToBan = usedTripDefsList.get(rand.nextInt(usedTripDefs.size()));
            options.bannedTrips.put(tripDefToBan.first, tripDefToBan.second);
        }
        options.bannedTrips.clear();
    }
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) BannedStopSet(org.opentripplanner.routing.request.BannedStopSet) TransitBoardAlight(org.opentripplanner.routing.edgetype.TransitBoardAlight) GraphPath(org.opentripplanner.routing.spt.GraphPath) Graph(org.opentripplanner.routing.graph.Graph) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) State(org.opentripplanner.routing.core.State) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) T2(org.opentripplanner.common.model.T2)

Aggregations

BannedStopSet (org.opentripplanner.routing.request.BannedStopSet)4 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)3 RoutingRequest (org.opentripplanner.routing.core.RoutingRequest)3 DatatypeConfigurationException (javax.xml.datatype.DatatypeConfigurationException)1 DatatypeFactory (javax.xml.datatype.DatatypeFactory)1 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)1 T2 (org.opentripplanner.common.model.T2)1 State (org.opentripplanner.routing.core.State)1 TransitBoardAlight (org.opentripplanner.routing.edgetype.TransitBoardAlight)1 Graph (org.opentripplanner.routing.graph.Graph)1 Vertex (org.opentripplanner.routing.graph.Vertex)1 GraphPath (org.opentripplanner.routing.spt.GraphPath)1 ShortestPathTree (org.opentripplanner.routing.spt.ShortestPathTree)1 Router (org.opentripplanner.standalone.Router)1