Search in sources :

Example 26 with Weighting

use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.

the class LMRoutingAlgorithmFactory method createAlgo.

@Override
public RoutingAlgorithm createAlgo(Graph g, Weighting w, AlgorithmOptions opts) {
    if (!lms.isInitialized())
        throw new IllegalStateException("Initialize landmark storage before creating algorithms");
    int activeLM = Math.max(1, opts.getHints().getInt(Parameters.Landmark.ACTIVE_COUNT, defaultActiveLandmarks));
    final String algoStr = opts.getAlgorithm();
    final Weighting weighting = g.wrapWeighting(w);
    if (ASTAR.equalsIgnoreCase(algoStr)) {
        double epsilon = opts.getHints().getDouble(Parameters.Algorithms.AStar.EPSILON, 1);
        AStar algo = new AStar(g, weighting, opts.getTraversalMode());
        algo.setApproximation(getApproximator(g, activeLM, epsilon));
        algo.setMaxVisitedNodes(opts.getMaxVisitedNodes());
        return algo;
    } else if (ASTAR_BI.equalsIgnoreCase(algoStr) || Helper.isEmpty(algoStr)) {
        double epsilon = opts.getHints().getDouble(Parameters.Algorithms.AStarBi.EPSILON, 1);
        AStarBidirection algo = new AStarBidirection(g, weighting, opts.getTraversalMode());
        algo.setApproximation(getApproximator(g, activeLM, epsilon));
        algo.setMaxVisitedNodes(opts.getMaxVisitedNodes());
        return algo;
    } else if (ALT_ROUTE.equalsIgnoreCase(algoStr)) {
        double epsilon = opts.getHints().getDouble(Parameters.Algorithms.AStarBi.EPSILON, 1);
        AlternativeRoute algo = new AlternativeRoute(g, weighting, opts.getTraversalMode());
        algo.setMaxPaths(opts.getHints().getInt(MAX_PATHS, 2));
        algo.setMaxWeightFactor(opts.getHints().getDouble(MAX_WEIGHT, 1.4));
        algo.setMaxShareFactor(opts.getHints().getDouble(MAX_SHARE, 0.6));
        algo.setMinPlateauFactor(opts.getHints().getDouble("alternative_route.min_plateau_factor", 0.2));
        algo.setApproximation(getApproximator(g, activeLM, epsilon));
        // landmark algorithm follows good compromise between fast response and exploring 'interesting' paths so we
        // can decrease this exploration factor further (1->dijkstra, 0.8->bidir. A*)
        algo.setMaxExplorationFactor(0.6);
        algo.setMaxVisitedNodes(opts.getMaxVisitedNodes());
        return algo;
    } else {
        throw new IllegalArgumentException("Landmarks algorithm only supports algorithm=" + ASTAR + "," + ASTAR_BI + " or " + ALT_ROUTE + ", but got: " + algoStr);
    }
}
Also used : Weighting(com.graphhopper.routing.weighting.Weighting) AStar(com.graphhopper.routing.AStar)

Example 27 with Weighting

use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.

the class PrepareLandmarksTest method testStoreAndLoad.

@Test
public void testStoreAndLoad() {
    GHUtility.setSpeed(60, true, true, encoder, graph.edge(0, 1).setDistance(80_000));
    GHUtility.setSpeed(60, true, true, encoder, graph.edge(1, 2).setDistance(80_000));
    String fileStr = "./target/tmp-lm";
    Helper.removeDir(new File(fileStr));
    Directory dir = new RAMDirectory(fileStr, true).create();
    Weighting weighting = new FastestWeighting(encoder);
    LMConfig lmConfig = new LMConfig("car", weighting);
    PrepareLandmarks plm = new PrepareLandmarks(dir, graph, lmConfig, 2);
    plm.setMinimumNodes(2);
    plm.doWork();
    double expectedFactor = plm.getLandmarkStorage().getFactor();
    assertTrue(plm.getLandmarkStorage().isInitialized());
    assertEquals(Arrays.toString(new int[] { 2, 0 }), Arrays.toString(plm.getLandmarkStorage().getLandmarks(1)));
    assertEquals(4800, Math.round(plm.getLandmarkStorage().getFromWeight(0, 1) * expectedFactor));
    dir = new RAMDirectory(fileStr, true);
    plm = new PrepareLandmarks(dir, graph, lmConfig, 2);
    assertTrue(plm.loadExisting());
    assertEquals(expectedFactor, plm.getLandmarkStorage().getFactor(), 1e-6);
    assertEquals(Arrays.toString(new int[] { 2, 0 }), Arrays.toString(plm.getLandmarkStorage().getLandmarks(1)));
    assertEquals(4800, Math.round(plm.getLandmarkStorage().getFromWeight(0, 1) * expectedFactor));
    Helper.removeDir(new File(fileStr));
}
Also used : FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Weighting(com.graphhopper.routing.weighting.Weighting) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) File(java.io.File) RAMDirectory(com.graphhopper.storage.RAMDirectory) Directory(com.graphhopper.storage.Directory) RAMDirectory(com.graphhopper.storage.RAMDirectory) Test(org.junit.jupiter.api.Test)

Example 28 with Weighting

use of com.graphhopper.routing.weighting.Weighting 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;
    DecimalEncodedValue avSpeedEnc = encoder.getAverageSpeedEnc();
    BooleanEncodedValue accessEnc = encoder.getAccessEnc();
    for (int hIndex = 0; hIndex < height; hIndex++) {
        for (int wIndex = 0; wIndex < width; wIndex++) {
            int node = wIndex + hIndex * width;
            // do not connect first with last column!
            double speed = 20 + rand.nextDouble() * 30;
            if (wIndex + 1 < width)
                graph.edge(node, node + 1).set(accessEnc, true, true).set(avSpeedEnc, speed);
            // avoid dead ends
            if (hIndex + 1 < height)
                graph.edge(node, node + width).set(accessEnc, true, true).set(avSpeedEnc, speed);
            updateDistancesFor(graph, node, -hIndex / 50.0, wIndex / 50.0);
        }
    }
    Directory dir = new RAMDirectory();
    LocationIndexTree index = new LocationIndexTree(graph, dir);
    index.prepareIndex();
    int lm = 5, activeLM = 2;
    Weighting weighting = new FastestWeighting(encoder);
    LMConfig lmConfig = new LMConfig("car", weighting);
    LandmarkStorage store = new LandmarkStorage(graph, dir, lmConfig, lm);
    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];
    Arrays.fill(activeLandmarkIndices, -1);
    store.chooseActiveLandmarks(27, 47, activeLandmarkIndices, 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);
    PrepareLandmarks prepare = new PrepareLandmarks(new RAMDirectory(), graph, lmConfig, 4);
    prepare.setMinimumNodes(2);
    prepare.doWork();
    LandmarkStorage lms = prepare.getLandmarkStorage();
    AStar expectedAlgo = new AStar(graph, weighting, tm);
    Path expectedPath = expectedAlgo.calcPath(41, 183);
    PMap hints = new PMap().putObject(Parameters.Landmark.ACTIVE_COUNT, 2);
    // landmarks with A*
    RoutingAlgorithm oneDirAlgoWithLandmarks = new LMRoutingAlgorithmFactory(lms).createAlgo(graph, weighting, new AlgorithmOptions().setAlgorithm(ASTAR).setTraversalMode(tm).setHints(hints));
    Path path = oneDirAlgoWithLandmarks.calcPath(41, 183);
    assertEquals(expectedPath.getWeight(), path.getWeight(), .1);
    assertEquals(expectedPath.calcNodes(), path.calcNodes());
    assertEquals(expectedAlgo.getVisitedNodes() - 135, oneDirAlgoWithLandmarks.getVisitedNodes());
    // landmarks with bidir A*
    RoutingAlgorithm biDirAlgoWithLandmarks = new LMRoutingAlgorithmFactory(lms).createAlgo(graph, weighting, new AlgorithmOptions().setAlgorithm(ASTAR_BI).setTraversalMode(tm).setHints(hints));
    path = biDirAlgoWithLandmarks.calcPath(41, 183);
    assertEquals(expectedPath.getWeight(), path.getWeight(), .1);
    assertEquals(expectedPath.calcNodes(), path.calcNodes());
    assertEquals(expectedAlgo.getVisitedNodes() - 162, biDirAlgoWithLandmarks.getVisitedNodes());
    // 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
    Snap fromSnap = index.findClosest(-0.0401, 0.2201, EdgeFilter.ALL_EDGES);
    Snap toSnap = index.findClosest(-0.2401, 0.0601, EdgeFilter.ALL_EDGES);
    QueryGraph qGraph = QueryGraph.create(graph, fromSnap, toSnap);
    RoutingAlgorithm qGraphOneDirAlgo = new LMRoutingAlgorithmFactory(lms).createAlgo(qGraph, weighting, new AlgorithmOptions().setAlgorithm(ASTAR).setTraversalMode(tm).setHints(hints));
    path = qGraphOneDirAlgo.calcPath(fromSnap.getClosestNode(), toSnap.getClosestNode());
    expectedAlgo = new AStar(qGraph, weighting, tm);
    expectedPath = expectedAlgo.calcPath(fromSnap.getClosestNode(), toSnap.getClosestNode());
    assertEquals(expectedPath.getWeight(), path.getWeight(), .1);
    assertEquals(expectedPath.calcNodes(), path.calcNodes());
    assertEquals(expectedAlgo.getVisitedNodes() - 135, qGraphOneDirAlgo.getVisitedNodes());
}
Also used : RoutingAlgorithm(com.graphhopper.routing.RoutingAlgorithm) ArrayList(java.util.ArrayList) AStar(com.graphhopper.routing.AStar) PMap(com.graphhopper.util.PMap) AlgorithmOptions(com.graphhopper.routing.AlgorithmOptions) Snap(com.graphhopper.storage.index.Snap) Random(java.util.Random) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Directory(com.graphhopper.storage.Directory) RAMDirectory(com.graphhopper.storage.RAMDirectory) Path(com.graphhopper.routing.Path) RAMDirectory(com.graphhopper.storage.RAMDirectory) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Weighting(com.graphhopper.routing.weighting.Weighting) DecimalEncodedValue(com.graphhopper.routing.ev.DecimalEncodedValue) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph) Test(org.junit.jupiter.api.Test)

Example 29 with Weighting

use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.

the class NodeBasedNodeContractorTest method testNodeContraction_shortcutWeightRounding.

/**
 * similar to the previous test, but using the fastest weighting
 */
@Test
public void testNodeContraction_shortcutWeightRounding() {
    CarFlagEncoder encoder = new CarFlagEncoder();
    EncodingManager encodingManager = EncodingManager.create(encoder);
    GraphHopperStorage graph = new GraphBuilder(encodingManager).create();
    // 0 ------------> 4
    // \             /
    // 1 --> 2 --> 3
    double fac = 60 / 3.6;
    double[] distances = { fac * 4.019, fac * 1.006, fac * 1.004, fac * 1.006, fac * 1.004 };
    GHUtility.setSpeed(60, true, false, encoder, graph.edge(0, 4).setDistance(distances[0]));
    GHUtility.setSpeed(60, true, false, encoder, graph.edge(0, 1).setDistance(distances[1]));
    GHUtility.setSpeed(60, true, false, encoder, graph.edge(1, 2).setDistance(distances[2]));
    GHUtility.setSpeed(60, true, false, encoder, graph.edge(2, 3).setDistance(distances[3]));
    GHUtility.setSpeed(60, true, false, encoder, graph.edge(3, 4).setDistance(distances[4]));
    graph.freeze();
    Weighting weighting = new FastestWeighting(encoder);
    CHConfig chConfig = CHConfig.nodeBased("p1", weighting);
    CHStorage chStore = graph.createCHStorage(chConfig);
    setMaxLevelOnAllNodes(chStore);
    // perform CH contraction
    contractInOrder(graph, chStore, chConfig, 1, 3, 2, 0, 4);
    // first we compare dijkstra with CH to make sure they produce the same results
    int from = 0;
    int to = 4;
    Dijkstra dikstra = new Dijkstra(graph, weighting, TraversalMode.NODE_BASED);
    Path dijkstraPath = dikstra.calcPath(from, to);
    DijkstraBidirectionCH ch = new DijkstraBidirectionCH(graph.createCHGraph(chStore, chConfig));
    Path chPath = ch.calcPath(from, to);
    assertEquals(dijkstraPath.calcNodes(), chPath.calcNodes());
    assertEquals(dijkstraPath.getDistance(), chPath.getDistance(), 1.e-6);
    assertEquals(dijkstraPath.getWeight(), chPath.getWeight(), 1.e-6);
}
Also used : EncodingManager(com.graphhopper.routing.util.EncodingManager) Path(com.graphhopper.routing.Path) DijkstraBidirectionCH(com.graphhopper.routing.DijkstraBidirectionCH) Dijkstra(com.graphhopper.routing.Dijkstra) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Weighting(com.graphhopper.routing.weighting.Weighting) ShortestWeighting(com.graphhopper.routing.weighting.ShortestWeighting) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) CarFlagEncoder(com.graphhopper.routing.util.CarFlagEncoder) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 30 with Weighting

use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.

the class CustomWeightingTest method testSpeedFactorBooleanEV.

@Test
public void testSpeedFactorBooleanEV() {
    EdgeIteratorState edge = GHUtility.setSpeed(15, true, true, carFE, graph.edge(0, 1).setDistance(10));
    CustomModel vehicleModel = new CustomModel();
    assertEquals(3.1, createWeighting(vehicleModel).calcEdgeWeight(edge, false), 0.01);
    // here we increase weight for edges that are road class links
    vehicleModel.addToPriority(If(RoadClassLink.KEY, MULTIPLY, 0.5));
    Weighting weighting = createWeighting(vehicleModel);
    BooleanEncodedValue rcLinkEnc = encodingManager.getBooleanEncodedValue(RoadClassLink.KEY);
    assertEquals(3.1, weighting.calcEdgeWeight(edge.set(rcLinkEnc, false), false), 0.01);
    assertEquals(5.5, weighting.calcEdgeWeight(edge.set(rcLinkEnc, true), false), 0.01);
}
Also used : FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) Weighting(com.graphhopper.routing.weighting.Weighting) Test(org.junit.jupiter.api.Test)

Aggregations

Weighting (com.graphhopper.routing.weighting.Weighting)57 FastestWeighting (com.graphhopper.routing.weighting.FastestWeighting)32 ShortestWeighting (com.graphhopper.routing.weighting.ShortestWeighting)15 Test (org.junit.jupiter.api.Test)15 Test (org.junit.Test)12 Snap (com.graphhopper.storage.index.Snap)11 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)10 QueryGraph (com.graphhopper.routing.querygraph.QueryGraph)9 GHPoint (com.graphhopper.util.shapes.GHPoint)9 Path (com.graphhopper.routing.Path)8 Graph (com.graphhopper.storage.Graph)8 LocationIndexTree (com.graphhopper.storage.index.LocationIndexTree)8 Profile (com.graphhopper.config.Profile)7 GraphHopperStorage (com.graphhopper.storage.GraphHopperStorage)7 ArrayList (java.util.ArrayList)7 GraphHopper (com.graphhopper.GraphHopper)6 IOException (java.io.IOException)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 AbstractWeighting (com.graphhopper.routing.weighting.AbstractWeighting)5