Search in sources :

Example 6 with LocationIndex

use of com.graphhopper.storage.index.LocationIndex in project graphhopper by graphhopper.

the class AbstractRoutingAlgorithmTester method calcPathViaQuery.

Path calcPathViaQuery(Weighting weighting, GraphHopperStorage ghStorage, double fromLat, double fromLon, double toLat, double toLon) {
    LocationIndex index = new LocationIndexTree(ghStorage, new RAMDirectory());
    index.prepareIndex();
    QueryResult from = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES);
    QueryResult to = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES);
    // correct order for CH: in factory do prepare and afterwards wrap in query graph
    AlgorithmOptions opts = AlgorithmOptions.start().weighting(weighting).build();
    RoutingAlgorithmFactory factory = createFactory(ghStorage, opts);
    QueryGraph qGraph = new QueryGraph(getGraph(ghStorage, weighting)).lookup(from, to);
    return factory.createAlgo(qGraph, opts).calcPath(from.getClosestNode(), to.getClosestNode());
}
Also used : QueryResult(com.graphhopper.storage.index.QueryResult) LocationIndex(com.graphhopper.storage.index.LocationIndex) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree)

Example 7 with LocationIndex

use of com.graphhopper.storage.index.LocationIndex in project graphhopper by graphhopper.

the class GraphHopperAPITest method testConcurrentGraphChange.

@Test
public void testConcurrentGraphChange() throws InterruptedException {
    final GraphHopperStorage graph = new GraphBuilder(encodingManager).create();
    initGraph(graph);
    graph.edge(1, 2, 10, true);
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger checkPointCounter = new AtomicInteger(0);
    final GraphHopper graphHopper = new GraphHopper() {

        @Override
        protected ChangeGraphHelper createChangeGraphHelper(Graph graph, LocationIndex locationIndex) {
            return new ChangeGraphHelper(graph, locationIndex) {

                @Override
                public long applyChanges(EncodingManager em, Collection<JsonFeature> features) {
                    // force sleep inside the lock and let the main thread run until the lock barrier
                    latch.countDown();
                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    checkPointCounter.incrementAndGet();
                    return super.applyChanges(em, features);
                }
            };
        }
    }.setStoreOnFlush(false).setEncodingManager(encodingManager).setCHEnabled(false).loadGraph(graph);
    GHResponse rsp = graphHopper.route(new GHRequest(42, 10.4, 42, 10));
    assertFalse(rsp.toString(), rsp.hasErrors());
    assertEquals(1800, rsp.getBest().getTime());
    final List<JsonFeature> list = new ArrayList<>();
    Map<String, Object> properties = new HashMap<>();
    properties.put("speed", 5);
    list.add(new JsonFeature("1", "bbox", new BBox(10.399, 10.4, 42.0, 42.001), null, properties));
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    executorService.submit(new Runnable() {

        @Override
        public void run() {
            graphHopper.changeGraph(list);
            checkPointCounter.incrementAndGet();
        }
    });
    latch.await();
    assertEquals(0, checkPointCounter.get());
    rsp = graphHopper.route(new GHRequest(42, 10.4, 42, 10));
    assertFalse(rsp.toString(), rsp.hasErrors());
    assertEquals(8400, rsp.getBest().getTime());
    executorService.shutdown();
    executorService.awaitTermination(3, TimeUnit.SECONDS);
    assertEquals(2, checkPointCounter.get());
}
Also used : ChangeGraphHelper(com.graphhopper.storage.change.ChangeGraphHelper) GraphBuilder(com.graphhopper.storage.GraphBuilder) EncodingManager(com.graphhopper.routing.util.EncodingManager) CountDownLatch(java.util.concurrent.CountDownLatch) LocationIndex(com.graphhopper.storage.index.LocationIndex) GraphHopperStorage(com.graphhopper.storage.GraphHopperStorage) JsonFeature(com.graphhopper.json.geo.JsonFeature) Graph(com.graphhopper.storage.Graph) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BBox(com.graphhopper.util.shapes.BBox) ExecutorService(java.util.concurrent.ExecutorService) Test(org.junit.Test)

Example 8 with LocationIndex

use of com.graphhopper.storage.index.LocationIndex in project graphhopper by graphhopper.

the class GraphEdgeIdFinderTest method testParseStringHints.

@Test
public void testParseStringHints() {
    FlagEncoder encoder = new CarFlagEncoder();
    EncodingManager em = new EncodingManager(encoder);
    GraphHopperStorage graph = new GraphBuilder(em).create();
    // 0-1-2
    // | |
    // 3-4
    graph.edge(0, 1, 1, true);
    graph.edge(1, 2, 1, true);
    graph.edge(3, 4, 1, true);
    graph.edge(0, 3, 1, true);
    graph.edge(1, 4, 1, true);
    AbstractRoutingAlgorithmTester.updateDistancesFor(graph, 0, 0.01, 0.00);
    AbstractRoutingAlgorithmTester.updateDistancesFor(graph, 1, 0.01, 0.01);
    AbstractRoutingAlgorithmTester.updateDistancesFor(graph, 2, 0.01, 0.02);
    AbstractRoutingAlgorithmTester.updateDistancesFor(graph, 3, 0.00, 0.00);
    AbstractRoutingAlgorithmTester.updateDistancesFor(graph, 4, 0.00, 0.01);
    LocationIndex locationIndex = new LocationIndexTree(graph, new RAMDirectory()).prepareIndex();
    HintsMap hints = new HintsMap();
    hints.put(Parameters.Routing.BLOCK_AREA, "0.01,0.005,1");
    ConfigMap cMap = new ConfigMap();
    GraphEdgeIdFinder graphFinder = new GraphEdgeIdFinder(graph, locationIndex);
    ConfigMap result = graphFinder.parseStringHints(cMap, hints, new DefaultEdgeFilter(encoder));
    GHIntHashSet blockedEdges = new GHIntHashSet();
    blockedEdges.add(0);
    assertEquals(blockedEdges, result.get(BLOCKED_EDGES, new GHIntHashSet()));
    List<Shape> blockedShapes = new ArrayList<>();
    assertEquals(blockedShapes, result.get(BLOCKED_SHAPES, new ArrayList<>()));
    // big area converts into shapes
    hints.put(Parameters.Routing.BLOCK_AREA, "0,0,1000");
    result = graphFinder.parseStringHints(cMap, hints, new DefaultEdgeFilter(encoder));
    blockedEdges.clear();
    assertEquals(blockedEdges, result.get(BLOCKED_EDGES, new GHIntHashSet()));
    blockedShapes.add(new Circle(0, 0, 1000));
    assertEquals(blockedShapes, result.get(BLOCKED_SHAPES, new ArrayList<>()));
}
Also used : EncodingManager(com.graphhopper.routing.util.EncodingManager) HintsMap(com.graphhopper.routing.util.HintsMap) Circle(com.graphhopper.util.shapes.Circle) GHIntHashSet(com.graphhopper.coll.GHIntHashSet) Shape(com.graphhopper.util.shapes.Shape) ConfigMap(com.graphhopper.util.ConfigMap) CarFlagEncoder(com.graphhopper.routing.util.CarFlagEncoder) FlagEncoder(com.graphhopper.routing.util.FlagEncoder) ArrayList(java.util.ArrayList) LocationIndex(com.graphhopper.storage.index.LocationIndex) DefaultEdgeFilter(com.graphhopper.routing.util.DefaultEdgeFilter) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) CarFlagEncoder(com.graphhopper.routing.util.CarFlagEncoder) Test(org.junit.Test)

Example 9 with LocationIndex

use of com.graphhopper.storage.index.LocationIndex in project graphhopper by graphhopper.

the class NearestServlet method doGet.

@Override
public void doGet(HttpServletRequest httpReq, HttpServletResponse httpRes) throws ServletException, IOException {
    String pointStr = getParam(httpReq, "point", null);
    boolean enabledElevation = getBooleanParam(httpReq, "elevation", false);
    JSONObject result = new JSONObject();
    if (pointStr != null && !pointStr.equalsIgnoreCase("")) {
        GHPoint place = GHPoint.parse(pointStr);
        LocationIndex index = hopper.getLocationIndex();
        QueryResult qr = index.findClosest(place.lat, place.lon, EdgeFilter.ALL_EDGES);
        if (!qr.isValid()) {
            result.put("error", "Nearest point cannot be found!");
        } else {
            GHPoint3D snappedPoint = qr.getSnappedPoint();
            result.put("type", "Point");
            JSONArray coord = new JSONArray();
            coord.put(snappedPoint.lon);
            coord.put(snappedPoint.lat);
            if (hopper.hasElevation() && enabledElevation)
                coord.put(snappedPoint.ele);
            result.put("coordinates", coord);
            // Distance from input to snapped point in meters
            result.put("distance", calc.calcDist(place.lat, place.lon, snappedPoint.lat, snappedPoint.lon));
        }
    } else {
        result.put("error", "No lat/lon specified!");
    }
    writeJson(httpReq, httpRes, result);
}
Also used : QueryResult(com.graphhopper.storage.index.QueryResult) JSONObject(org.json.JSONObject) GHPoint3D(com.graphhopper.util.shapes.GHPoint3D) JSONArray(org.json.JSONArray) GHPoint(com.graphhopper.util.shapes.GHPoint) LocationIndex(com.graphhopper.storage.index.LocationIndex)

Example 10 with LocationIndex

use of com.graphhopper.storage.index.LocationIndex in project graphhopper by graphhopper.

the class RoutingAlgorithmWithOSMIT method runAlgo.

/**
     * @param withCH if true also the CH and LM algorithms will be tested which need
     *               preparation and takes a bit longer
     */
Graph runAlgo(TestAlgoCollector testCollector, String osmFile, String graphFile, List<OneRun> forEveryAlgo, String importVehicles, boolean withCH, String vehicle, String weightStr, boolean is3D) {
    // for different weightings we need a different storage, otherwise we would need to remove the graph folder
    // everytime we come with a different weighting
    // graphFile += weightStr;
    AlgoHelperEntry algoEntry = null;
    OneRun tmpOneRun = null;
    try {
        Helper.removeDir(new File(graphFile));
        GraphHopper hopper = new GraphHopperOSM().setStoreOnFlush(true).setCHEnabled(false).setDataReaderFile(osmFile).setGraphHopperLocation(graphFile).setEncodingManager(new EncodingManager(importVehicles));
        // avoid that path.getDistance is too different to path.getPoint.calcDistance
        hopper.setWayPointMaxDistance(0);
        // always enable landmarks
        hopper.getLMFactoryDecorator().addWeighting(weightStr).setEnabled(true).setDisablingAllowed(true);
        if (withCH)
            hopper.getCHFactoryDecorator().addWeighting(weightStr).setEnabled(true).setDisablingAllowed(true);
        if (is3D)
            hopper.setElevationProvider(new SRTMProvider().setCacheDir(new File(DIR)));
        hopper.importOrLoad();
        TraversalMode tMode = importVehicles.contains("turn_costs=true") ? TraversalMode.EDGE_BASED_2DIR : TraversalMode.NODE_BASED;
        FlagEncoder encoder = hopper.getEncodingManager().getEncoder(vehicle);
        HintsMap hints = new HintsMap().setWeighting(weightStr).setVehicle(vehicle);
        Collection<AlgoHelperEntry> prepares = RoutingAlgorithmIT.createAlgos(hopper, hints, tMode);
        EdgeFilter edgeFilter = new DefaultEdgeFilter(encoder);
        for (AlgoHelperEntry entry : prepares) {
            algoEntry = entry;
            LocationIndex idx = entry.getIdx();
            for (OneRun oneRun : forEveryAlgo) {
                tmpOneRun = oneRun;
                List<QueryResult> list = oneRun.getList(idx, edgeFilter);
                testCollector.assertDistance(algoEntry, list, oneRun);
            }
        }
        return hopper.getGraphHopperStorage();
    } catch (Exception ex) {
        if (algoEntry == null)
            throw new RuntimeException("cannot handle file " + osmFile + ", " + ex.getMessage(), ex);
        throw new RuntimeException("cannot handle " + algoEntry.toString() + ", for " + tmpOneRun + ", file " + osmFile + ", " + ex.getMessage(), ex);
    } finally {
    // Helper.removeDir(new File(graphFile));
    }
}
Also used : AlgoHelperEntry(com.graphhopper.routing.util.TestAlgoCollector.AlgoHelperEntry) OneRun(com.graphhopper.routing.util.TestAlgoCollector.OneRun) GraphHopperOSM(com.graphhopper.reader.osm.GraphHopperOSM) GraphHopper(com.graphhopper.GraphHopper) LocationIndex(com.graphhopper.storage.index.LocationIndex) IOException(java.io.IOException) SRTMProvider(com.graphhopper.reader.dem.SRTMProvider) QueryResult(com.graphhopper.storage.index.QueryResult) File(java.io.File)

Aggregations

LocationIndex (com.graphhopper.storage.index.LocationIndex)10 Test (org.junit.Test)6 LocationIndexTree (com.graphhopper.storage.index.LocationIndexTree)5 QueryResult (com.graphhopper.storage.index.QueryResult)5 Weighting (com.graphhopper.routing.weighting.Weighting)4 FlagEncoder (com.graphhopper.routing.util.FlagEncoder)3 AlgoHelperEntry (com.graphhopper.routing.util.TestAlgoCollector.AlgoHelperEntry)3 Graph (com.graphhopper.storage.Graph)3 ArrayList (java.util.ArrayList)3 GraphHopper (com.graphhopper.GraphHopper)2 GraphHopperOSM (com.graphhopper.reader.osm.GraphHopperOSM)2 EncodingManager (com.graphhopper.routing.util.EncodingManager)2 HintsMap (com.graphhopper.routing.util.HintsMap)2 OneRun (com.graphhopper.routing.util.TestAlgoCollector.OneRun)2 FastestWeighting (com.graphhopper.routing.weighting.FastestWeighting)2 GraphHopperStorage (com.graphhopper.storage.GraphHopperStorage)2 RAMDirectory (com.graphhopper.storage.RAMDirectory)2 File (java.io.File)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 GHRequest (com.graphhopper.GHRequest)1