Package org.opentripplanner.routing.core

Examples of org.opentripplanner.routing.core.RoutingRequest


            @QueryParam("output")   @DefaultValue("POINTS") String output ) throws Exception {

        this.debugGeoms = new ArrayList();
        this.tooFastTraversedEdgeGeoms = new ArrayList();

        RoutingRequest sptRequestA = buildRequest(0);
        String from = sptRequestA.from.toString();
        int pos = 1;
        float lat = 0;
        float lon = 0;
        for (String s : from.split(",")) {
            if (s.isEmpty()) {
                // no location
                Response.status(Status.BAD_REQUEST).entity("no position").build();
                return null;
            }
            try {
                float num = Float.parseFloat(s);
                if (pos == 1) {
                    lat = num;
                }
                if (pos == 2) {
                    lon = num;
                }
            } catch (Exception e) {
                throw new WebApplicationException(
                        Response.status(Status.BAD_REQUEST)
                                .entity("Could not parse position string to number. Require numerical lat & long coords.")
                                .build());
            }
            pos++;
        }

        GeometryFactory gf = new GeometryFactory();

        Coordinate dropPoint = new Coordinate(lon, lat);

        int walkInMin = (int) Math.floor(walkmins);
        double walkInSec = walkmins * 60;
        LOG.debug("given travel time: " + walkInMin + " mins + " + (walkInSec - (60 * walkInMin))
                + " sec");
        // restrict the evaluated SPT size to 30mins for requests with walking < 30min
        // if larger walking times are requested we adjust the evaluated
        // graph dynamically by 1.3 * min -> this should save processing time
        if (walkInMin < 30) {
            sptRequestA.worstTime = sptRequestA.dateTime + (30 * 60);
        } else {
            sptRequestA.worstTime = sptRequestA.dateTime + Math.round(walkInMin * 1.3 * 60);
        }
        // set the switch-time for shed/area calculation, i.e. to decide if the hull is calculated based on points or on edges
        TraverseModeSet modes = sptRequestA.modes;
        LOG.debug("mode(s): " + modes);
        if ((modes.contains(TraverseMode.TRANSIT)) || (modes.contains(TraverseMode.BUSISH))
                || (modes.contains(TraverseMode.TRAINISH))) {
            shedCalcMethodSwitchTimeInSec = 60 * 20; // 20min (use 20min for transit, since buses may not come all the time)
        } else if (modes.contains(TraverseMode.CAR)) {
            shedCalcMethodSwitchTimeInSec = 60 * 10; // 10min
        } else if (modes.contains(TraverseMode.BICYCLE)) {
            shedCalcMethodSwitchTimeInSec = 60 * 10; // 10min
        } else {
            shedCalcMethodSwitchTimeInSec = 60 * 20; // 20min
        }
        // set the maxUserSpeed, which is used later to check for u-type streets/crescents when calculating sub-edges;
        // Note, that the car speed depends on the edge itself, so this value may be replaced later
        this.usesCar = false;
        int numberOfModes = modes.getModes().size();
        if (numberOfModes == 1) {
            if (modes.getWalk()) {
                this.maxUserSpeed = sptRequestA.walkSpeed;
            } else if (modes.getBicycle()) {
                this.maxUserSpeed = sptRequestA.bikeSpeed;
            } else if (modes.getDriving()) {
                this.maxUserSpeed = sptRequestA.carSpeed;
                this.usesCar = true;
            }
        } else {// for all other cases (multiple-modes)
                // sstein: I thought I may set it to 36.111 m/sec = 130 km/h,
                // but maybe it is better to assume walk speed for transit, i.e. treat it like if the
                // person gets off the bus on the last crossing and walks the "last mile".
            this.maxUserSpeed = sptRequestA.walkSpeed;
        }

        if (doSpeedTest) {
            LOG.debug("performing angle and speed based test to detect u-shapes");
        } else {
            LOG.debug("performing only angle based test to detect u-shapes");
        }

        // TODO: OTP prefers to snap to car-roads/ways, which is not so nice, when walking,
        // and a footpath is closer by. So far there is no option to switch that off

        // create the ShortestPathTree
        try {
            sptRequestA.setRoutingContext(graphService.getGraph());
        } catch (Exception e) {
            // if we get an exception here, and in particular a VertexNotFoundException,
            // then it is likely that we chose a (transit) mode without having that (transit) modes data
            LOG.debug("cannot set RoutingContext: " + e.toString());
            LOG.debug("cannot set RoutingContext: setting mode=WALK");
            sptRequestA.setMode(TraverseMode.WALK); // fall back to walk mode
            sptRequestA.setRoutingContext(graphService.getGraph());
        }
        ShortestPathTree sptA = sptService.getShortestPathTree(sptRequestA);
        StreetLocation origin = (StreetLocation) sptRequestA.rctx.fromVertex;
        sptRequestA.cleanup(); // remove inserted points

        // create a LineString for display
        Coordinate pathToStreetCoords[] = new Coordinate[2];
        pathToStreetCoords[0] = dropPoint;
        pathToStreetCoords[1] = origin.getCoordinate();
View Full Code Here


        // TODO: this seems to only check the endpoints, which are usually auto-generated
        //if ( ! options.isAccessible())
        //    throw new LocationNotAccessible();
       
        // Copy options to keep originals
        RoutingRequest originalOptions = options.clone();

        /* try to plan the trip */
        List<GraphPath> paths = null;
        boolean tooSloped = false;
        try {
View Full Code Here

        this.params = params;
       
        // Core OTP modules
        graphService = gs;
        routingRequest = new RoutingRequest();
        sptServiceFactory = new GenericAStarFactory();

        // Choose a PathService to wrap the SPTService, depending on expected maximum path lengths
        if (params.longDistance) {
            LongDistancePathService pathService = new LongDistancePathService(graphService, sptServiceFactory);
View Full Code Here

     * @param  n allows building several request objects from the same query parameters,
     *         re-specifying only those parameters that change from one request to the next.
     * @throws ParameterException when there is a problem interpreting a query parameter
     */
    protected RoutingRequest buildRequest(int n) throws ParameterException {
        RoutingRequest request = otpServer.routingRequest.clone();
        request.setFromString(get(fromPlace, n, request.getFromPlace().getRepresentation()));
        request.setToString(get(toPlace, n, request.getToPlace().getRepresentation()));
        request.routerId = routerId;
        {
            //FIXME: get defaults for these from request
            String d = get(date, n, null);
            String t = get(time, n, null);
            TimeZone tz;
            if (otpServer.graphService != null) { // in tests graphService can be null
                tz = otpServer.graphService.getGraph(request.routerId).getTimeZone();
            } else {
                LOG.warn("No graph service available, using default time zone.");
                tz = TimeZone.getDefault();
                LOG.info("Time zone set to {}", tz);
            }
            if (d == null && t != null) { // Time was provided but not date
                LOG.debug("parsing ISO datetime {}", t);
                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(t);
                    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(d, t, tz);
                }
            } else {
                request.setDateTime(d, t, tz);
            }
        }
        request.setWheelchairAccessible(get(wheelchair, n, request.wheelchairAccessible));
        request.setNumItineraries(get(numItineraries, n, request.getNumItineraries()));
        request.setMaxWalkDistance(get(maxWalkDistance, n, request.getMaxWalkDistance()));
        request.setMaxPreTransitTime(get(maxPreTransitTime, n, request.maxPreTransitTime));
        request.setWalkReluctance(get(walkReluctance, n, request.walkReluctance));
        request.setWaitReluctance(get(waitReluctance, n, request.waitReluctance));
        request.setWaitAtBeginningFactor(get(waitAtBeginningFactor, n, request.waitAtBeginningFactor));
        request.walkSpeed = get(walkSpeed, n, request.walkSpeed);
        double bikeSpeedParam = get(bikeSpeed, n, request.bikeSpeed);
        request.bikeSpeed = bikeSpeedParam;
        int bikeSwitchTimeParam = get(bikeSwitchTime, n, request.bikeSwitchTime);
        request.bikeSwitchTime = bikeSwitchTimeParam;
        int bikeSwitchCostParam = get(bikeSwitchCost, n, request.bikeSwitchCost);
        request.bikeSwitchCost = bikeSwitchCostParam;
        OptimizeType opt = get(optimize, n, request.optimize);
        {
            Double tsafe =  get(triangleSafetyFactor, n, null);
            Double tslope = get(triangleSlopeFactor,  n, null);
            Double ttime =  get(triangleTimeFactor,   n, null);
            if (tsafe != null || tslope != null || ttime != null ) {
                if (tsafe == null || tslope == null || ttime == null) {
                    throw new ParameterException(Message.UNDERSPECIFIED_TRIANGLE);
                }
                if (opt == null) {
                    opt = OptimizeType.TRIANGLE;
                } else if (opt != OptimizeType.TRIANGLE) {
                    throw new ParameterException(Message.TRIANGLE_OPTIMIZE_TYPE_NOT_SET);
                }
                if (Math.abs(tsafe + tslope + ttime - 1) > Math.ulp(1) * 3) {
                    throw new ParameterException(Message.TRIANGLE_NOT_AFFINE);
                }
                request.setTriangleSafetyFactor(tsafe);
                request.setTriangleSlopeFactor(tslope);
                request.setTriangleTimeFactor(ttime);
            } else if (opt == OptimizeType.TRIANGLE) {
                throw new ParameterException(Message.TRIANGLE_VALUES_NOT_SET);
            }
        }
        request.setArriveBy(get(arriveBy, n, false));
        request.showIntermediateStops = get(showIntermediateStops, n, request.showIntermediateStops);
        /* intermediate places and their ordering are shared because they are themselves a list */
        if (intermediatePlaces != null && intermediatePlaces.size() > 0
            && ! intermediatePlaces.get(0).equals("")) {
            request.setIntermediatePlacesFromStrings(intermediatePlaces);
        }
        if (intermediatePlacesOrdered == null)
            intermediatePlacesOrdered = request.intermediatePlacesOrdered;
        request.intermediatePlacesOrdered = intermediatePlacesOrdered;
        request.setPreferredRoutes(get(preferredRoutes, n, request.getPreferredRouteStr()));
        request.setOtherThanPreferredRoutesPenalty(get(otherThanPreferredRoutesPenalty, n, request.otherThanPreferredRoutesPenalty));
        request.setPreferredAgencies(get(preferredAgencies, n, request.getPreferredAgenciesStr()));
        request.setUnpreferredRoutes(get(unpreferredRoutes, n, request.getUnpreferredRouteStr()));
        request.setUnpreferredAgencies(get(unpreferredAgencies, n, request.getUnpreferredAgenciesStr()));
        request.setWalkBoardCost(get(walkBoardCost, n, request.walkBoardCost));
        request.setBikeBoardCost(get(bikeBoardCost, n, request.bikeBoardCost));
        request.setBannedRoutes(get(bannedRoutes, n, request.getBannedRouteStr()));
        request.setBannedAgencies(get(bannedAgencies, n, request.getBannedAgenciesStr()));
        HashMap<AgencyAndId, BannedStopSet> bannedTripMap = makeBannedTripMap(get(bannedTrips, n, null));
        if (bannedTripMap != null) {
            request.bannedTrips = bannedTripMap;
        }
        request.setBannedStops(get(bannedStops, n, request.getBannedStopsStr()));
        request.setBannedStopsHard(get(bannedStopsHard, n, request.getBannedStopsHardStr()));
       
        // "Least transfers" optimization is accomplished via an increased transfer penalty.
        // See comment on RoutingRequest.transferPentalty.
        if (opt == OptimizeType.TRANSFERS) {
            opt = OptimizeType.QUICK;
            request.transferPenalty = get(transferPenalty, n, 0) + 1800;
        } else {
            request.transferPenalty = (get(transferPenalty, n, request.transferPenalty));
        }
        request.batch = (get(batch, n, new Boolean(request.batch)));
        request.setOptimize(opt);
        /* Temporary code to get bike/car parking and renting working. */
        modes.get(0).applyToRequest(request);

        if (request.allowBikeRental && bikeSpeedParam == -1) {
            //slower bike speed for bike sharing, based on empirical evidence from DC.
            request.bikeSpeed = 4.3;
        }

        request.boardSlack = (get(boardSlack, n, request.boardSlack));
        request.alightSlack = (get(alightSlack, n, request.alightSlack));
        request.transferSlack = (get(minTransferTime, n, request.transferSlack));
        request.nonpreferredTransferPenalty = get(nonpreferredTransferPenalty, n, request.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");
        }

        request.setMaxTransfers(get(maxTransfers, n, request.maxTransfers));
        final long NOW_THRESHOLD_MILLIS = 15 * 60 * 60 * 1000;
        boolean tripPlannedForNow = Math.abs(request.getDateTime().getTime() - new Date().getTime())
                < NOW_THRESHOLD_MILLIS;
        request.useBikeRentalAvailabilityInformation = (tripPlannedForNow);
        if (request.intermediatePlaces != null
                && (request.modes.isTransit() ||
                        (request.modes.getWalk() &&
View Full Code Here

    @DefaultValue("90") int cutoffMinutes,
    @QueryParam("routerId") String routerId) {

        // Build the request
        try {
            RoutingRequest req = buildRequest(0); // batch must be true
          
            Graph graph;
           
            // routerId is optional -- select default graph if not set
          if(routerId == null || routerId.isEmpty()) {
            graph = server.graphService.getGraph();
          }
          else
            graph = server.graphService.getGraph(routerId);
           
          req.setRoutingContext(graph);
         
            EarliestArrivalSPTService sptService = new EarliestArrivalSPTService();
            sptService.maxDuration = (60 * cutoffMinutes);
            ShortestPathTree spt = sptService.getShortestPathTree(req);
            req.cleanup();
            if (spt != null) {
                TimeSurface surface = new TimeSurface(spt);
                surface.params = Maps.newHashMap();
                for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
                    // include only the first instance of each query parameter
View Full Code Here

         *       out so it's used here too...
         */
       
        // create response object, containing a copy of all request parameters
        Response response = new Response(uriInfo);
        RoutingRequest request = null;
        try {
            // fill in request from query parameters via shared superclass method
            request = super.buildRequest();
            TripPlan plan = otpServer.planGenerator.generate(request);
            response.setPlan(plan);
        } catch (Exception e) {
            PlannerError error = new PlannerError(e);
            if(!PlannerError.isPlanningError(e.getClass()))
                LOG.warn("Error while planning path: ", e);
            response.setError(error);
        } finally {
            if (request != null) {
                response.debugOutput = request.rctx.debugOutput;
                request.cleanup(); // TODO verify that this is being done on Analyst web services
            }      
        }
        return response;
    }
View Full Code Here

        isoChroneRequest.includeDebugGeometry = debug;
        isoChroneRequest.precisionMeters = precisionMeters;
        if (coordinateOrigin != null)
            isoChroneRequest.coordinateOrigin = new GenericLocation(null, coordinateOrigin)
                    .getCoordinate();
        RoutingRequest sptRequest = buildRequest(0);

        if (maxTimeSec != null) {
            isoChroneRequest.maxTimeSec = maxTimeSec;
        } else {
            isoChroneRequest.maxTimeSec = isoChroneRequest.maxCutoffSec;
View Full Code Here

    public String getName() {
        return "street transit link";
    }

    public State traverse(State s0) {
        RoutingRequest req = s0.getOptions();
        if (s0.getOptions().wheelchairAccessible && !wheelchairAccessible) {
            return null;
        }
        if (s0.getOptions().bikeParkAndRide && !s0.isBikeParked()) {
            // Forbid taking your own bike in the station if bike P+R activated.
View Full Code Here

    public String getName() {
        return GtfsLibrary.getRouteName(getPattern().route);
    }
   
    public State optimisticTraverse(State state0) {
        RoutingRequest options = state0.getOptions();
       
        // Ignore this edge if either of its stop is banned hard
        if (!options.bannedStopsHard.isEmpty()) {
            if (options.bannedStopsHard.matches(((PatternStopVertex) fromv).getStop())
                    || options.bannedStopsHard.matches(((PatternStopVertex) tov).getStop())) {
View Full Code Here

    public double weightLowerBound(RoutingRequest options) {
        return timeLowerBound(options);
    }
   
    public State traverse(State s0) {
        RoutingRequest options = s0.getOptions();
       
        // Ignore this edge if either of its stop is banned hard
        if (!options.bannedStopsHard.isEmpty()) {
            if (options.bannedStopsHard.matches(((PatternStopVertex) fromv).getStop())
                    || options.bannedStopsHard.matches(((PatternStopVertex) tov).getStop())) {
View Full Code Here

TOP

Related Classes of org.opentripplanner.routing.core.RoutingRequest

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.