Search in sources :

Example 11 with Router

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

the class TimeGridWs method getTimeGridPng.

@GET
@Produces({ "image/png" })
public Response getTimeGridPng(@QueryParam("base64") @DefaultValue("false") boolean base64) throws Exception {
    /* Fetch the Router for this request using server and routerId fields from superclass. */
    Router router = otpServer.getRouter(routerId);
    if (precisionMeters < 10)
        throw new IllegalArgumentException("Too small precisionMeters: " + precisionMeters);
    if (offRoadDistanceMeters < 10)
        throw new IllegalArgumentException("Too small offRoadDistanceMeters: " + offRoadDistanceMeters);
    // Build the request
    RoutingRequest sptRequest = buildRequest();
    SampleGridRequest tgRequest = new SampleGridRequest();
    tgRequest.maxTimeSec = maxTimeSec;
    tgRequest.precisionMeters = precisionMeters;
    tgRequest.offRoadDistanceMeters = offRoadDistanceMeters;
    if (coordinateOrigin != null)
        tgRequest.coordinateOrigin = new GenericLocation(null, coordinateOrigin).getCoordinate();
    // Get a sample grid
    ZSampleGrid<WTWD> sampleGrid = router.sampleGridRenderer.getSampleGrid(tgRequest, sptRequest);
    int cols = sampleGrid.getXMax() - sampleGrid.getXMin() + 1;
    int rows = sampleGrid.getYMax() - sampleGrid.getYMin() + 1;
    // Hard-coded to RGBA
    int channels = 4;
    // We force to 8 bits channel depth, some clients won't support more than 8
    // (namely, HTML5 canvas...)
    ImageInfo imgInfo = new ImageInfo(cols, rows, 8, true, false, false);
    /**
     * TODO: PNGJ allow for progressive (ie line-by-line) writing. Thus we could theorically
     * prevent having to allocate a bit pixel array in the first place, but we would need a
     * line-by-line iterator on the sample grid, which is currently not the case.
     */
    int[][] rgba = new int[rows][cols * channels];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PngWriter pw = new PngWriter(baos, imgInfo);
    pw.getMetadata().setText(PngChunkTextVar.KEY_Software, "OTPA");
    pw.getMetadata().setText(PngChunkTextVar.KEY_Creation_Time, new Date().toString());
    pw.getMetadata().setText(PngChunkTextVar.KEY_Description, "Sample grid bitmap");
    String gridCornerStr = String.format(Locale.US, "%.8f,%.8f", sampleGrid.getCenter().y + sampleGrid.getYMin() * sampleGrid.getCellSize().y, sampleGrid.getCenter().x + sampleGrid.getXMin() * sampleGrid.getCellSize().x);
    String gridCellSzStr = String.format(Locale.US, "%.12f,%.12f", sampleGrid.getCellSize().y, sampleGrid.getCellSize().x);
    String offRoadDistStr = String.format(Locale.US, "%d", offRoadDistanceMeters);
    PngChunkTEXT gridCornerChunk = new PngChunkTEXT(imgInfo);
    gridCornerChunk.setKeyVal(OTPA_GRID_CORNER, gridCornerStr);
    pw.getChunksList().queue(gridCornerChunk);
    PngChunkTEXT gridCellSzChunk = new PngChunkTEXT(imgInfo);
    gridCellSzChunk.setKeyVal(OTPA_GRID_CELL_SIZE, gridCellSzStr);
    pw.getChunksList().queue(gridCellSzChunk);
    PngChunkTEXT offRoadDistChunk = new PngChunkTEXT(imgInfo);
    offRoadDistChunk.setKeyVal(OTPA_OFFROAD_DIST, offRoadDistStr);
    pw.getChunksList().queue(offRoadDistChunk);
    double unit;
    switch(zDataType) {
        case TIME:
            // 1:1sec, max 18h
            unit = 1.0;
            break;
        case BOARDINGS:
            // 1:0.001 boarding, max 65.5
            unit = 1000.0;
            break;
        case WALK_DISTANCE:
            // 1:0.1m, max 6.55km
            unit = 10.0;
            break;
        default:
            throw new IllegalArgumentException("Unsupported Z DataType.");
    }
    for (ZSamplePoint<WTWD> p : sampleGrid) {
        WTWD z = p.getZ();
        int row = p.getY() - sampleGrid.getYMin();
        int col = p.getX() - sampleGrid.getXMin();
        double zz;
        switch(zDataType) {
            case TIME:
                zz = z.wTime / z.w;
                break;
            case BOARDINGS:
                zz = z.wBoardings / z.w;
                break;
            case WALK_DISTANCE:
                zz = z.wWalkDist / z.w;
                break;
            default:
                throw new IllegalArgumentException("Unsupported Z DataType.");
        }
        int iz;
        if (Double.isInfinite(zz)) {
            iz = 65535;
        } else {
            iz = ImageLineHelper.clampTo_0_65535((int) Math.round(zz * unit));
            if (iz == 65535)
                // Clamp
                iz = 65534;
        }
        // d is expressed as a percentage of grid size, max 255%.
        // Sometimes d will be bigger than 2.55 x grid size,
        // but this should not be too much important as we are off-bounds.
        int id = ImageLineHelper.clampTo_0_255((int) Math.round(z.d / precisionMeters * 100));
        int offset = col * channels;
        // z low 8 bits
        rgba[row][offset + 0] = (iz & 0xFF);
        // z high 8 bits
        rgba[row][offset + 1] = (iz >> 8);
        // d
        rgba[row][offset + 2] = id;
        /*
             * Keep the alpha channel at 255, otherwise the RGB channel will be downsampled on some
             * rendering clients (namely, JS canvas).
             */
        rgba[row][offset + 3] = 255;
    }
    for (int row = 0; row < rgba.length; row++) {
        ImageLineInt iline = new ImageLineInt(imgInfo, rgba[row]);
        pw.writeRow(iline, row);
    }
    pw.end();
    // Disallow caching on client side
    CacheControl cc = new CacheControl();
    cc.setNoCache(true);
    // Also put the meta-data in the HTML header (easier to read from JS)
    byte[] data = baos.toByteArray();
    if (base64) {
        data = Base64.encodeBase64(data);
    }
    return Response.ok().cacheControl(cc).entity(data).header(OTPA_GRID_CORNER, gridCornerStr).header(OTPA_GRID_CELL_SIZE, gridCellSzStr).header(OTPA_OFFROAD_DIST, offRoadDistStr).build();
}
Also used : PngChunkTEXT(ar.com.hjg.pngj.chunks.PngChunkTEXT) WTWD(org.opentripplanner.analyst.request.SampleGridRenderer.WTWD) SampleGridRequest(org.opentripplanner.analyst.request.SampleGridRequest) Router(org.opentripplanner.standalone.Router) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ZSamplePoint(org.opentripplanner.common.geometry.ZSampleGrid.ZSamplePoint) Date(java.util.Date) PngWriter(ar.com.hjg.pngj.PngWriter) GenericLocation(org.opentripplanner.common.model.GenericLocation) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) CacheControl(javax.ws.rs.core.CacheControl) ImageInfo(ar.com.hjg.pngj.ImageInfo) ImageLineInt(ar.com.hjg.pngj.ImageLineInt)

Example 12 with Router

use of org.opentripplanner.standalone.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(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 13 with Router

use of org.opentripplanner.standalone.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 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 14 with Router

use of org.opentripplanner.standalone.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);
    alertsUpdateHandler = new AlertsUpdateHandler();
    graph = new Graph();
    router = new Router("TEST", graph);
    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(feedId.getId()).iterator().next().getId();
    System.out.printf("Set the agency ID for this test to %s\n", agencyId);
    graph.index(new DefaultStreetVertexIndexFactory());
    timetableSnapshotSource = new TimetableSnapshotSource(graph);
    timetableSnapshotSource.purgeExpiredData = (false);
    graph.timetableSnapshotSource = (timetableSnapshotSource);
    alertPatchServiceImpl = new AlertPatchServiceImpl(graph);
    alertsUpdateHandler.setAlertPatchService(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.Router) DefaultStreetVertexIndexFactory(org.opentripplanner.routing.impl.DefaultStreetVertexIndexFactory) AlertPatchServiceImpl(org.opentripplanner.routing.impl.AlertPatchServiceImpl) 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) TimetableSnapshotSource(org.opentripplanner.updater.stoptime.TimetableSnapshotSource) AlertsUpdateHandler(org.opentripplanner.updater.alerts.AlertsUpdateHandler)

Example 15 with Router

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

the class GraphInspectorTileResource method tileGet.

@GET
@Path("/tile/{layer}/{z}/{x}/{y}.{ext}")
@Produces("image/*")
public Response tileGet() throws Exception {
    // Re-use analyst
    Envelope2D env = SlippyTile.tile2Envelope(x, y, z);
    TileRequest tileRequest = new TileRequest(env, 256, 256);
    Router router = otpServer.getRouter(routerId);
    BufferedImage image = router.tileRendererManager.renderTile(tileRequest, layer);
    MIMEImageFormat format = new MIMEImageFormat("image/" + ext);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(image.getWidth() * image.getHeight() / 4);
    ImageIO.write(image, format.type, baos);
    CacheControl cc = new CacheControl();
    cc.setMaxAge(3600);
    cc.setNoCache(false);
    return Response.ok(baos.toByteArray()).type(format.toString()).cacheControl(cc).build();
}
Also used : TileRequest(org.opentripplanner.analyst.request.TileRequest) Router(org.opentripplanner.standalone.Router) MIMEImageFormat(org.opentripplanner.api.parameter.MIMEImageFormat) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CacheControl(javax.ws.rs.core.CacheControl) Envelope2D(org.geotools.geometry.Envelope2D) BufferedImage(java.awt.image.BufferedImage) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

Router (org.opentripplanner.standalone.Router)22 GET (javax.ws.rs.GET)9 Produces (javax.ws.rs.Produces)8 RoutingRequest (org.opentripplanner.routing.core.RoutingRequest)8 Path (javax.ws.rs.Path)6 Graph (org.opentripplanner.routing.graph.Graph)6 Envelope2D (org.geotools.geometry.Envelope2D)5 TimeSurface (org.opentripplanner.analyst.TimeSurface)5 TileRequest (org.opentripplanner.analyst.request.TileRequest)5 RenderRequest (org.opentripplanner.analyst.request.RenderRequest)4 ArrayList (java.util.ArrayList)3 DefaultStreetVertexIndexFactory (org.opentripplanner.routing.impl.DefaultStreetVertexIndexFactory)3 GraphPathFinder (org.opentripplanner.routing.impl.GraphPathFinder)3 ShortestPathTree (org.opentripplanner.routing.spt.ShortestPathTree)3 CommandLineParameters (org.opentripplanner.standalone.CommandLineParameters)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 Date (java.util.Date)2 MIMEImageFormat (org.opentripplanner.api.parameter.MIMEImageFormat)2 GenericLocation (org.opentripplanner.common.model.GenericLocation)2