Search in sources :

Example 1 with GraphPathFinder

use of org.opentripplanner.routing.impl.GraphPathFinder in project OpenTripPlanner by opentripplanner.

the class PlannerResource method plan.

// We inject info about the incoming request so we can include the incoming query
// parameters in the outgoing response. This is a TriMet requirement.
// Jersey uses @Context to inject internal types and @InjectParam or @Resource for DI objects.
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML + Q, MediaType.TEXT_XML + Q })
public Response plan(@Context UriInfo uriInfo, @Context Request grizzlyRequest) {
    /*
         * TODO: add Lang / Locale parameter, and thus get localized content (Messages & more...)
         * TODO: from/to inputs should be converted / geocoded / etc... here, and maybe send coords 
         *       or vertex ids to planner (or error back to user)
         * TODO: org.opentripplanner.routing.module.PathServiceImpl has COOORD parsing. Abstract that
         *       out so it's used here too...
         */
    // Create response object, containing a copy of all request parameters. Maybe they should be in the debug section of the response.
    Response response = new Response(uriInfo);
    RoutingRequest request = null;
    Router router = null;
    List<GraphPath> paths = null;
    try {
        /* Fill in request fields from query parameters via shared superclass method, catching any errors. */
        request = super.buildRequest();
        router = otpServer.getRouter(request.routerId);
        /* Find some good GraphPaths through the OTP Graph. */
        // we could also get a persistent router-scoped GraphPathFinder but there's no setup cost here
        GraphPathFinder gpFinder = new GraphPathFinder(router);
        paths = gpFinder.graphPathFinderEntryPoint(request);
        /* Convert the internal GraphPaths to a TripPlan object that is included in an OTP web service Response. */
        TripPlan plan = GraphPathToTripPlanConverter.generatePlan(paths, 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) {
            if (request.rctx != null) {
                response.debugOutput = request.rctx.debugOutput;
            }
            // TODO verify that this cleanup step is being done on Analyst web services
            request.cleanup();
        }
    }
    /* Populate up the elevation metadata */
    response.elevationMetadata = new ElevationMetadata();
    response.elevationMetadata.ellipsoidToGeoidDifference = router.graph.ellipsoidToGeoidDifference;
    response.elevationMetadata.geoidElevation = request.geoidElevation;
    /* Log this request if such logging is enabled. */
    if (request != null && router != null && router.requestLogger != null) {
        StringBuilder sb = new StringBuilder();
        String clientIpAddress = grizzlyRequest.getRemoteAddr();
        // sb.append(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        sb.append(clientIpAddress);
        sb.append(' ');
        sb.append(request.arriveBy ? "ARRIVE" : "DEPART");
        sb.append(' ');
        sb.append(LocalDateTime.ofInstant(Instant.ofEpochSecond(request.dateTime), ZoneId.systemDefault()));
        sb.append(' ');
        sb.append(request.modes.getAsStr());
        sb.append(' ');
        sb.append(request.from.lat);
        sb.append(' ');
        sb.append(request.from.lng);
        sb.append(' ');
        sb.append(request.to.lat);
        sb.append(' ');
        sb.append(request.to.lng);
        sb.append(' ');
        if (paths != null) {
            for (GraphPath path : paths) {
                sb.append(path.getDuration());
                sb.append(' ');
                sb.append(path.getTrips().size());
                sb.append(' ');
            }
        }
        router.requestLogger.info(sb.toString());
    }
    return response;
}
Also used : GraphPath(org.opentripplanner.routing.spt.GraphPath) TripPlan(org.opentripplanner.api.model.TripPlan) Router(org.opentripplanner.standalone.Router) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) GraphPathFinder(org.opentripplanner.routing.impl.GraphPathFinder) PlannerError(org.opentripplanner.api.model.error.PlannerError) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 2 with GraphPathFinder

use of org.opentripplanner.routing.impl.GraphPathFinder in project OpenTripPlanner by opentripplanner.

the class TestIntermediatePlaces method setUp.

@BeforeClass
public static void setUp() {
    try {
        Graph graph = FakeGraph.buildGraphNoTransit();
        FakeGraph.addPerpendicularRoutes(graph);
        FakeGraph.link(graph);
        graph.index(new DefaultStreetVertexIndexFactory());
        OTPServer otpServer = new OTPServer(new CommandLineParameters(), new GraphService());
        otpServer.getGraphService().registerGraph("A", new MemoryGraphSource("A", graph));
        Router router = otpServer.getGraphService().getRouter("A");
        TestIntermediatePlaces.graphPathFinder = new GraphPathFinder(router);
        timeZone = graph.getTimeZone();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        assert false : "Could not build graph: " + e.getMessage();
    } catch (Exception e) {
        e.printStackTrace();
        assert false : "Could not add transit data: " + e.getMessage();
    }
}
Also used : GraphService(org.opentripplanner.routing.services.GraphService) CommandLineParameters(org.opentripplanner.standalone.CommandLineParameters) FakeGraph(org.opentripplanner.graph_builder.module.FakeGraph) Graph(org.opentripplanner.routing.graph.Graph) OTPServer(org.opentripplanner.standalone.OTPServer) MemoryGraphSource(org.opentripplanner.routing.impl.MemoryGraphSource) Router(org.opentripplanner.standalone.Router) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DefaultStreetVertexIndexFactory(org.opentripplanner.routing.impl.DefaultStreetVertexIndexFactory) GraphPathFinder(org.opentripplanner.routing.impl.GraphPathFinder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BeforeClass(org.junit.BeforeClass)

Example 3 with GraphPathFinder

use of org.opentripplanner.routing.impl.GraphPathFinder in project OpenTripPlanner by opentripplanner.

the class TestOpenStreetMapGraphBuilder method testBuildingAreas.

/**
 * This reads test file with area
 * and tests if it can be routed if visibility is used and if it isn't
 *
 * Routing needs to be successful in both options since without visibility calculation
 * area rings are used.
 * @param skipVisibility if true visibility calculations are skipped
 * @throws UnsupportedEncodingException
 */
private void testBuildingAreas(boolean skipVisibility) throws UnsupportedEncodingException {
    Graph gg = new Graph();
    OpenStreetMapModule loader = new OpenStreetMapModule();
    loader.skipVisibility = skipVisibility;
    loader.setDefaultWayPropertySetSource(new DefaultWayPropertySetSource());
    FileBasedOpenStreetMapProviderImpl provider = new FileBasedOpenStreetMapProviderImpl();
    File file = new File(URLDecoder.decode(getClass().getResource("usf_area.osm.gz").getFile(), "UTF-8"));
    provider.setPath(file);
    loader.setProvider(provider);
    loader.buildGraph(gg, extra);
    new StreetVertexIndexServiceImpl(gg);
    OTPServer otpServer = new OTPServer(new CommandLineParameters(), new GraphService());
    otpServer.getGraphService().registerGraph("A", new MemoryGraphSource("A", gg));
    Router a = otpServer.getGraphService().getRouter("A");
    RoutingRequest request = new RoutingRequest("WALK");
    // This are vertices that can be connected only over edges on area (with correct permissions)
    // It tests if it is possible to route over area without visibility calculations
    Vertex bottomV = gg.getVertex("osm:node:580290955");
    Vertex topV = gg.getVertex("osm:node:559271124");
    request.setRoutingContext(a.graph, bottomV, topV);
    GraphPathFinder graphPathFinder = new GraphPathFinder(a);
    List<GraphPath> pathList = graphPathFinder.graphPathFinderEntryPoint(request);
    assertNotNull(pathList);
    assertFalse(pathList.isEmpty());
    for (GraphPath path : pathList) {
        assertFalse(path.states.isEmpty());
    }
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) IntersectionVertex(org.opentripplanner.routing.vertextype.IntersectionVertex) CommandLineParameters(org.opentripplanner.standalone.CommandLineParameters) FileBasedOpenStreetMapProviderImpl(org.opentripplanner.openstreetmap.impl.FileBasedOpenStreetMapProviderImpl) GraphPath(org.opentripplanner.routing.spt.GraphPath) Router(org.opentripplanner.standalone.Router) GraphService(org.opentripplanner.routing.services.GraphService) Graph(org.opentripplanner.routing.graph.Graph) OTPServer(org.opentripplanner.standalone.OTPServer) MemoryGraphSource(org.opentripplanner.routing.impl.MemoryGraphSource) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) File(java.io.File) GraphPathFinder(org.opentripplanner.routing.impl.GraphPathFinder) StreetVertexIndexServiceImpl(org.opentripplanner.routing.impl.StreetVertexIndexServiceImpl)

Example 4 with GraphPathFinder

use of org.opentripplanner.routing.impl.GraphPathFinder in project OpenTripPlanner by opentripplanner.

the class GraphVisualizer method route.

protected void route(String from, String to) {
    Date when;
    // Year + 1900
    try {
        when = dateFormat.parse(searchDate.getText());
    } catch (ParseException e) {
        searchDate.setText("Format: " + dateFormat.toPattern());
        return;
    }
    TraverseModeSet modeSet = new TraverseModeSet();
    modeSet.setWalk(walkCheckBox.isSelected());
    modeSet.setBicycle(bikeCheckBox.isSelected());
    modeSet.setFerry(ferryCheckBox.isSelected());
    modeSet.setRail(trainCheckBox.isSelected());
    modeSet.setTram(trainCheckBox.isSelected());
    modeSet.setSubway(trainCheckBox.isSelected());
    modeSet.setFunicular(trainCheckBox.isSelected());
    modeSet.setGondola(trainCheckBox.isSelected());
    modeSet.setBus(busCheckBox.isSelected());
    modeSet.setCableCar(busCheckBox.isSelected());
    modeSet.setCar(carCheckBox.isSelected());
    // otherwise 'false' will clear trainish and busish
    if (transitCheckBox.isSelected())
        modeSet.setTransit(true);
    RoutingRequest options = new RoutingRequest(modeSet);
    options.setArriveBy(arriveByCheckBox.isSelected());
    // override low 2-4 minute values
    options.setWalkBoardCost(Integer.parseInt(boardingPenaltyField.getText()) * 60);
    // TODO LG Add ui element for bike board cost (for now bike = 2 * walk)
    options.setBikeBoardCost(Integer.parseInt(boardingPenaltyField.getText()) * 60 * 2);
    // there should be a ui element for walk distance and optimize type
    options.setOptimize(getSelectedOptimizeType());
    options.setMaxWalkDistance(Integer.parseInt(maxWalkField.getText()));
    options.setDateTime(when);
    options.setFromString(from);
    options.setToString(to);
    options.walkSpeed = Float.parseFloat(walkSpeed.getText());
    options.bikeSpeed = Float.parseFloat(bikeSpeed.getText());
    options.softWalkLimiting = (softWalkLimiting.isSelected());
    options.softWalkPenalty = (Float.parseFloat(softWalkPenalty.getText()));
    options.softWalkOverageRate = (Float.parseFloat(this.softWalkOverageRate.getText()));
    options.numItineraries = 1;
    System.out.println("--------");
    System.out.println("Path from " + from + " to " + to + " at " + when);
    System.out.println("\tModes: " + modeSet);
    System.out.println("\tOptions: " + options);
    options.numItineraries = (Integer.parseInt(this.nPaths.getText()));
    // apply callback if the options call for it
    // if( dontUseGraphicalCallbackCheckBox.isSelected() ){
    // TODO perhaps avoid using a GraphPathFinder and go one level down the call chain directly to a GenericAStar
    // TODO perhaps instead of giving the pathservice a callback, we can just put the visitor in the routing request
    GraphPathFinder finder = new GraphPathFinder(router);
    long t0 = System.currentTimeMillis();
    // TODO: check options properly intialized (AMB)
    List<GraphPath> paths = finder.graphPathFinderEntryPoint(options);
    long dt = System.currentTimeMillis() - t0;
    searchTimeElapsedLabel.setText("search time elapsed: " + dt + "ms");
    if (paths == null) {
        System.out.println("no path");
        showGraph.highlightGraphPath(null);
        return;
    }
    // now's a convenient time to set graphical SPT weights
    showGraph.simpleSPT.setWeights();
    showPathsInPanel(paths);
    // now's a good time to set showGraph's SPT drawing weights
    showGraph.setSPTFlattening(Float.parseFloat(sptFlattening.getText()));
    showGraph.setSPTThickness(Float.parseFloat(sptThickness.getText()));
    showGraph.redraw();
    options.cleanup();
}
Also used : GraphPath(org.opentripplanner.routing.spt.GraphPath) TraverseModeSet(org.opentripplanner.routing.core.TraverseModeSet) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) ParseException(java.text.ParseException) GraphPathFinder(org.opentripplanner.routing.impl.GraphPathFinder)

Example 5 with GraphPathFinder

use of org.opentripplanner.routing.impl.GraphPathFinder in project OpenTripPlanner by opentripplanner.

the class GtfsTest method plan.

public Leg[] plan(long dateTime, String fromVertex, String toVertex, String onTripId, boolean wheelchairAccessible, boolean preferLeastTransfers, TraverseMode preferredMode, String excludedRoute, String excludedStop, int legCount) {
    final TraverseMode mode = preferredMode != null ? preferredMode : TraverseMode.TRANSIT;
    RoutingRequest routingRequest = new RoutingRequest();
    routingRequest.setNumItineraries(1);
    routingRequest.setArriveBy(dateTime < 0);
    routingRequest.dateTime = Math.abs(dateTime);
    if (fromVertex != null && !fromVertex.isEmpty()) {
        routingRequest.from = (new GenericLocation(null, feedId.getId() + ":" + fromVertex));
    }
    if (toVertex != null && !toVertex.isEmpty()) {
        routingRequest.to = new GenericLocation(null, feedId.getId() + ":" + toVertex);
    }
    if (onTripId != null && !onTripId.isEmpty()) {
        routingRequest.startingTransitTripId = (new AgencyAndId(feedId.getId(), onTripId));
    }
    routingRequest.setRoutingContext(graph);
    routingRequest.setWheelchairAccessible(wheelchairAccessible);
    routingRequest.transferPenalty = (preferLeastTransfers ? 300 : 0);
    routingRequest.setModes(new TraverseModeSet(TraverseMode.WALK, mode));
    // TODO route matcher still using underscores because it's quite nonstandard and should be eliminated from the 1.0 release rather than reworked
    if (excludedRoute != null && !excludedRoute.isEmpty()) {
        routingRequest.setBannedRoutes(feedId.getId() + "__" + excludedRoute);
    }
    if (excludedStop != null && !excludedStop.isEmpty()) {
        routingRequest.setBannedStopsHard(feedId.getId() + ":" + excludedStop);
    }
    routingRequest.setOtherThanPreferredRoutesPenalty(0);
    // The walk board cost is set low because it interferes with test 2c1.
    // As long as boarding has a very low cost, waiting should not be "better" than riding
    // since this makes interlining _worse_ than alighting and re-boarding the same line.
    // TODO rethink whether it makes sense to weight waiting to board _less_ than 1.
    routingRequest.setWaitReluctance(1);
    routingRequest.setWalkBoardCost(30);
    List<GraphPath> paths = new GraphPathFinder(router).getPaths(routingRequest);
    TripPlan tripPlan = GraphPathToTripPlanConverter.generatePlan(paths, routingRequest);
    // Stored in instance field for use in individual tests
    itinerary = tripPlan.itinerary.get(0);
    assertEquals(legCount, itinerary.legs.size());
    return itinerary.legs.toArray(new Leg[legCount]);
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) GraphPath(org.opentripplanner.routing.spt.GraphPath) TripPlan(org.opentripplanner.api.model.TripPlan) GenericLocation(org.opentripplanner.common.model.GenericLocation) TraverseMode(org.opentripplanner.routing.core.TraverseMode) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) TraverseModeSet(org.opentripplanner.routing.core.TraverseModeSet) GraphPathFinder(org.opentripplanner.routing.impl.GraphPathFinder)

Aggregations

GraphPathFinder (org.opentripplanner.routing.impl.GraphPathFinder)5 RoutingRequest (org.opentripplanner.routing.core.RoutingRequest)4 GraphPath (org.opentripplanner.routing.spt.GraphPath)4 Router (org.opentripplanner.standalone.Router)3 TripPlan (org.opentripplanner.api.model.TripPlan)2 TraverseModeSet (org.opentripplanner.routing.core.TraverseModeSet)2 Graph (org.opentripplanner.routing.graph.Graph)2 MemoryGraphSource (org.opentripplanner.routing.impl.MemoryGraphSource)2 GraphService (org.opentripplanner.routing.services.GraphService)2 CommandLineParameters (org.opentripplanner.standalone.CommandLineParameters)2 OTPServer (org.opentripplanner.standalone.OTPServer)2 File (java.io.File)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ParseException (java.text.ParseException)1 GET (javax.ws.rs.GET)1 Produces (javax.ws.rs.Produces)1 BeforeClass (org.junit.BeforeClass)1 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)1 PlannerError (org.opentripplanner.api.model.error.PlannerError)1 GenericLocation (org.opentripplanner.common.model.GenericLocation)1