Search in sources :

Example 6 with State

use of org.opentripplanner.routing.core.State in project OpenTripPlanner by opentripplanner.

the class GraphPathFinder method joinPaths.

private static GraphPath joinPaths(List<GraphPath> paths) {
    State lastState = paths.get(0).states.getLast();
    GraphPath newPath = new GraphPath(lastState, false);
    Vertex lastVertex = lastState.getVertex();
    // With more paths we should allow more transfers
    lastState.getOptions().maxTransfers *= paths.size();
    for (GraphPath path : paths.subList(1, paths.size())) {
        lastState = newPath.states.getLast();
        // add a leg-switching state
        LegSwitchingEdge legSwitchingEdge = new LegSwitchingEdge(lastVertex, lastVertex);
        lastState = legSwitchingEdge.traverse(lastState);
        newPath.edges.add(legSwitchingEdge);
        newPath.states.add(lastState);
        // add the next subpath
        for (Edge e : path.edges) {
            lastState = e.traverse(lastState);
            newPath.edges.add(e);
            newPath.states.add(lastState);
        }
        lastVertex = path.getEndVertex();
    }
    return newPath;
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) LegSwitchingEdge(org.opentripplanner.routing.edgetype.LegSwitchingEdge) State(org.opentripplanner.routing.core.State) GraphPath(org.opentripplanner.routing.spt.GraphPath) LegSwitchingEdge(org.opentripplanner.routing.edgetype.LegSwitchingEdge) Edge(org.opentripplanner.routing.graph.Edge)

Example 7 with State

use of org.opentripplanner.routing.core.State in project OpenTripPlanner by opentripplanner.

the class GraphPath method getTrips.

/**
 * @return A list containing one AgencyAndId (trip_id) for each vehicle boarded in this path,
 * in the chronological order they are boarded.
 */
public List<AgencyAndId> getTrips() {
    List<AgencyAndId> ret = new LinkedList<AgencyAndId>();
    Trip lastTrip = null;
    for (State s : states) {
        if (s.getBackEdge() != null) {
            Trip trip = s.getBackTrip();
            if (trip != null && trip != lastTrip) {
                ret.add(trip.getId());
                lastTrip = trip;
            }
        }
    }
    return ret;
}
Also used : Trip(org.onebusaway.gtfs.model.Trip) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) State(org.opentripplanner.routing.core.State) LinkedList(java.util.LinkedList)

Example 8 with State

use of org.opentripplanner.routing.core.State in project OpenTripPlanner by opentripplanner.

the class SIsochrone method getIsochrone.

/**
 * Calculates walksheds for a given location, based on time given to walk and the walk speed.
 *
 * Depending on the value for the "output" parameter (i.e. "POINTS", "SHED" or "EDGES"), a
 * different type of GeoJSON geometry is returned. If a SHED is requested, then a ConcaveHull
 * of the EDGES/roads is returned. If that fails, a ConvexHull will be returned.
 * <p>
 * The ConcaveHull parameter is set to 0.005 degrees. The offroad walkspeed is assumed to be
 * 0.83333 m/sec (= 3km/h) until a road is hit.
 * <p>
 * Note that the set of EDGES/roads returned as well as POINTS returned may contain duplicates.
 * If POINTS are requested, then not the end-points are returned at which the max time is
 * reached, but instead all the graph nodes/crossings that are within the time limits.
 * <p>
 * In case there is no road near by within the given time, then a circle for the walktime limit
 * is created and returned for the SHED parameter. Otherwise the edge with the direction
 * towards the closest road. Note that the circle is calculated in Euclidian 2D coordinates,
 * and distortions towards an ellipse will appear if it is transformed/projected to the user location.
 * <p>
 * An example request may look like this:
 * localhost:8080/otp-rest-servlet/ws/iso?layers=traveltime&styles=mask&batch=true&fromPlace=51.040193121307176
 * %2C-114.04471635818481&toPlace
 * =51.09098935%2C-113.95179705&time=2012-06-06T08%3A00%3A00&mode=WALK&maxWalkDistance=10000&walkSpeed=1.38&walkTime=10.7&output=EDGES
 * Though the first parameters (i) layer, (ii) styles and (iii) batch could be discarded.
 *
 * @param walkmins Maximum number of minutes to walk.
 * @param output Can be set to "POINTS", "SHED" or "EDGES" to return different types of GeoJSON
 *        geometry. SHED returns a ConcaveHull or ConvexHull of the edges/roads. POINTS returns
 *        all graph nodes that are within the time limit.
 * @return a JSON document containing geometries (either points, lineStrings or a polygon).
 * @throws Exception
 * @author sstein---geo.uzh.ch
 */
@GET
@Produces({ MediaType.APPLICATION_JSON })
public String getIsochrone(@QueryParam("walkTime") @DefaultValue("15") double walkmins, @QueryParam("output") @DefaultValue("POINTS") String output) throws Exception {
    this.debugGeoms = new ArrayList();
    this.tooFastTraversedEdgeGeoms = new ArrayList();
    RoutingRequest sptRequestA = buildRequest();
    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");
    // 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)) {
        // 20min (use 20min for transit, since buses may not come all the time)
        shedCalcMethodSwitchTimeInSec = 60 * 20;
    } else if (modes.contains(TraverseMode.CAR)) {
        // 10min
        shedCalcMethodSwitchTimeInSec = 60 * 10;
    } else if (modes.contains(TraverseMode.BICYCLE)) {
        // 10min
        shedCalcMethodSwitchTimeInSec = 60 * 10;
    } else {
        // 20min
        shedCalcMethodSwitchTimeInSec = 60 * 20;
    }
    // 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.getCar()) {
            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
    Router router = otpServer.getRouter(routerId);
    // create the ShortestPathTree
    try {
        sptRequestA.setRoutingContext(router.graph);
    } 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");
        // fall back to walk mode
        sptRequestA.setMode(TraverseMode.WALK);
        sptRequestA.setRoutingContext(router.graph);
    }
    ShortestPathTree sptA = new AStar().getShortestPathTree(sptRequestA);
    StreetLocation origin = (StreetLocation) sptRequestA.rctx.fromVertex;
    // remove inserted points
    sptRequestA.cleanup();
    // create a LineString for display
    Coordinate[] pathToStreetCoords = new Coordinate[2];
    pathToStreetCoords[0] = dropPoint;
    pathToStreetCoords[1] = origin.getCoordinate();
    LineString pathToStreet = gf.createLineString(pathToStreetCoords);
    // get distance between origin and drop point for time correction
    double distanceToRoad = SphericalDistanceLibrary.distance(origin.getY(), origin.getX(), dropPoint.y, dropPoint.x);
    long offRoadTimeCorrection = (long) (distanceToRoad / this.offRoadWalkspeed);
    // 
    // --- filter the states ---
    // 
    Set<Coordinate> visitedCoords = new HashSet<Coordinate>();
    ArrayList<Edge> allConnectingEdges = new ArrayList<Edge>();
    Coordinate[] coords = null;
    long maxTime = (long) walkInSec - offRoadTimeCorrection;
    // if the initial walk is already to long, there is no need to parse...
    if (maxTime <= 0) {
        noRoadNearBy = true;
        long timeToWalk = (long) walkInSec;
        long timeBetweenStates = offRoadTimeCorrection;
        long timeMissing = timeToWalk;
        double fraction = (double) timeMissing / (double) timeBetweenStates;
        pathToStreet = getSubLineString(pathToStreet, fraction);
        LOG.debug("no street found within giving travel time (for off-road walkspeed: {} m/sec)", this.offRoadWalkspeed);
    } else {
        noRoadNearBy = false;
        Map<ReversibleLineStringWrapper, Edge> connectingEdgesMap = Maps.newHashMap();
        for (State state : sptA.getAllStates()) {
            long et = state.getElapsedTimeSeconds();
            if (et <= maxTime) {
                // 250 points away (while 145 were finally displayed)
                if (visitedCoords.contains(state.getVertex().getCoordinate())) {
                    continue;
                } else {
                    visitedCoords.add(state.getVertex().getCoordinate());
                }
                // -- get all Edges needed later for the edge representation
                // and to calculate an edge-based walkshed
                // Note, it can happen that we get a null geometry here, e.g. for hop-edges!
                Collection<Edge> vertexEdgesIn = state.getVertex().getIncoming();
                for (Iterator<Edge> iterator = vertexEdgesIn.iterator(); iterator.hasNext(); ) {
                    Edge edge = (Edge) iterator.next();
                    Geometry edgeGeom = edge.getGeometry();
                    if (edgeGeom != null) {
                        // make sure we get only real edges
                        if (edgeGeom instanceof LineString) {
                            // allConnectingEdges.add(edge); // instead of this, use a map now, so we don't have similar edge many times
                            connectingEdgesMap.put(new ReversibleLineStringWrapper((LineString) edgeGeom), edge);
                        }
                    }
                }
                Collection<Edge> vertexEdgesOut = state.getVertex().getOutgoing();
                for (Iterator<Edge> iterator = vertexEdgesOut.iterator(); iterator.hasNext(); ) {
                    Edge edge = (Edge) iterator.next();
                    Geometry edgeGeom = edge.getGeometry();
                    if (edgeGeom != null) {
                        if (edgeGeom instanceof LineString) {
                            // allConnectingEdges.add(edge); // instead of this, use a map now, so we don't similar edge many times
                            connectingEdgesMap.put(new ReversibleLineStringWrapper((LineString) edgeGeom), edge);
                        }
                    }
                }
            }
        // end : if(et < maxTime)
        }
        // --
        // points from list to array, for later
        coords = new Coordinate[visitedCoords.size()];
        int i = 0;
        for (Coordinate c : visitedCoords) coords[i++] = c;
        // connection edges from Map to List
        allConnectingEdges.clear();
        for (Edge tedge : connectingEdgesMap.values()) allConnectingEdges.add(tedge);
    }
    StringWriter sw = new StringWriter();
    GeometryJSON geometryJSON = new GeometryJSON();
    // 
    try {
        if (output.equals(SIsochrone.RESULT_TYPE_POINTS)) {
            // and return those points
            if (noRoadNearBy) {
                Geometry circleShape = createCirle(dropPoint, pathToStreet);
                coords = circleShape.getCoordinates();
            }
            // -- the states/nodes with time elapsed <= X min.
            LOG.debug("write multipoint geom with {} points", coords.length);
            geometryJSON.write(gf.createMultiPoint(coords), sw);
            LOG.debug("done");
        } else if (output.equals(SIsochrone.RESULT_TYPE_SHED)) {
            Geometry[] geomsArray = null;
            // in case there was no road we create a circle
            if (noRoadNearBy) {
                Geometry circleShape = createCirle(dropPoint, pathToStreet);
                geometryJSON.write(circleShape, sw);
            } else {
                if (maxTime > shedCalcMethodSwitchTimeInSec) {
                    // eg., walkshed > 20 min
                    // -- create a point-based walkshed
                    // less exact and should be used for large walksheds with many edges
                    LOG.debug("create point-based shed (not from edges)");
                    geomsArray = new Geometry[coords.length];
                    for (int j = 0; j < geomsArray.length; j++) {
                        geomsArray[j] = gf.createPoint(coords[j]);
                    }
                } else {
                    // -- create an edge-based walkshed
                    // it is more exact and should be used for short walks
                    LOG.debug("create edge-based shed (not from points)");
                    Map<ReversibleLineStringWrapper, LineString> walkShedEdges = Maps.newHashMap();
                    // add the walk from the pushpin to closest street point
                    walkShedEdges.put(new ReversibleLineStringWrapper(pathToStreet), pathToStreet);
                    // get the edges and edge parts within time limits
                    ArrayList<LineString> withinTimeEdges = this.getLinesAndSubEdgesWithinMaxTime(maxTime, allConnectingEdges, sptA, angleLimitForUShapeDetection, distanceToleranceForUShapeDetection, maxUserSpeed, usesCar, doSpeedTest);
                    for (LineString ls : withinTimeEdges) {
                        walkShedEdges.put(new ReversibleLineStringWrapper(ls), ls);
                    }
                    geomsArray = new Geometry[walkShedEdges.size()];
                    int k = 0;
                    for (LineString ls : walkShedEdges.values()) geomsArray[k++] = ls;
                }
                // end if-else: maxTime condition
                GeometryCollection gc = gf.createGeometryCollection(geomsArray);
                // create the concave hull, but in case it fails we just return the convex hull
                Geometry outputHull = null;
                LOG.debug("create concave hull from {} geoms with edge length limit of about {} m (distance on meridian)", geomsArray.length, concaveHullAlpha * 111132);
                // (see wikipedia: http://en.wikipedia.org/wiki/Latitude#The_length_of_a_degree_of_latitude)
                try {
                    ConcaveHull hull = new ConcaveHull(gc, concaveHullAlpha);
                    outputHull = hull.getConcaveHull();
                } catch (Exception e) {
                    outputHull = gc.convexHull();
                    LOG.debug("Could not generate ConcaveHull for WalkShed, using ConvexHull instead.");
                }
                LOG.debug("write shed geom");
                geometryJSON.write(outputHull, sw);
                LOG.debug("done");
            }
        } else if (output.equals(SIsochrone.RESULT_TYPE_EDGES)) {
            // in case there was no road we return only the suggested path to the street
            if (noRoadNearBy) {
                geometryJSON.write(pathToStreet, sw);
            } else {
                // -- if we would use only the edges from the paths to the origin we will miss
                // some edges that will be never on the shortest path (e.g. loops/crescents).
                // However, we can retrieve all edges by checking the times for each
                // edge end-point
                Map<ReversibleLineStringWrapper, LineString> walkShedEdges = Maps.newHashMap();
                // add the walk from the pushpin to closest street point
                walkShedEdges.put(new ReversibleLineStringWrapper(pathToStreet), pathToStreet);
                // get the edges and edge parts within time limits
                ArrayList<LineString> withinTimeEdges = this.getLinesAndSubEdgesWithinMaxTime(maxTime, allConnectingEdges, sptA, angleLimitForUShapeDetection, distanceToleranceForUShapeDetection, maxUserSpeed, usesCar, doSpeedTest);
                for (LineString ls : withinTimeEdges) {
                    walkShedEdges.put(new ReversibleLineStringWrapper(ls), ls);
                }
                Geometry mls = null;
                LineString[] edges = new LineString[walkShedEdges.size()];
                int k = 0;
                for (LineString ls : walkShedEdges.values()) edges[k++] = ls;
                LOG.debug("create multilinestring from {} geoms", edges.length);
                mls = gf.createMultiLineString(edges);
                LOG.debug("write geom");
                geometryJSON.write(mls, sw);
                LOG.debug("done");
            }
        } else if (output.equals("DEBUGEDGES")) {
            // -- for debugging, i.e. display of detected u-shapes/crescents
            ArrayList<LineString> withinTimeEdges = this.getLinesAndSubEdgesWithinMaxTime(maxTime, allConnectingEdges, sptA, angleLimitForUShapeDetection, distanceToleranceForUShapeDetection, maxUserSpeed, usesCar, doSpeedTest);
            if (this.showTooFastEdgesAsDebugGeomsANDnotUShapes) {
                LOG.debug("displaying edges that are traversed too fast");
                this.debugGeoms = this.tooFastTraversedEdgeGeoms;
            } else {
                LOG.debug("displaying detected u-shaped roads/crescents");
            }
            LineString[] edges = new LineString[this.debugGeoms.size()];
            int k = 0;
            for (Iterator iterator = debugGeoms.iterator(); iterator.hasNext(); ) {
                LineString ls = (LineString) iterator.next();
                edges[k] = ls;
                k++;
            }
            Geometry mls = gf.createMultiLineString(edges);
            LOG.debug("write debug geom");
            geometryJSON.write(mls, sw);
            LOG.debug("done");
        }
    } catch (Exception e) {
        LOG.error("Exception creating isochrone", e);
    }
    return sw.toString();
}
Also used : GeometryJSON(org.geotools.geojson.geom.GeometryJSON) AStar(org.opentripplanner.routing.algorithm.AStar) StringWriter(java.io.StringWriter) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) ConcaveHull(org.opensphere.geometry.algorithm.ConcaveHull) Router(org.opentripplanner.standalone.Router) TraverseModeSet(org.opentripplanner.routing.core.TraverseModeSet) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) ReversibleLineStringWrapper(org.opentripplanner.common.geometry.ReversibleLineStringWrapper) State(org.opentripplanner.routing.core.State) StreetLocation(org.opentripplanner.routing.location.StreetLocation) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) Edge(org.opentripplanner.routing.graph.Edge)

Example 9 with State

use of org.opentripplanner.routing.core.State in project OpenTripPlanner by opentripplanner.

the class SIsochrone method getLinesAndSubEdgesWithinMaxTime.

/**
 * Filters all input edges and returns all those as LineString geometries, that have at least one end point within the time limits. If they have
 * only one end point inside, then the sub-edge is returned.
 *
 * @param maxTime the time limit in seconds that defines the size of the walkshed
 * @param allConnectingStateEdges all Edges that have been found to connect all states < maxTime
 * @param spt the ShortestPathTree generated for the pushpin drop point as origin
 * @param angleLimit the angle tolerance to detect roads with u-shapes, i.e. Pi/2 angles, in Radiant.
 * @param distanceTolerance in percent (e.g. 1.1 = 110%) for u-shape detection based on distance criteria
 * @param hasCar is travel mode by CAR?
 * @param performSpeedTest if true applies a test to each edge to check if the edge can be traversed in time. The test can detect u-shaped roads.
 * @return
 */
ArrayList<LineString> getLinesAndSubEdgesWithinMaxTime(long maxTime, ArrayList<Edge> allConnectingStateEdges, ShortestPathTree spt, double angleLimit, double distanceTolerance, double userSpeed, boolean hasCar, boolean performSpeedTest) {
    LOG.debug("maximal userSpeed set to: " + userSpeed + " m/sec ");
    if (hasCar) {
        LOG.debug("travel mode is set to CAR, hence the given speed may be adjusted for each edge");
    }
    ArrayList<LineString> walkShedEdges = new ArrayList<LineString>();
    ArrayList<LineString> otherEdges = new ArrayList<LineString>();
    ArrayList<LineString> borderEdges = new ArrayList<LineString>();
    ArrayList<LineString> uShapes = new ArrayList<LineString>();
    int countEdgesOutside = 0;
    // -- determination of walkshed edges via edge states
    for (Iterator iterator = allConnectingStateEdges.iterator(); iterator.hasNext(); ) {
        Edge edge = (Edge) iterator.next();
        State sFrom = spt.getState(edge.getFromVertex());
        State sTo = spt.getState(edge.getToVertex());
        if ((sFrom != null) && (sTo != null)) {
            long fromTime = sFrom.getElapsedTimeSeconds();
            long toTime = sTo.getElapsedTimeSeconds();
            long dt = Math.abs(toTime - fromTime);
            Geometry edgeGeom = edge.getGeometry();
            if ((edgeGeom != null) && (edgeGeom instanceof LineString)) {
                LineString ls = (LineString) edgeGeom;
                // detect u-shape roads/crescents - they need to be treated separately
                boolean uShapeOrLonger = testForUshape(edge, maxTime, fromTime, toTime, angleLimit, distanceTolerance, userSpeed, hasCar, performSpeedTest);
                if (uShapeOrLonger) {
                    uShapes.add(ls);
                }
                // evaluate if an edge is completely within the time or only with one end
                if ((fromTime < maxTime) && (toTime < maxTime)) {
                    // a second test if we have a u-shaped road.
                    if (uShapeOrLonger) {
                        treatAndAddUshapeWithinTimeLimits(maxTime, userSpeed, walkShedEdges, edge, fromTime, toTime, ls, hasCar);
                    } else {
                        walkShedEdges.add(ls);
                    }
                } else // end if:fromTime & toTime < maxTime
                {
                    // create the sub edge
                    if ((fromTime < maxTime) || (toTime < maxTime)) {
                        double lineDist = edge.getDistance();
                        LineString inputLS = ls;
                        double fraction = 1.0;
                        if (fromTime < toTime) {
                            double distanceToWalkInTimeMissing = distanceToMoveInRemainingTime(maxTime, fromTime, dt, userSpeed, edge, hasCar, uShapeOrLonger);
                            fraction = (double) distanceToWalkInTimeMissing / (double) lineDist;
                        } else {
                            // toTime < fromTime : invert the edge direction
                            inputLS = (LineString) ls.reverse();
                            double distanceToWalkInTimeMissing = distanceToMoveInRemainingTime(maxTime, toTime, dt, userSpeed, edge, hasCar, uShapeOrLonger);
                            fraction = (double) distanceToWalkInTimeMissing / (double) lineDist;
                        }
                        // get the subedge
                        LineString subLine = this.getSubLineString(inputLS, fraction);
                        borderEdges.add(subLine);
                    } else {
                        // this edge is completely outside - this should actually not happen
                        // we will not do anything, just count
                        countEdgesOutside++;
                    }
                }
            // end else: fromTime & toTime < maxTime
            } else // end if: edge instance of LineString
            {
                // edge is not instance of LineString
                LOG.debug("edge not instance of LineString");
            }
        } else // end if(sFrom && sTo != null) start Else
        {
            // LOG.debug("could not retrieve state for edge-endpoint"); //for a 6min car ride, there can be (too) many of such messages
            Geometry edgeGeom = edge.getGeometry();
            if ((edgeGeom != null) && (edgeGeom instanceof LineString)) {
                otherEdges.add((LineString) edgeGeom);
            }
        }
    // end else: sFrom && sTo != null
    }
    // end for loop over edges
    walkShedEdges.addAll(borderEdges);
    this.debugGeoms.addAll(uShapes);
    LOG.debug("number of detected u-shapes/crescents: " + uShapes.size());
    return walkShedEdges;
}
Also used : State(org.opentripplanner.routing.core.State) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) Edge(org.opentripplanner.routing.graph.Edge)

Example 10 with State

use of org.opentripplanner.routing.core.State in project OpenTripPlanner by opentripplanner.

the class AnalysisUtils method getComponentPolygons.

/**
 * Get polygons covering the components of the graph. The largest component (in terms of number
 * of nodes) will not overlap any other components (it will have holes); the others may overlap
 * each other.
 *
 * @param dateTime
 */
public static List<Geometry> getComponentPolygons(Graph graph, RoutingRequest options, long time) {
    DisjointSet<Vertex> components = getConnectedComponents(graph);
    LinkedListMultimap<Integer, Coordinate> componentCoordinates = LinkedListMultimap.create();
    options.setDummyRoutingContext(graph);
    for (Vertex v : graph.getVertices()) {
        for (Edge e : v.getOutgoing()) {
            State s0 = new State(v, time, options);
            State s1 = e.traverse(s0);
            if (s1 != null) {
                Integer component = components.find(e.getFromVertex());
                Geometry geometry = s1.getBackEdge().getGeometry();
                if (geometry != null) {
                    List<Coordinate> coordinates = new ArrayList<Coordinate>(Arrays.asList(geometry.getCoordinates()));
                    for (int i = 0; i < coordinates.size(); ++i) {
                        Coordinate coordinate = new Coordinate(coordinates.get(i));
                        coordinate.x = Math.round(coordinate.x * PRECISION) / PRECISION;
                        coordinate.y = Math.round(coordinate.y * PRECISION) / PRECISION;
                        coordinates.set(i, coordinate);
                    }
                    componentCoordinates.putAll(component, coordinates);
                }
            }
        }
    }
    // generate convex hull of each component
    List<Geometry> geoms = new ArrayList<Geometry>();
    int mainComponentSize = 0;
    int mainComponentIndex = -1;
    int component = 0;
    for (Integer key : componentCoordinates.keySet()) {
        List<Coordinate> coords = componentCoordinates.get(key);
        Coordinate[] coordArray = new Coordinate[coords.size()];
        ConvexHull hull = new ConvexHull(coords.toArray(coordArray), GeometryUtils.getGeometryFactory());
        Geometry geom = hull.getConvexHull();
        // buffer components which are mere lines so that they do not disappear.
        if (geom instanceof LineString) {
            // ~10 meters
            geom = geom.buffer(0.01);
        } else if (geom instanceof Point) {
            // ~50 meters, so that it shows up
            geom = geom.buffer(0.05);
        }
        geoms.add(geom);
        if (mainComponentSize < coordArray.length) {
            mainComponentIndex = component;
            mainComponentSize = coordArray.length;
        }
        ++component;
    }
    // subtract small components out of main component
    // (small components are permitted to overlap each other)
    Geometry mainComponent = geoms.get(mainComponentIndex);
    for (int i = 0; i < geoms.size(); ++i) {
        Geometry geom = geoms.get(i);
        if (i == mainComponentIndex) {
            continue;
        }
        mainComponent = mainComponent.difference(geom);
    }
    geoms.set(mainComponentIndex, mainComponent);
    return geoms;
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) ArrayList(java.util.ArrayList) ConvexHull(com.vividsolutions.jts.algorithm.ConvexHull) Point(com.vividsolutions.jts.geom.Point) Point(com.vividsolutions.jts.geom.Point) Geometry(com.vividsolutions.jts.geom.Geometry) Coordinate(com.vividsolutions.jts.geom.Coordinate) LineString(com.vividsolutions.jts.geom.LineString) State(org.opentripplanner.routing.core.State) Edge(org.opentripplanner.routing.graph.Edge)

Aggregations

State (org.opentripplanner.routing.core.State)78 RoutingRequest (org.opentripplanner.routing.core.RoutingRequest)42 GraphPath (org.opentripplanner.routing.spt.GraphPath)25 ShortestPathTree (org.opentripplanner.routing.spt.ShortestPathTree)24 Test (org.junit.Test)23 Edge (org.opentripplanner.routing.graph.Edge)22 Vertex (org.opentripplanner.routing.graph.Vertex)20 StreetEdge (org.opentripplanner.routing.edgetype.StreetEdge)13 Coordinate (com.vividsolutions.jts.geom.Coordinate)11 TransitStop (org.opentripplanner.routing.vertextype.TransitStop)8 Graph (org.opentripplanner.routing.graph.Graph)7 DominanceFunction (org.opentripplanner.routing.spt.DominanceFunction)7 NonLocalizedString (org.opentripplanner.util.NonLocalizedString)6 LineString (com.vividsolutions.jts.geom.LineString)5 HashSet (java.util.HashSet)5 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)5 Trip (org.onebusaway.gtfs.model.Trip)5 StateEditor (org.opentripplanner.routing.core.StateEditor)5 TemporaryStreetLocation (org.opentripplanner.routing.location.TemporaryStreetLocation)5 IntersectionVertex (org.opentripplanner.routing.vertextype.IntersectionVertex)5