Search in sources :

Example 1 with LocationIndex

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

the class ChangeGraphHelperTest method testApplyChanges.

@Test
public void testApplyChanges() {
    // 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();
    FlagEncoder encoder = encodingManager.getEncoder("car");
    double defaultSpeed = encoder.getSpeed(GHUtility.getEdge(graph, 0, 1).getFlags());
    AllEdgesIterator iter = graph.getAllEdges();
    while (iter.next()) {
        long flags = GHUtility.getEdge(graph, 0, 1).getFlags();
        assertEquals(defaultSpeed, encoder.getSpeed(flags), .1);
        assertTrue(encoder.isForward(flags));
    }
    Reader reader = new InputStreamReader(getClass().getResourceAsStream("overlaydata1.json"), Helper.UTF_CS);
    ChangeGraphHelper instance = new ChangeGraphHelper(graph, locationIndex);
    JsonFeatureConverter converter = new JsonFeatureConverter(ghson, instance, encodingManager);
    long updates = converter.applyChanges(reader);
    assertEquals(2, updates);
    // assert changed speed and access
    double newSpeed = encoder.getSpeed(GHUtility.getEdge(graph, 0, 1).getFlags());
    assertEquals(10, newSpeed, .1);
    assertTrue(newSpeed < defaultSpeed);
    assertFalse(encoder.isForward(GHUtility.getEdge(graph, 3, 4).getFlags()));
}
Also used : AllEdgesIterator(com.graphhopper.routing.util.AllEdgesIterator) InputStreamReader(java.io.InputStreamReader) FlagEncoder(com.graphhopper.routing.util.FlagEncoder) JsonFeatureConverter(com.graphhopper.json.JsonFeatureConverter) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) LocationIndex(com.graphhopper.storage.index.LocationIndex) RAMDirectory(com.graphhopper.storage.RAMDirectory) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) Test(org.junit.Test)

Example 2 with LocationIndex

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

the class RoutingAlgorithmWithOSMIT method testMonacoParallel.

@Test
public void testMonacoParallel() throws IOException {
    System.out.println("testMonacoParallel takes a bit time...");
    String graphFile = "target/monaco-gh";
    Helper.removeDir(new File(graphFile));
    final EncodingManager encodingManager = new EncodingManager("car");
    final GraphHopper hopper = new GraphHopperOSM().setStoreOnFlush(true).setEncodingManager(encodingManager).setCHEnabled(false).setWayPointMaxDistance(0).setDataReaderFile(DIR + "/monaco.osm.gz").setGraphHopperLocation(graphFile).importOrLoad();
    final Graph g = hopper.getGraphHopperStorage();
    final LocationIndex idx = hopper.getLocationIndex();
    final List<OneRun> instances = createMonacoCar();
    List<Thread> threads = new ArrayList<Thread>();
    final AtomicInteger integ = new AtomicInteger(0);
    int MAX = 100;
    final FlagEncoder carEncoder = encodingManager.getEncoder("car");
    // testing if algorithms are independent. should be. so test only two algorithms. 
    // also the preparing is too costly to be called for every thread
    int algosLength = 2;
    final Weighting weighting = new ShortestWeighting(encodingManager.getEncoder("car"));
    final EdgeFilter filter = new DefaultEdgeFilter(carEncoder);
    for (int no = 0; no < MAX; no++) {
        for (int instanceNo = 0; instanceNo < instances.size(); instanceNo++) {
            String[] algos = new String[] { ASTAR, DIJKSTRA_BI };
            for (final String algoStr : algos) {
                // an algorithm is not thread safe! reuse via clear() is ONLY appropriated if used from same thread!
                final int instanceIndex = instanceNo;
                Thread t = new Thread() {

                    @Override
                    public void run() {
                        OneRun oneRun = instances.get(instanceIndex);
                        AlgorithmOptions opts = AlgorithmOptions.start().weighting(weighting).algorithm(algoStr).build();
                        testCollector.assertDistance(new AlgoHelperEntry(g, opts, idx, algoStr + "|" + weighting), oneRun.getList(idx, filter), oneRun);
                        integ.addAndGet(1);
                    }
                };
                t.start();
                threads.add(t);
            }
        }
    }
    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }
    }
    assertEquals(MAX * algosLength * instances.size(), integ.get());
    assertEquals(testCollector.toString(), 0, testCollector.errors.size());
    hopper.close();
}
Also used : AlgoHelperEntry(com.graphhopper.routing.util.TestAlgoCollector.AlgoHelperEntry) ArrayList(java.util.ArrayList) GraphHopperOSM(com.graphhopper.reader.osm.GraphHopperOSM) OneRun(com.graphhopper.routing.util.TestAlgoCollector.OneRun) GraphHopper(com.graphhopper.GraphHopper) LocationIndex(com.graphhopper.storage.index.LocationIndex) ShortestWeighting(com.graphhopper.routing.weighting.ShortestWeighting) Graph(com.graphhopper.storage.Graph) Weighting(com.graphhopper.routing.weighting.Weighting) ShortestWeighting(com.graphhopper.routing.weighting.ShortestWeighting) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) File(java.io.File) Test(org.junit.Test)

Example 3 with LocationIndex

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

the class RoutingAlgorithmIT method createAlgos.

public static List<AlgoHelperEntry> createAlgos(final GraphHopper hopper, final HintsMap hints, TraversalMode tMode) {
    GraphHopperStorage ghStorage = hopper.getGraphHopperStorage();
    LocationIndex idx = hopper.getLocationIndex();
    String addStr = "";
    if (tMode.isEdgeBased())
        addStr = "turn|";
    FlagEncoder encoder = hopper.getEncodingManager().getEncoder(hints.getVehicle());
    Weighting weighting = hopper.createWeighting(hints, encoder, hopper.getGraphHopperStorage());
    HintsMap defaultHints = new HintsMap().put(Parameters.CH.DISABLE, true).put(Parameters.Landmark.DISABLE, true).setVehicle(hints.getVehicle()).setWeighting(hints.getWeighting());
    AlgorithmOptions defaultOpts = AlgorithmOptions.start(new AlgorithmOptions("", weighting, tMode)).hints(defaultHints).build();
    List<AlgoHelperEntry> prepare = new ArrayList<>();
    prepare.add(new AlgoHelperEntry(ghStorage, AlgorithmOptions.start(defaultOpts).algorithm(ASTAR).build(), idx, "astar|beeline|" + addStr + weighting));
    // later: include dijkstraOneToMany
    prepare.add(new AlgoHelperEntry(ghStorage, AlgorithmOptions.start(defaultOpts).algorithm(DIJKSTRA).build(), idx, "dijkstra|" + addStr + weighting));
    AlgorithmOptions astarbiOpts = AlgorithmOptions.start(defaultOpts).algorithm(ASTAR_BI).build();
    astarbiOpts.getHints().put(ASTAR_BI + ".approximation", "BeelineSimplification");
    AlgorithmOptions dijkstrabiOpts = AlgorithmOptions.start(defaultOpts).algorithm(DIJKSTRA_BI).build();
    prepare.add(new AlgoHelperEntry(ghStorage, astarbiOpts, idx, "astarbi|beeline|" + addStr + weighting));
    prepare.add(new AlgoHelperEntry(ghStorage, dijkstrabiOpts, idx, "dijkstrabi|" + addStr + weighting));
    // add additional preparations if CH and LM preparation are enabled
    if (hopper.getLMFactoryDecorator().isEnabled()) {
        final HintsMap lmHints = new HintsMap(defaultHints).put(Parameters.Landmark.DISABLE, false);
        prepare.add(new AlgoHelperEntry(ghStorage, AlgorithmOptions.start(astarbiOpts).hints(lmHints).build(), idx, "astarbi|landmarks|" + weighting) {

            @Override
            public RoutingAlgorithmFactory createRoutingFactory() {
                return hopper.getAlgorithmFactory(lmHints);
            }
        });
    }
    if (hopper.getCHFactoryDecorator().isEnabled()) {
        final HintsMap chHints = new HintsMap(defaultHints).put(Parameters.CH.DISABLE, false);
        Weighting pickedWeighting = null;
        for (Weighting tmpWeighting : hopper.getCHFactoryDecorator().getWeightings()) {
            if (tmpWeighting.equals(weighting)) {
                pickedWeighting = tmpWeighting;
                break;
            }
        }
        if (pickedWeighting == null)
            throw new IllegalStateException("Didn't find weighting " + hints.getWeighting() + " in " + hopper.getCHFactoryDecorator().getWeightings());
        prepare.add(new AlgoHelperEntry(ghStorage.getGraph(CHGraph.class, pickedWeighting), AlgorithmOptions.start(dijkstrabiOpts).hints(chHints).build(), idx, "dijkstrabi|ch|prepare|" + hints.getWeighting()) {

            @Override
            public RoutingAlgorithmFactory createRoutingFactory() {
                return hopper.getAlgorithmFactory(chHints);
            }
        });
        prepare.add(new AlgoHelperEntry(ghStorage.getGraph(CHGraph.class, pickedWeighting), AlgorithmOptions.start(astarbiOpts).hints(chHints).build(), idx, "astarbi|ch|prepare|" + hints.getWeighting()) {

            @Override
            public RoutingAlgorithmFactory createRoutingFactory() {
                return hopper.getAlgorithmFactory(chHints);
            }
        });
    }
    return prepare;
}
Also used : HintsMap(com.graphhopper.routing.util.HintsMap) AlgoHelperEntry(com.graphhopper.routing.util.TestAlgoCollector.AlgoHelperEntry) FlagEncoder(com.graphhopper.routing.util.FlagEncoder) ArrayList(java.util.ArrayList) LocationIndex(com.graphhopper.storage.index.LocationIndex) GraphHopperStorage(com.graphhopper.storage.GraphHopperStorage) Weighting(com.graphhopper.routing.weighting.Weighting)

Example 4 with LocationIndex

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

the class PrepareLandmarksTest method testLandmarkStorageAndRouting.

@Test
public void testLandmarkStorageAndRouting() {
    // create graph with lat,lon 
    // 0  1  2  ...
    // 15 16 17 ...
    Random rand = new Random(0);
    int width = 15, height = 15;
    for (int hIndex = 0; hIndex < height; hIndex++) {
        for (int wIndex = 0; wIndex < width; wIndex++) {
            int node = wIndex + hIndex * width;
            long flags = encoder.setProperties(20 + rand.nextDouble() * 30, true, true);
            // do not connect first with last column!
            if (wIndex + 1 < width)
                graph.edge(node, node + 1).setFlags(flags);
            // avoid dead ends
            if (hIndex + 1 < height)
                graph.edge(node, node + width).setFlags(flags);
            AbstractRoutingAlgorithmTester.updateDistancesFor(graph, node, -hIndex / 50.0, wIndex / 50.0);
        }
    }
    Directory dir = new RAMDirectory();
    LocationIndex index = new LocationIndexTree(graph, dir);
    index.prepareIndex();
    int lm = 5, activeLM = 2;
    Weighting weighting = new FastestWeighting(encoder);
    LandmarkStorage store = new LandmarkStorage(graph, dir, lm, weighting, tm);
    store.setMinimumNodes(2);
    store.createLandmarks();
    // landmarks should be the 4 corners of the grid:
    int[] intList = store.getLandmarks(1);
    Arrays.sort(intList);
    assertEquals("[0, 14, 70, 182, 224]", Arrays.toString(intList));
    // two landmarks: one for subnetwork 0 (all empty) and one for subnetwork 1
    assertEquals(2, store.getSubnetworksWithLandmarks());
    assertEquals(0, store.getFromWeight(0, 224));
    double factor = store.getFactor();
    assertEquals(4671, Math.round(store.getFromWeight(0, 47) * factor));
    assertEquals(3640, Math.round(store.getFromWeight(0, 52) * factor));
    long weight1_224 = store.getFromWeight(1, 224);
    assertEquals(5525, Math.round(weight1_224 * factor));
    long weight1_47 = store.getFromWeight(1, 47);
    assertEquals(921, Math.round(weight1_47 * factor));
    // grid is symmetric
    assertEquals(weight1_224, store.getToWeight(1, 224));
    assertEquals(weight1_47, store.getToWeight(1, 47));
    // prefer the landmarks before and behind the goal
    int[] activeLandmarkIndices = new int[activeLM];
    int[] activeFroms = new int[activeLM];
    int[] activeTos = new int[activeLM];
    Arrays.fill(activeLandmarkIndices, -1);
    store.initActiveLandmarks(27, 47, activeLandmarkIndices, activeFroms, activeTos, false);
    List<Integer> list = new ArrayList<>();
    for (int idx : activeLandmarkIndices) {
        list.add(store.getLandmarks(1)[idx]);
    }
    // TODO should better select 0 and 224?
    assertEquals(Arrays.asList(224, 70), list);
    AlgorithmOptions opts = AlgorithmOptions.start().weighting(weighting).traversalMode(tm).build();
    PrepareLandmarks prepare = new PrepareLandmarks(new RAMDirectory(), graph, weighting, tm, 4, 2);
    prepare.setMinimumNodes(2);
    prepare.doWork();
    AStar expectedAlgo = new AStar(graph, weighting, tm);
    Path expectedPath = expectedAlgo.calcPath(41, 183);
    // landmarks with A*
    RoutingAlgorithm oneDirAlgoWithLandmarks = prepare.getDecoratedAlgorithm(graph, new AStar(graph, weighting, tm), opts);
    Path path = oneDirAlgoWithLandmarks.calcPath(41, 183);
    assertEquals(expectedPath.getWeight(), path.getWeight(), .1);
    assertEquals(expectedPath.calcNodes(), path.calcNodes());
    assertEquals(expectedAlgo.getVisitedNodes(), oneDirAlgoWithLandmarks.getVisitedNodes() + 142);
    // landmarks with bidir A*
    opts.getHints().put("lm.recalc_count", 50);
    RoutingAlgorithm biDirAlgoWithLandmarks = prepare.getDecoratedAlgorithm(graph, new AStarBidirection(graph, weighting, tm), opts);
    path = biDirAlgoWithLandmarks.calcPath(41, 183);
    assertEquals(expectedPath.getWeight(), path.getWeight(), .1);
    assertEquals(expectedPath.calcNodes(), path.calcNodes());
    assertEquals(expectedAlgo.getVisitedNodes(), biDirAlgoWithLandmarks.getVisitedNodes() + 164);
    // landmarks with A* and a QueryGraph. We expect slightly less optimal as two more cycles needs to be traversed
    // due to the two more virtual nodes but this should not harm in practise
    QueryGraph qGraph = new QueryGraph(graph);
    QueryResult fromQR = index.findClosest(-0.0401, 0.2201, EdgeFilter.ALL_EDGES);
    QueryResult toQR = index.findClosest(-0.2401, 0.0601, EdgeFilter.ALL_EDGES);
    qGraph.lookup(fromQR, toQR);
    RoutingAlgorithm qGraphOneDirAlgo = prepare.getDecoratedAlgorithm(qGraph, new AStar(qGraph, weighting, tm), opts);
    path = qGraphOneDirAlgo.calcPath(fromQR.getClosestNode(), toQR.getClosestNode());
    expectedAlgo = new AStar(qGraph, weighting, tm);
    expectedPath = expectedAlgo.calcPath(fromQR.getClosestNode(), toQR.getClosestNode());
    assertEquals(expectedPath.getWeight(), path.getWeight(), .1);
    assertEquals(expectedPath.calcNodes(), path.calcNodes());
    assertEquals(expectedAlgo.getVisitedNodes(), qGraphOneDirAlgo.getVisitedNodes() + 133);
}
Also used : LocationIndex(com.graphhopper.storage.index.LocationIndex) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) QueryResult(com.graphhopper.storage.index.QueryResult) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Weighting(com.graphhopper.routing.weighting.Weighting) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Test(org.junit.Test)

Example 5 with LocationIndex

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

the class RoundTripRoutingTemplateTest method testCalcRoundTrip.

@Test
public void testCalcRoundTrip() throws Exception {
    Weighting weighting = new FastestWeighting(carFE);
    Graph g = createTestGraph(true);
    RoundTripRoutingTemplate rTripRouting = new RoundTripRoutingTemplate(new GHRequest(), new GHResponse(), null, 1);
    LocationIndex locationIndex = new LocationIndexTree(g, new RAMDirectory()).prepareIndex();
    QueryResult qr4 = locationIndex.findClosest(0.05, 0.25, EdgeFilter.ALL_EDGES);
    assertEquals(4, qr4.getClosestNode());
    QueryResult qr5 = locationIndex.findClosest(0.00, 0.05, EdgeFilter.ALL_EDGES);
    assertEquals(5, qr5.getClosestNode());
    QueryResult qr6 = locationIndex.findClosest(0.00, 0.10, EdgeFilter.ALL_EDGES);
    assertEquals(6, qr6.getClosestNode());
    QueryGraph qGraph = new QueryGraph(g);
    qGraph.lookup(qr4, qr5);
    rTripRouting.setQueryResults(Arrays.asList(qr5, qr4, qr5));
    List<Path> paths = rTripRouting.calcPaths(qGraph, new RoutingAlgorithmFactorySimple(), new AlgorithmOptions(DIJKSTRA_BI, weighting, tMode));
    assertEquals(2, paths.size());
    assertEquals(Helper.createTList(5, 6, 3, 4), paths.get(0).calcNodes());
    assertEquals(Helper.createTList(4, 8, 7, 6, 5), paths.get(1).calcNodes());
    qGraph = new QueryGraph(g);
    qGraph.lookup(qr4, qr6);
    rTripRouting.setQueryResults(Arrays.asList(qr6, qr4, qr6));
    paths = rTripRouting.calcPaths(qGraph, new RoutingAlgorithmFactorySimple(), new AlgorithmOptions(DIJKSTRA_BI, weighting, tMode));
    assertEquals(2, paths.size());
    assertEquals(Helper.createTList(6, 3, 4), paths.get(0).calcNodes());
    assertEquals(Helper.createTList(4, 8, 7, 6), paths.get(1).calcNodes());
}
Also used : GHResponse(com.graphhopper.GHResponse) LocationIndex(com.graphhopper.storage.index.LocationIndex) RAMDirectory(com.graphhopper.storage.RAMDirectory) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) QueryResult(com.graphhopper.storage.index.QueryResult) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Weighting(com.graphhopper.routing.weighting.Weighting) Graph(com.graphhopper.storage.Graph) GHRequest(com.graphhopper.GHRequest) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Test(org.junit.Test)

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