Search in sources :

Example 6 with Router

use of org.opentripplanner.standalone.server.Router in project OpenTripPlanner by opentripplanner.

the class GtfsTest method setUp.

protected void setUp() {
    File gtfs = new File("src/test/resources/" + getFeedName());
    File gtfsRealTime = new File("src/test/resources/" + getFeedName() + ".pb");
    GtfsBundle gtfsBundle = new GtfsBundle(gtfs);
    feedId = new GtfsFeedId.Builder().id("FEED").build();
    gtfsBundle.setFeedId(feedId);
    List<GtfsBundle> gtfsBundleList = Collections.singletonList(gtfsBundle);
    GtfsModule gtfsGraphBuilderImpl = new GtfsModule(gtfsBundleList, ServiceDateInterval.unbounded());
    alertsUpdateHandler = new AlertsUpdateHandler();
    graph = new Graph();
    router = new Router(graph, RouterConfig.DEFAULT);
    gtfsBundle.setTransfersTxtDefinesStationPaths(true);
    gtfsGraphBuilderImpl.buildGraph(graph, null);
    // Set the agency ID to be used for tests to the first one in the feed.
    agencyId = graph.getAgencies().iterator().next().getId().getId();
    System.out.printf("Set the agency ID for this test to %s\n", agencyId);
    graph.index();
    timetableSnapshotSource = new TimetableSnapshotSource(graph);
    timetableSnapshotSource.purgeExpiredData = false;
    graph.getOrSetupTimetableSnapshotProvider(g -> timetableSnapshotSource);
    alertPatchServiceImpl = new TransitAlertServiceImpl(graph);
    alertsUpdateHandler.setTransitAlertService(alertPatchServiceImpl);
    alertsUpdateHandler.setFeedId(feedId.getId());
    try {
        final boolean fullDataset = false;
        InputStream inputStream = new FileInputStream(gtfsRealTime);
        FeedMessage feedMessage = FeedMessage.PARSER.parseFrom(inputStream);
        List<FeedEntity> feedEntityList = feedMessage.getEntityList();
        List<TripUpdate> updates = new ArrayList<TripUpdate>(feedEntityList.size());
        for (FeedEntity feedEntity : feedEntityList) {
            updates.add(feedEntity.getTripUpdate());
        }
        timetableSnapshotSource.applyTripUpdates(graph, fullDataset, updates, feedId.getId());
        alertsUpdateHandler.update(feedMessage);
    } catch (Exception exception) {
    }
}
Also used : TripUpdate(com.google.transit.realtime.GtfsRealtime.TripUpdate) GtfsFeedId(org.opentripplanner.graph_builder.module.GtfsFeedId) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Router(org.opentripplanner.standalone.server.Router) FileInputStream(java.io.FileInputStream) FeedMessage(com.google.transit.realtime.GtfsRealtime.FeedMessage) GtfsModule(org.opentripplanner.graph_builder.module.GtfsModule) Graph(org.opentripplanner.routing.graph.Graph) GtfsBundle(org.opentripplanner.graph_builder.model.GtfsBundle) FeedEntity(com.google.transit.realtime.GtfsRealtime.FeedEntity) File(java.io.File) TransitAlertServiceImpl(org.opentripplanner.routing.impl.TransitAlertServiceImpl) TimetableSnapshotSource(org.opentripplanner.updater.stoptime.TimetableSnapshotSource) AlertsUpdateHandler(org.opentripplanner.updater.alerts.AlertsUpdateHandler)

Example 7 with Router

use of org.opentripplanner.standalone.server.Router 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();
        Router router = new Router(graph, RouterConfig.DEFAULT);
        router.startup();
        TestIntermediatePlaces.graphPathFinder = new GraphPathFinder(router);
        timeZone = graph.getTimeZone();
    } catch (Exception e) {
        e.printStackTrace();
        assert false : "Could not add transit data: " + e.toString();
    }
}
Also used : FakeGraph(org.opentripplanner.graph_builder.module.FakeGraph) Graph(org.opentripplanner.routing.graph.Graph) Router(org.opentripplanner.standalone.server.Router) GraphPathFinder(org.opentripplanner.routing.impl.GraphPathFinder) BeforeClass(org.junit.BeforeClass)

Example 8 with Router

use of org.opentripplanner.standalone.server.Router 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 graph = new Graph();
    OpenStreetMapModule loader = new OpenStreetMapModule();
    loader.skipVisibility = skipVisibility;
    loader.setDefaultWayPropertySetSource(new DefaultWayPropertySetSource());
    File file = new File(URLDecoder.decode(getClass().getResource("usf_area.osm.pbf").getFile(), "UTF-8"));
    BinaryOpenStreetMapProvider provider = new BinaryOpenStreetMapProvider(file, false);
    loader.setProvider(provider);
    loader.buildGraph(graph, extra);
    new StreetVertexIndex(graph);
    Router router = new Router(graph, RouterConfig.DEFAULT);
    router.startup();
    RoutingRequest request = new RoutingRequest(new TraverseModeSet(TraverseMode.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 = graph.getVertex("osm:node:580290955");
    Vertex topV = graph.getVertex("osm:node:559271124");
    request.setRoutingContext(router.graph, bottomV, topV);
    GraphPathFinder graphPathFinder = new GraphPathFinder(router);
    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) GraphPath(org.opentripplanner.routing.spt.GraphPath) Router(org.opentripplanner.standalone.server.Router) TraverseModeSet(org.opentripplanner.routing.core.TraverseModeSet) BinaryOpenStreetMapProvider(org.opentripplanner.openstreetmap.BinaryOpenStreetMapProvider) Graph(org.opentripplanner.routing.graph.Graph) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest) File(java.io.File) GraphPathFinder(org.opentripplanner.routing.impl.GraphPathFinder) StreetVertexIndex(org.opentripplanner.routing.impl.StreetVertexIndex)

Example 9 with Router

use of org.opentripplanner.standalone.server.Router in project OpenTripPlanner by opentripplanner.

the class TransmodelGraphQLPlanner method plan.

public PlanResponse plan(DataFetchingEnvironment environment) {
    PlanResponse response = new PlanResponse();
    RoutingRequest request = null;
    try {
        TransmodelRequestContext ctx = environment.getContext();
        Router router = ctx.getRouter();
        request = createRequest(environment);
        RoutingResponse res = ctx.getRoutingService().route(request, router);
        response.plan = res.getTripPlan();
        response.metadata = res.getMetadata();
        for (RoutingError routingError : res.getRoutingErrors()) {
            response.messages.add(PlannerErrorMapper.mapMessage(routingError).message);
        }
        response.debugOutput = res.getDebugAggregator().finishedRendering();
    } catch (Exception e) {
        LOG.warn("System error");
        LOG.error("Root cause: " + e.getMessage(), e);
        PlannerError error = new PlannerError();
        error.setMsg(Message.SYSTEM_ERROR);
        response.messages.add(error.message);
    }
    return response;
}
Also used : RoutingError(org.opentripplanner.routing.api.response.RoutingError) PlanResponse(org.opentripplanner.ext.transmodelapi.model.PlanResponse) Router(org.opentripplanner.standalone.server.Router) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest) PlannerError(org.opentripplanner.api.model.error.PlannerError) RoutingResponse(org.opentripplanner.routing.api.response.RoutingResponse) ParameterException(org.opentripplanner.api.common.ParameterException)

Example 10 with Router

use of org.opentripplanner.standalone.server.Router 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();
    RoutingRequest request = router.defaultRoutingRequest.clone();
    // router configuration and cloned. We check whether each parameter was supplied before overwriting the default.
    if (fromPlace != null)
        request.from = LocationStringParser.fromOldStyleString(fromPlace);
    if (toPlace != null)
        request.to = LocationStringParser.fromOldStyleString(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 (searchWindow != null) {
        request.searchWindow = Duration.ofSeconds(searchWindow);
    }
    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 == BicycleOptimizeType.TRIANGLE) {
            RoutingRequest.assertTriangleParameters(triangleSafetyFactor, triangleTimeFactor, triangleSlopeFactor);
            request.setBikeTriangleSafetyFactor(triangleSafetyFactor);
            request.setBikeTriangleSlopeFactor(triangleSlopeFactor);
            request.setBikeTriangleTimeFactor(triangleTimeFactor);
        }
    }
    if (arriveBy != null) {
        request.setArriveBy(arriveBy);
    }
    if (showIntermediateStops != null) {
        request.showIntermediateStops = showIntermediateStops;
    }
    if (intermediatePlaces != null) {
        request.setIntermediatePlacesFromStrings(intermediatePlaces);
    }
    if (preferredRoutes != null) {
        request.setPreferredRoutesFromSting(preferredRoutes);
    }
    if (otherThanPreferredRoutesPenalty != null) {
        request.setOtherThanPreferredRoutesPenalty(otherThanPreferredRoutesPenalty);
    }
    if (preferredAgencies != null) {
        request.setPreferredAgenciesFromString(preferredAgencies);
    }
    if (unpreferredRoutes != null) {
        request.setUnpreferredRoutesFromSting(unpreferredRoutes);
    }
    if (unpreferredAgencies != null) {
        request.setUnpreferredAgenciesFromString(unpreferredAgencies);
    }
    if (walkBoardCost != null) {
        request.setWalkBoardCost(walkBoardCost);
    }
    if (bikeBoardCost != null) {
        request.setBikeBoardCost(bikeBoardCost);
    }
    if (bannedRoutes != null) {
        request.setBannedRoutesFromSting(bannedRoutes);
    }
    if (whiteListedRoutes != null) {
        request.setWhiteListedRoutesFromSting(whiteListedRoutes);
    }
    if (bannedAgencies != null) {
        request.setBannedAgenciesFromSting(bannedAgencies);
    }
    if (whiteListedAgencies != null) {
        request.setWhiteListedAgenciesFromSting(whiteListedAgencies);
    }
    HashMap<FeedScopedId, BannedStopSet> bannedTripMap = makeBannedTripMap(bannedTrips);
    if (bannedTripMap != null) {
        request.bannedTrips = bannedTripMap;
    }
    // See comment on RoutingRequest.transferPentalty.
    if (transferPenalty != null) {
        request.transferCost = transferPenalty;
    }
    if (optimize == BicycleOptimizeType.TRANSFERS) {
        optimize = BicycleOptimizeType.QUICK;
        request.transferCost += 1800;
    }
    if (optimize != null) {
        request.setOptimize(optimize);
    }
    /* Temporary code to get bike/car parking and renting working. */
    if (modes != null && !modes.qModes.isEmpty()) {
        request.modes = modes.getRequestModes();
    }
    if (request.bikeRental && 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) {
        int alightAndBoardSlack = request.boardSlack + request.alightSlack;
        if (alightAndBoardSlack > minTransferTime) {
            throw new IllegalArgumentException("Invalid parameters: 'minTransferTime' must be greater than or equal to board slack plus alight slack");
        }
        request.transferSlack = minTransferTime - alightAndBoardSlack;
    }
    if (nonpreferredTransferPenalty != null)
        request.nonpreferredTransferCost = nonpreferredTransferPenalty;
    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 = FeedScopedId.parseId(startTransitStopId);
    if (startTransitTripId != null && !startTransitTripId.isEmpty())
        request.startingTransitTripId = FeedScopedId.parseId(startTransitTripId);
    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;
    if (pathComparator != null)
        request.pathComparator = pathComparator;
    if (debugItineraryFilter != null) {
        request.debugItineraryFilter = debugItineraryFilter;
    }
    // getLocale function returns defaultLocale if locale is null
    request.locale = ResourceBundleSingleton.INSTANCE.getLocale(locale);
    return request;
}
Also used : DatatypeFactory(javax.xml.datatype.DatatypeFactory) BannedStopSet(org.opentripplanner.routing.api.request.BannedStopSet) GregorianCalendar(java.util.GregorianCalendar) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) Router(org.opentripplanner.standalone.server.Router) Date(java.util.Date) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) DatatypeConfigurationException(javax.xml.datatype.DatatypeConfigurationException) TimeZone(java.util.TimeZone) FeedScopedId(org.opentripplanner.model.FeedScopedId) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest)

Aggregations

Router (org.opentripplanner.standalone.server.Router)12 RoutingRequest (org.opentripplanner.routing.api.request.RoutingRequest)6 GET (javax.ws.rs.GET)4 Produces (javax.ws.rs.Produces)4 Graph (org.opentripplanner.routing.graph.Graph)4 ArrayList (java.util.ArrayList)3 File (java.io.File)2 Date (java.util.Date)2 List (java.util.List)2 Path (javax.ws.rs.Path)2 ParameterException (org.opentripplanner.api.common.ParameterException)2 PlannerError (org.opentripplanner.api.model.error.PlannerError)2 GraphPathFinder (org.opentripplanner.routing.impl.GraphPathFinder)2 GraphPath (org.opentripplanner.routing.spt.GraphPath)2 FeedEntity (com.google.transit.realtime.GtfsRealtime.FeedEntity)1 FeedMessage (com.google.transit.realtime.GtfsRealtime.FeedMessage)1 TripUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate)1 BufferedImage (java.awt.image.BufferedImage)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1