Search in sources :

Example 6 with AStar

use of org.opentripplanner.routing.algorithm.AStar in project OpenTripPlanner by opentripplanner.

the class GraphIndex method findClosestStopsByWalking.

/* TODO: an almost similar function exists in ProfileRouter, combine these.
    *  Should these live in a separate class? */
public List<StopAndDistance> findClosestStopsByWalking(double lat, double lon, int radius) {
    // Make a normal OTP routing request so we can traverse edges and use GenericAStar
    // TODO make a function that builds normal routing requests from profile requests
    RoutingRequest rr = new RoutingRequest(TraverseMode.WALK);
    rr.from = new GenericLocation(lat, lon);
    // FIXME requires destination to be set, not necessary for analyst
    rr.to = new GenericLocation(lat, lon);
    rr.batch = true;
    rr.setRoutingContext(graph);
    rr.walkSpeed = 1;
    rr.dominanceFunction = new DominanceFunction.LeastWalk();
    // RR dateTime defaults to currentTime.
    // If elapsed time is not capped, searches are very slow.
    rr.worstTime = (rr.dateTime + radius);
    AStar astar = new AStar();
    rr.setNumItineraries(1);
    StopFinderTraverseVisitor visitor = new StopFinderTraverseVisitor();
    astar.setTraverseVisitor(visitor);
    // timeout in seconds
    astar.getShortestPathTree(rr, 1);
    // Destroy the routing context, to clean up the temporary edges & vertices
    rr.rctx.destroy();
    return visitor.stopsFound;
}
Also used : AStar(org.opentripplanner.routing.algorithm.AStar) GenericLocation(org.opentripplanner.common.model.GenericLocation) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction)

Example 7 with AStar

use of org.opentripplanner.routing.algorithm.AStar 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 8 with AStar

use of org.opentripplanner.routing.algorithm.AStar in project OpenTripPlanner by opentripplanner.

the class TestShapefileStreetGraphBuilderImpl method testBasic.

@Test
public void testBasic() throws Exception {
    Graph gg = new Graph();
    URL resource = getClass().getResource("nyc_streets/streets.shp");
    File file = null;
    if (resource != null) {
        file = new File(resource.getFile());
    }
    if (file == null || !file.exists()) {
        System.out.println("No New York City basemap; skipping; see comment here for details");
        /*
             * This test requires the New York City base map. Place it among the source 
             * resources and Eclipse should automatically copy it over to the target directory.
             * Once you have prepared these files, you may need to 'refresh' in Eclipse's package 
             * explorer to force Eclipse to notice the new resources.
             * 
             * Recent versions of this map are available only in Arcview Geodatabase format.
             * For conversion to a Shapefile, you will need the archived MapInfo version at:
             * http://www.nyc.gov/html/dcp/html/bytes/bytesarchive.shtml#lion
             * Download the MapInfo file of Lion version 10B. 
             * 
             * This must then be converted to a ShapeFile as follows:
             * cd opentripplanner-graph-builder/src/test/resources/org/opentripplanner/graph_builder/module/shapefile
             * mkdir nyc_streets       (this is where we will store the shapefile)
             * unzip nyc_lion10ami.zip (this should place zipfile contents in a ./lion directory)
             * ogr2ogr -f 'ESRI Shapefile' nyc_streets/streets.shp lion/MNLION1.tab 
             * ogr2ogr -update -append -f 'ESRI Shapefile' nyc_streets lion/SILION1.tab -nln streets 
             * ogr2ogr -update -append -f 'ESRI Shapefile' nyc_streets lion/QNLION1.tab -nln streets 
             * ogr2ogr -update -append -f 'ESRI Shapefile' nyc_streets lion/BKLION1.tab -nln streets 
             * ogr2ogr -update -append -f 'ESRI Shapefile' nyc_streets lion/BXLION1.tab -nln streets
             * 
             * Testing also requires NYC Subway data in GTFS in the same location: 
             * wget http://data.topplabs.org/data/mta_nyct_subway/subway.zip
             */
        return;
    }
    ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file);
    ShapefileStreetSchema schema = new ShapefileStreetSchema();
    schema.setIdAttribute("SegmentID");
    schema.setNameAttribute("Street");
    /* only featuretyp=0 are streets */
    CaseBasedBooleanConverter selector = new CaseBasedBooleanConverter("FeatureTyp", false);
    HashMap<String, Boolean> streets = new HashMap<String, Boolean>();
    streets.put("0", true);
    selector.setValues(streets);
    schema.setFeatureSelector(selector);
    /* street directions */
    CaseBasedTraversalPermissionConverter perms = new CaseBasedTraversalPermissionConverter("TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE);
    perms.addPermission("W", StreetTraversalPermission.ALL, StreetTraversalPermission.PEDESTRIAN);
    perms.addPermission("A", StreetTraversalPermission.PEDESTRIAN, StreetTraversalPermission.ALL);
    perms.addPermission("T", StreetTraversalPermission.ALL, StreetTraversalPermission.ALL);
    schema.setPermissionConverter(perms);
    ShapefileStreetModule loader = new ShapefileStreetModule();
    loader.setFeatureSourceFactory(factory);
    loader.setSchema(schema);
    loader.buildGraph(gg, new HashMap<Class<?>, Object>());
    // find start and end vertices
    Vertex start = null;
    Vertex end = null;
    Vertex carlton = null;
    Coordinate vanderbiltAtPark = new Coordinate(-73.969178, 40.676785);
    Coordinate grandAtLafayette = new Coordinate(-73.999095, 40.720005);
    Coordinate carltonAtPark = new Coordinate(-73.972347, 40.677447);
    for (Vertex v : gg.getVertices()) {
        if (v.getCoordinate().distance(vanderbiltAtPark) < 0.00005) {
            /* we need the correct vanderbilt at park.  In this case,
                 * that's the one facing west on vanderbilt.
                 */
            int numParks = 0;
            int numCarltons = 0;
            for (Edge e : v.getOutgoing()) {
                if (e.getToVertex().getName().contains("PARK")) {
                    numParks++;
                }
                if (e.getToVertex().getName().contains("CARLTON")) {
                    numCarltons++;
                }
            }
            if (numCarltons != 2 || numParks != 1) {
                continue;
            }
            start = v;
        } else if (v.getCoordinate().distance(grandAtLafayette) < 0.0001) {
            end = v;
        } else if (v.getCoordinate().distance(carltonAtPark) < 0.00005) {
            /* we need the correct carlton at park.  In this case,
                 * that's the one facing west.
                 */
            int numFlatbushes = 0;
            int numParks = 0;
            for (Edge e : v.getOutgoing()) {
                if (e.getToVertex().getName().contains("FLATBUSH")) {
                    numFlatbushes++;
                }
                if (e.getToVertex().getName().contains("PARK")) {
                    numParks++;
                }
            }
            if (numFlatbushes != 2 || numParks != 1) {
                continue;
            }
            carlton = v;
        }
    }
    assertNotNull(start);
    assertNotNull(end);
    assertNotNull(carlton);
    assertEquals(3, start.getDegreeOut());
    assertEquals(3, start.getDegreeIn());
    AStar aStar = new AStar();
    RoutingRequest opt = new RoutingRequest();
    opt.setRoutingContext(gg, start, end);
    ShortestPathTree spt = aStar.getShortestPathTree(opt);
    assertNotNull(spt);
    // test that the option to walk bikes on the first or last segment works
    opt = new RoutingRequest(new TraverseModeSet(TraverseMode.BICYCLE));
    // Real live cyclists tell me that they would prefer to ride around the long way than to
    // walk their bikes the short way.  If we slow down the default biking speed, that will
    // force a change in preferences.
    opt.bikeSpeed = 2;
    opt.setRoutingContext(gg, start, carlton);
    spt = aStar.getShortestPathTree(opt);
    assertNotNull(spt);
/* commented out as bike walking is not supported */
/*
        GraphPath path = spt.getPath(carlton.vertex);
        assertNotNull(path);
        assertTrue(path.edges.size() <= 3);

        wo.setArriveBy(true);
        spt = AStar.getShortestPathTreeBack(gg, start.vertex, carlton.vertex, new State(0), wo);
        assertNotNull(spt);
        
        path = spt.getPath(carlton.vertex);
        assertTrue(path.edges.size() <= 3);
         */
}
Also used : Vertex(org.opentripplanner.routing.graph.Vertex) HashMap(java.util.HashMap) AStar(org.opentripplanner.routing.algorithm.AStar) TraverseModeSet(org.opentripplanner.routing.core.TraverseModeSet) URL(java.net.URL) Graph(org.opentripplanner.routing.graph.Graph) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) Coordinate(com.vividsolutions.jts.geom.Coordinate) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) File(java.io.File) Edge(org.opentripplanner.routing.graph.Edge) Test(org.junit.Test)

Example 9 with AStar

use of org.opentripplanner.routing.algorithm.AStar in project OpenTripPlanner by opentripplanner.

the class AddTripPatternTest method testStopLinking.

/**
 * Make sure that stops are properly linked into the graph
 */
@Test
public void testStopLinking() throws Exception {
    AddTripPattern atp = getAddTripPattern(RouteSelector.BROAD_HIGH);
    atp.timetables.add(getTimetable(true));
    // get a graph
    Graph g = buildGraphNoTransit();
    link(g);
    g.index(new DefaultStreetVertexIndexFactory());
    // materialize the trip pattern
    atp.materialize(g);
    // there should be five stops because one point is not a stop
    assertEquals(5, atp.temporaryStops.length);
    // they should all be linked into the graph
    for (int i = 0; i < atp.temporaryStops.length; i++) {
        assertNotNull(atp.temporaryStops[i].sample);
        assertNotNull(atp.temporaryStops[i].sample.v0);
        assertNotNull(atp.temporaryStops[i].sample.v1);
    }
    // no services running: not needed for trips added on the fly.
    TimeWindow window = new TimeWindow(7 * 3600, 9 * 3600, new BitSet(), DayOfWeek.WEDNESDAY);
    Scenario scenario = new Scenario(0);
    scenario.modifications = Lists.newArrayList(atp);
    ProfileRequest req = new ProfileRequest();
    req.scenario = scenario;
    req.boardingAssumption = RaptorWorkerTimetable.BoardingAssumption.WORST_CASE;
    RaptorWorkerData data = new RaptorWorkerData(g, window, req);
    assertEquals(5, data.nStops);
    // make sure we can find the stops
    AStar aStar = new AStar();
    RoutingRequest rr = new RoutingRequest(TraverseMode.WALK);
    rr.from = new GenericLocation(39.963417, -82.980799);
    rr.batch = true;
    rr.setRoutingContext(g);
    rr.batch = true;
    ShortestPathTree spt = aStar.getShortestPathTree(rr);
    TIntIntMap stops = data.findStopsNear(spt, g, false, 1.3f);
    // we should have found stops
    assertFalse(stops.isEmpty());
    // ensure that the times made it into the data
    // This assumes worst-case departure, and the first worst departure is 10:30 after the service
    // starts running (dwell + headway)
    assertEquals(4 * 3600 + 600 + 30, data.timetablesForPattern.get(0).getFrequencyDeparture(0, 0, 39 * 360, -1, null));
}
Also used : BitSet(java.util.BitSet) AStar(org.opentripplanner.routing.algorithm.AStar) DefaultStreetVertexIndexFactory(org.opentripplanner.routing.impl.DefaultStreetVertexIndexFactory) TIntIntMap(gnu.trove.map.TIntIntMap) FakeGraph(org.opentripplanner.graph_builder.module.FakeGraph) Graph(org.opentripplanner.routing.graph.Graph) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) GenericLocation(org.opentripplanner.common.model.GenericLocation) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) Test(org.junit.Test)

Example 10 with AStar

use of org.opentripplanner.routing.algorithm.AStar in project OpenTripPlanner by opentripplanner.

the class AddTripPatternTest method testTimetableTrips.

/**
 * Test adding trips with a timetable rather than frequencies
 */
@Test
public void testTimetableTrips() throws Exception {
    AddTripPattern atp = getAddTripPattern(RouteSelector.BROAD_HIGH);
    atp.timetables.add(getTimetable(false));
    // get a graph
    Graph g = buildGraphNoTransit();
    link(g);
    g.index(new DefaultStreetVertexIndexFactory());
    // materialize the trip pattern
    atp.materialize(g);
    // there should be five stops because one point is not a stop
    assertEquals(5, atp.temporaryStops.length);
    // they should all be linked into the graph
    for (int i = 0; i < atp.temporaryStops.length; i++) {
        assertNotNull(atp.temporaryStops[i].sample);
        assertNotNull(atp.temporaryStops[i].sample.v0);
        assertNotNull(atp.temporaryStops[i].sample.v1);
    }
    // no services running: not needed for trips added on the fly.
    TimeWindow window = new TimeWindow(7 * 3600, 9 * 3600, new BitSet(), DayOfWeek.WEDNESDAY);
    Scenario scenario = new Scenario(0);
    scenario.modifications = Lists.newArrayList(atp);
    ProfileRequest req = new ProfileRequest();
    req.scenario = scenario;
    req.boardingAssumption = RaptorWorkerTimetable.BoardingAssumption.WORST_CASE;
    RaptorWorkerData data = new RaptorWorkerData(g, window, req);
    assertEquals(5, data.nStops);
    // make sure we can find the stops
    AStar aStar = new AStar();
    RoutingRequest rr = new RoutingRequest(TraverseMode.WALK);
    rr.from = new GenericLocation(39.963417, -82.980799);
    rr.batch = true;
    rr.setRoutingContext(g);
    rr.batch = true;
    ShortestPathTree spt = aStar.getShortestPathTree(rr);
    TIntIntMap stops = data.findStopsNear(spt, g, false, 1.3f);
    // we should have found stops
    assertFalse(stops.isEmpty());
    // ensure that the times made it into the data
    // This is after the first dwell time has been applied
    assertEquals(7 * 3600 + 30, data.timetablesForPattern.get(0).getDeparture(0, 0));
}
Also used : BitSet(java.util.BitSet) AStar(org.opentripplanner.routing.algorithm.AStar) DefaultStreetVertexIndexFactory(org.opentripplanner.routing.impl.DefaultStreetVertexIndexFactory) TIntIntMap(gnu.trove.map.TIntIntMap) FakeGraph(org.opentripplanner.graph_builder.module.FakeGraph) Graph(org.opentripplanner.routing.graph.Graph) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) GenericLocation(org.opentripplanner.common.model.GenericLocation) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) Test(org.junit.Test)

Aggregations

AStar (org.opentripplanner.routing.algorithm.AStar)17 RoutingRequest (org.opentripplanner.routing.core.RoutingRequest)15 ShortestPathTree (org.opentripplanner.routing.spt.ShortestPathTree)10 GenericLocation (org.opentripplanner.common.model.GenericLocation)9 DominanceFunction (org.opentripplanner.routing.spt.DominanceFunction)9 State (org.opentripplanner.routing.core.State)4 TraverseModeSet (org.opentripplanner.routing.core.TraverseModeSet)4 Graph (org.opentripplanner.routing.graph.Graph)4 Coordinate (com.vividsolutions.jts.geom.Coordinate)3 TIntIntMap (gnu.trove.map.TIntIntMap)3 Test (org.junit.Test)3 Edge (org.opentripplanner.routing.graph.Edge)3 DefaultStreetVertexIndexFactory (org.opentripplanner.routing.impl.DefaultStreetVertexIndexFactory)3 File (java.io.File)2 BitSet (java.util.BitSet)2 QualifiedModeSet (org.opentripplanner.api.parameter.QualifiedModeSet)2 FakeGraph (org.opentripplanner.graph_builder.module.FakeGraph)2 Vertex (org.opentripplanner.routing.graph.Vertex)2 GraphPath (org.opentripplanner.routing.spt.GraphPath)2 TransitStop (org.opentripplanner.routing.vertextype.TransitStop)2