Search in sources :

Example 26 with Edge

use of org.opentripplanner.routing.graph.Edge in project OpenTripPlanner by opentripplanner.

the class GraphPathToTripPlanConverter method generateWalkSteps.

/**
 * Converts a list of street edges to a list of turn-by-turn directions.
 *
 * @param previous a non-transit leg that immediately precedes this one (bike-walking, say), or null
 *
 * @return
 */
public static List<WalkStep> generateWalkSteps(Graph graph, State[] states, WalkStep previous, Locale requestedLocale) {
    List<WalkStep> steps = new ArrayList<WalkStep>();
    WalkStep step = null;
    // distance used for appending elevation profiles
    double lastAngle = 0, distance = 0;
    // track whether we are in a roundabout, and if so the exit number
    int roundaboutExit = 0;
    String roundaboutPreviousStreet = null;
    State onBikeRentalState = null, offBikeRentalState = null;
    // Check if this leg is a SimpleTransfer; if so, rebuild state array based on stored transfer edges
    if (states.length == 2 && states[1].getBackEdge() instanceof SimpleTransfer) {
        SimpleTransfer transferEdge = ((SimpleTransfer) states[1].getBackEdge());
        List<Edge> transferEdges = transferEdge.getEdges();
        if (transferEdges != null) {
            // Create a new initial state. Some parameters may have change along the way, copy them from the first state
            StateEditor se = new StateEditor(states[0].getOptions(), transferEdges.get(0).getFromVertex());
            se.setNonTransitOptionsFromState(states[0]);
            State s = se.makeState();
            ArrayList<State> transferStates = new ArrayList<>();
            transferStates.add(s);
            for (Edge e : transferEdges) {
                s = e.traverse(s);
                transferStates.add(s);
            }
            states = transferStates.toArray(new State[transferStates.size()]);
        }
    }
    for (int i = 0; i < states.length - 1; i++) {
        State backState = states[i];
        State forwardState = states[i + 1];
        Edge edge = forwardState.getBackEdge();
        if (edge instanceof RentABikeOnEdge)
            onBikeRentalState = forwardState;
        if (edge instanceof RentABikeOffEdge)
            offBikeRentalState = forwardState;
        boolean createdNewStep = false, disableZagRemovalForThisStep = false;
        if (edge instanceof FreeEdge) {
            continue;
        }
        if (forwardState.getBackMode() == null || !forwardState.getBackMode().isOnStreetNonTransit()) {
            // ignore STLs and the like
            continue;
        }
        Geometry geom = edge.getGeometry();
        if (geom == null) {
            continue;
        }
        // before or will come after
        if (edge instanceof ElevatorAlightEdge) {
            // don't care what came before or comes after
            step = createWalkStep(graph, forwardState, requestedLocale);
            createdNewStep = true;
            disableZagRemovalForThisStep = true;
            // tell the user where to get off the elevator using the exit notation, so the
            // i18n interface will say 'Elevator to <exit>'
            // what happens is that the webapp sees name == null and ignores that, and it sees
            // exit != null and uses to <exit>
            // the floor name is the AlightEdge name
            // reset to avoid confusion with 'Elevator on floor 1 to floor 1'
            step.streetName = ((ElevatorAlightEdge) edge).getName(requestedLocale);
            step.relativeDirection = RelativeDirection.ELEVATOR;
            steps.add(step);
            continue;
        }
        String streetName = edge.getName(requestedLocale);
        int idx = streetName.indexOf('(');
        String streetNameNoParens;
        if (idx > 0)
            streetNameNoParens = streetName.substring(0, idx - 1);
        else
            streetNameNoParens = streetName;
        if (step == null) {
            // first step
            step = createWalkStep(graph, forwardState, requestedLocale);
            createdNewStep = true;
            steps.add(step);
            double thisAngle = DirectionUtils.getFirstAngle(geom);
            if (previous == null) {
                step.setAbsoluteDirection(thisAngle);
                step.relativeDirection = RelativeDirection.DEPART;
            } else {
                step.setDirections(previous.angle, thisAngle, false);
            }
            // new step, set distance to length of first edge
            distance = edge.getDistance();
        } else if (((step.streetName != null && !step.streetNameNoParens().equals(streetNameNoParens)) && (!step.bogusName || !edge.hasBogusName())) || // went on to or off of a roundabout
        edge.isRoundabout() != (roundaboutExit > 0) || isLink(edge) && !isLink(backState.getBackEdge())) {
            // Street name has changed, or we've gone on to or off of a roundabout.
            if (roundaboutExit > 0) {
                // if we were just on a roundabout,
                // make note of which exit was taken in the existing step
                // ordinal numbers from
                step.exit = Integer.toString(roundaboutExit);
                if (streetNameNoParens.equals(roundaboutPreviousStreet)) {
                    step.stayOn = true;
                }
                roundaboutExit = 0;
            }
            /* start a new step */
            step = createWalkStep(graph, forwardState, requestedLocale);
            createdNewStep = true;
            steps.add(step);
            if (edge.isRoundabout()) {
                // indicate that we are now on a roundabout
                // and use one-based exit numbering
                roundaboutExit = 1;
                roundaboutPreviousStreet = backState.getBackEdge().getName(requestedLocale);
                idx = roundaboutPreviousStreet.indexOf('(');
                if (idx > 0)
                    roundaboutPreviousStreet = roundaboutPreviousStreet.substring(0, idx - 1);
            }
            double thisAngle = DirectionUtils.getFirstAngle(geom);
            step.setDirections(lastAngle, thisAngle, edge.isRoundabout());
            // new step, set distance to length of first edge
            distance = edge.getDistance();
        } else {
            /* street name has not changed */
            double thisAngle = DirectionUtils.getFirstAngle(geom);
            RelativeDirection direction = WalkStep.getRelativeDirection(lastAngle, thisAngle, edge.isRoundabout());
            boolean optionsBefore = backState.multipleOptionsBefore();
            if (edge.isRoundabout()) {
                // we are on a roundabout, and have already traversed at least one edge of it.
                if (optionsBefore) {
                    // increment exit count if we passed one.
                    roundaboutExit += 1;
                }
            }
            if (edge.isRoundabout() || direction == RelativeDirection.CONTINUE) {
            // we are continuing almost straight, or continuing along a roundabout.
            // just append elevation info onto the existing step.
            } else {
                // we are not on a roundabout, and not continuing straight through.
                // figure out if there were other plausible turn options at the last
                // intersection
                // to see if we should generate a "left to continue" instruction.
                boolean shouldGenerateContinue = false;
                if (edge instanceof StreetEdge) {
                    // the next edges will be PlainStreetEdges, we hope
                    double angleDiff = getAbsoluteAngleDiff(thisAngle, lastAngle);
                    for (Edge alternative : backState.getVertex().getOutgoingStreetEdges()) {
                        if (alternative.getName(requestedLocale).equals(streetName)) {
                            // are usually caused by street splits
                            continue;
                        }
                        double altAngle = DirectionUtils.getFirstAngle(alternative.getGeometry());
                        double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle);
                        if (angleDiff > Math.PI / 4 || altAngleDiff - angleDiff < Math.PI / 16) {
                            shouldGenerateContinue = true;
                            break;
                        }
                    }
                } else {
                    double angleDiff = getAbsoluteAngleDiff(lastAngle, thisAngle);
                    // FIXME: this code might be wrong with the removal of the edge-based graph
                    State twoStatesBack = backState.getBackState();
                    Vertex backVertex = twoStatesBack.getVertex();
                    for (Edge alternative : backVertex.getOutgoingStreetEdges()) {
                        List<Edge> alternatives = alternative.getToVertex().getOutgoingStreetEdges();
                        if (alternatives.size() == 0) {
                            // this is not an alternative
                            continue;
                        }
                        alternative = alternatives.get(0);
                        if (alternative.getName(requestedLocale).equals(streetName)) {
                            // are usually caused by street splits
                            continue;
                        }
                        double altAngle = DirectionUtils.getFirstAngle(alternative.getGeometry());
                        double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle);
                        if (angleDiff > Math.PI / 4 || altAngleDiff - angleDiff < Math.PI / 16) {
                            shouldGenerateContinue = true;
                            break;
                        }
                    }
                }
                if (shouldGenerateContinue) {
                    // turn to stay on same-named street
                    step = createWalkStep(graph, forwardState, requestedLocale);
                    createdNewStep = true;
                    steps.add(step);
                    step.setDirections(lastAngle, thisAngle, false);
                    step.stayOn = true;
                    // new step, set distance to length of first edge
                    distance = edge.getDistance();
                }
            }
        }
        State exitState = backState;
        Edge exitEdge = exitState.getBackEdge();
        while (exitEdge instanceof FreeEdge) {
            exitState = exitState.getBackState();
            exitEdge = exitState.getBackEdge();
        }
        if (exitState.getVertex() instanceof ExitVertex) {
            step.exit = ((ExitVertex) exitState.getVertex()).getExitName();
        }
        if (createdNewStep && !disableZagRemovalForThisStep && forwardState.getBackMode() == backState.getBackMode()) {
            // check last three steps for zag
            int last = steps.size() - 1;
            if (last >= 2) {
                WalkStep threeBack = steps.get(last - 2);
                WalkStep twoBack = steps.get(last - 1);
                WalkStep lastStep = steps.get(last);
                if (twoBack.distance < MAX_ZAG_DISTANCE && lastStep.streetNameNoParens().equals(threeBack.streetNameNoParens())) {
                    if (((lastStep.relativeDirection == RelativeDirection.RIGHT || lastStep.relativeDirection == RelativeDirection.HARD_RIGHT) && (twoBack.relativeDirection == RelativeDirection.RIGHT || twoBack.relativeDirection == RelativeDirection.HARD_RIGHT)) || ((lastStep.relativeDirection == RelativeDirection.LEFT || lastStep.relativeDirection == RelativeDirection.HARD_LEFT) && (twoBack.relativeDirection == RelativeDirection.LEFT || twoBack.relativeDirection == RelativeDirection.HARD_LEFT))) {
                        // in this case, we have two left turns or two right turns in quick
                        // succession; this is probably a U-turn.
                        steps.remove(last - 1);
                        lastStep.distance += twoBack.distance;
                        // A U-turn to the left, typical in the US.
                        if (lastStep.relativeDirection == RelativeDirection.LEFT || lastStep.relativeDirection == RelativeDirection.HARD_LEFT)
                            lastStep.relativeDirection = RelativeDirection.UTURN_LEFT;
                        else
                            lastStep.relativeDirection = RelativeDirection.UTURN_RIGHT;
                        // in this case, we're definitely staying on the same street
                        // (since it's zag removal, the street names are the same)
                        lastStep.stayOn = true;
                    } else {
                        // What is a zag? TODO write meaningful documentation for this.
                        // It appears to mean simplifying out several rapid turns in succession
                        // from the description.
                        // total hack to remove zags.
                        steps.remove(last);
                        steps.remove(last - 1);
                        step = threeBack;
                        step.distance += twoBack.distance;
                        distance += step.distance;
                        if (twoBack.elevation != null) {
                            if (step.elevation == null) {
                                step.elevation = twoBack.elevation;
                            } else {
                                for (P2<Double> d : twoBack.elevation) {
                                    step.elevation.add(new P2<Double>(d.first + step.distance, d.second));
                                }
                            }
                        }
                    }
                }
            }
        } else {
            if (!createdNewStep && step.elevation != null) {
                List<P2<Double>> s = encodeElevationProfile(edge, distance, backState.getOptions().geoidElevation ? -graph.ellipsoidToGeoidDifference : 0);
                if (step.elevation != null && step.elevation.size() > 0) {
                    step.elevation.addAll(s);
                } else {
                    step.elevation = s;
                }
            }
            distance += edge.getDistance();
        }
        // increment the total length for this step
        step.distance += edge.getDistance();
        step.addAlerts(graph.streetNotesService.getNotes(forwardState), requestedLocale);
        lastAngle = DirectionUtils.getLastAngle(geom);
        step.edges.add(edge);
    }
    // add bike rental information if applicable
    if (onBikeRentalState != null && !steps.isEmpty()) {
        steps.get(steps.size() - 1).bikeRentalOnStation = new BikeRentalStationInfo((BikeRentalStationVertex) onBikeRentalState.getBackEdge().getToVertex());
    }
    if (offBikeRentalState != null && !steps.isEmpty()) {
        steps.get(0).bikeRentalOffStation = new BikeRentalStationInfo((BikeRentalStationVertex) offBikeRentalState.getBackEdge().getFromVertex());
    }
    return steps;
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) LineString(com.vividsolutions.jts.geom.LineString) P2(org.opentripplanner.common.model.P2) BikeRentalStationInfo(org.opentripplanner.profile.BikeRentalStationInfo) Geometry(com.vividsolutions.jts.geom.Geometry) Edge(org.opentripplanner.routing.graph.Edge)

Example 27 with Edge

use of org.opentripplanner.routing.graph.Edge in project OpenTripPlanner by opentripplanner.

the class CheckGeometryModule method buildGraph.

@Override
public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
    for (Vertex gv : graph.getVertices()) {
        if (Double.isNaN(gv.getCoordinate().x) || Double.isNaN(gv.getCoordinate().y)) {
            LOG.warn("Vertex " + gv + " has NaN location; this will cause doom.");
            LOG.warn(graph.addBuilderAnnotation(new BogusVertexGeometry(gv)));
        }
        // TODO: This was filtered to EdgeNarratives before EdgeNarrative removal
        for (Edge e : gv.getOutgoing()) {
            Geometry g = e.getGeometry();
            if (g == null) {
                continue;
            }
            for (Coordinate c : g.getCoordinates()) {
                if (Double.isNaN(c.x) || Double.isNaN(c.y)) {
                    LOG.warn(graph.addBuilderAnnotation(new BogusEdgeGeometry(e)));
                }
            }
            if (e instanceof HopEdge) {
                Coordinate edgeStartCoord = e.getFromVertex().getCoordinate();
                Coordinate edgeEndCoord = e.getToVertex().getCoordinate();
                Coordinate[] geometryCoordinates = g.getCoordinates();
                if (geometryCoordinates.length < 2) {
                    LOG.warn(graph.addBuilderAnnotation(new BogusEdgeGeometry(e)));
                    continue;
                }
                Coordinate geometryStartCoord = geometryCoordinates[0];
                Coordinate geometryEndCoord = geometryCoordinates[geometryCoordinates.length - 1];
                if (SphericalDistanceLibrary.distance(edgeStartCoord, geometryStartCoord) > MAX_VERTEX_SHAPE_ERROR) {
                    LOG.warn(graph.addBuilderAnnotation(new VertexShapeError(e)));
                } else if (SphericalDistanceLibrary.distance(edgeEndCoord, geometryEndCoord) > MAX_VERTEX_SHAPE_ERROR) {
                    LOG.warn(graph.addBuilderAnnotation(new VertexShapeError(e)));
                }
            }
        }
    }
}
Also used : BogusEdgeGeometry(org.opentripplanner.graph_builder.annotation.BogusEdgeGeometry) BogusVertexGeometry(org.opentripplanner.graph_builder.annotation.BogusVertexGeometry) Geometry(com.vividsolutions.jts.geom.Geometry) Vertex(org.opentripplanner.routing.graph.Vertex) HopEdge(org.opentripplanner.routing.edgetype.HopEdge) Coordinate(com.vividsolutions.jts.geom.Coordinate) BogusEdgeGeometry(org.opentripplanner.graph_builder.annotation.BogusEdgeGeometry) VertexShapeError(org.opentripplanner.graph_builder.annotation.VertexShapeError) HopEdge(org.opentripplanner.routing.edgetype.HopEdge) Edge(org.opentripplanner.routing.graph.Edge) BogusVertexGeometry(org.opentripplanner.graph_builder.annotation.BogusVertexGeometry)

Example 28 with Edge

use of org.opentripplanner.routing.graph.Edge in project OpenTripPlanner by opentripplanner.

the class TestUnroutable method testOnBoardRouting.

/**
 * Search for a path across the Willamette river. This OSM data includes a bridge that is not yet built and is
 * therefore tagged highway=construction.
 * TODO also test unbuilt, proposed, raceways etc.
 */
public void testOnBoardRouting() throws Exception {
    RoutingRequest options = new RoutingRequest();
    Vertex from = graph.getVertex("osm:node:2003617278");
    Vertex to = graph.getVertex("osm:node:40446276");
    options.setRoutingContext(graph, from, to);
    options.setMode(TraverseMode.BICYCLE);
    ShortestPathTree spt = aStar.getShortestPathTree(options);
    GraphPath path = spt.getPath(to, false);
    // is filtered out, thus the null check.
    if (path != null) {
        for (Edge edge : path.edges) {
            assertFalse("Path should not use the as-yet unbuilt Tilikum Crossing bridge.", "Tilikum Crossing".equals(edge.getName()));
        }
    }
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) GraphPath(org.opentripplanner.routing.spt.GraphPath) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) Edge(org.opentripplanner.routing.graph.Edge)

Example 29 with Edge

use of org.opentripplanner.routing.graph.Edge in project OpenTripPlanner by opentripplanner.

the class TriangleInequalityTest method checkTriangleInequality.

private void checkTriangleInequality(TraverseModeSet traverseModes) {
    assertNotNull(start);
    assertNotNull(end);
    RoutingRequest prototypeOptions = new RoutingRequest();
    // All reluctance terms are 1.0 so that duration is monotonically increasing in weight.
    prototypeOptions.stairsReluctance = (1.0);
    prototypeOptions.setWalkReluctance(1.0);
    prototypeOptions.turnReluctance = (1.0);
    prototypeOptions.carSpeed = 1.0;
    prototypeOptions.walkSpeed = 1.0;
    prototypeOptions.bikeSpeed = 1.0;
    prototypeOptions.traversalCostModel = (new ConstantIntersectionTraversalCostModel(10.0));
    prototypeOptions.dominanceFunction = new DominanceFunction.EarliestArrival();
    if (traverseModes != null) {
        prototypeOptions.setModes(traverseModes);
    }
    RoutingRequest options = prototypeOptions.clone();
    options.setRoutingContext(_graph, start, end);
    AStar aStar = new AStar();
    ShortestPathTree tree = aStar.getShortestPathTree(options);
    GraphPath path = tree.getPath(end, false);
    options.cleanup();
    assertNotNull(path);
    double startEndWeight = path.getWeight();
    int startEndDuration = path.getDuration();
    assertTrue(startEndWeight > 0);
    assertEquals(startEndWeight, (double) startEndDuration, 1.0 * path.edges.size());
    // Try every vertex in the graph as an intermediate.
    boolean violated = false;
    for (Vertex intermediate : _graph.getVertices()) {
        if (intermediate == start || intermediate == end) {
            continue;
        }
        GraphPath startIntermediatePath = getPath(aStar, prototypeOptions, null, start, intermediate);
        if (startIntermediatePath == null) {
            continue;
        }
        Edge back = startIntermediatePath.states.getLast().getBackEdge();
        GraphPath intermediateEndPath = getPath(aStar, prototypeOptions, back, intermediate, end);
        if (intermediateEndPath == null) {
            continue;
        }
        double startIntermediateWeight = startIntermediatePath.getWeight();
        int startIntermediateDuration = startIntermediatePath.getDuration();
        double intermediateEndWeight = intermediateEndPath.getWeight();
        int intermediateEndDuration = intermediateEndPath.getDuration();
        // TODO(flamholz): fix traversal so that there's no rounding at the second resolution.
        assertEquals(startIntermediateWeight, (double) startIntermediateDuration, 1.0 * startIntermediatePath.edges.size());
        assertEquals(intermediateEndWeight, (double) intermediateEndDuration, 1.0 * intermediateEndPath.edges.size());
        double diff = startIntermediateWeight + intermediateEndWeight - startEndWeight;
        if (diff < -0.01) {
            System.out.println("Triangle inequality violated - diff = " + diff);
            violated = true;
        }
    // assertTrue(startIntermediateDuration + intermediateEndDuration >=
    // startEndDuration);
    }
    assertFalse(violated);
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) AStar(org.opentripplanner.routing.algorithm.AStar) GraphPath(org.opentripplanner.routing.spt.GraphPath) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) ConstantIntersectionTraversalCostModel(org.opentripplanner.routing.core.ConstantIntersectionTraversalCostModel) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction) Edge(org.opentripplanner.routing.graph.Edge)

Example 30 with Edge

use of org.opentripplanner.routing.graph.Edge in project OpenTripPlanner by opentripplanner.

the class TestHalfEdges method testNetworkLinker.

@Test
public void testNetworkLinker() {
    int numVerticesBefore = graph.getVertices().size();
    StreetLinkerModule ttsnm = new StreetLinkerModule();
    ttsnm.buildGraph(graph, new HashMap<Class<?>, Object>());
    int numVerticesAfter = graph.getVertices().size();
    assertEquals(4, numVerticesAfter - numVerticesBefore);
    Collection<Edge> outgoing = station1.getOutgoing();
    assertTrue(outgoing.size() == 2);
    Edge edge = outgoing.iterator().next();
    Vertex midpoint = edge.getToVertex();
    assertTrue(Math.abs(midpoint.getCoordinate().y - 40.01) < 0.00000001);
    outgoing = station2.getOutgoing();
    assertTrue(outgoing.size() == 2);
    edge = outgoing.iterator().next();
    Vertex station2point = edge.getToVertex();
    assertTrue(Math.abs(station2point.getCoordinate().x - -74.002) < 0.00000001);
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) IntersectionVertex(org.opentripplanner.routing.vertextype.IntersectionVertex) StreetLinkerModule(org.opentripplanner.graph_builder.module.StreetLinkerModule) TemporaryFreeEdge(org.opentripplanner.routing.edgetype.TemporaryFreeEdge) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) Edge(org.opentripplanner.routing.graph.Edge) Test(org.junit.Test)

Aggregations

Edge (org.opentripplanner.routing.graph.Edge)113 Vertex (org.opentripplanner.routing.graph.Vertex)61 StreetEdge (org.opentripplanner.routing.edgetype.StreetEdge)53 IntersectionVertex (org.opentripplanner.routing.vertextype.IntersectionVertex)26 HashSet (java.util.HashSet)23 State (org.opentripplanner.routing.core.State)22 Coordinate (com.vividsolutions.jts.geom.Coordinate)19 Graph (org.opentripplanner.routing.graph.Graph)19 RoutingRequest (org.opentripplanner.routing.core.RoutingRequest)18 Test (org.junit.Test)17 ShortestPathTree (org.opentripplanner.routing.spt.ShortestPathTree)17 TransitStop (org.opentripplanner.routing.vertextype.TransitStop)17 ArrayList (java.util.ArrayList)16 LineString (com.vividsolutions.jts.geom.LineString)15 GraphPath (org.opentripplanner.routing.spt.GraphPath)15 StreetVertex (org.opentripplanner.routing.vertextype.StreetVertex)12 PathwayEdge (org.opentripplanner.routing.edgetype.PathwayEdge)11 Geometry (com.vividsolutions.jts.geom.Geometry)9 Stop (org.onebusaway.gtfs.model.Stop)9 TripPattern (org.opentripplanner.routing.edgetype.TripPattern)9