Search in sources :

Example 16 with QueryGraph

use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.

the class Router method routeAlt.

protected GHResponse routeAlt(GHRequest request, Solver solver) {
    if (request.getPoints().size() > 2)
        throw new IllegalArgumentException("Currently alternative routes work only with start and end point. You tried to use: " + request.getPoints().size() + " points");
    GHResponse ghRsp = new GHResponse();
    StopWatch sw = new StopWatch().start();
    DirectedEdgeFilter directedEdgeFilter = solver.createDirectedEdgeFilter();
    List<Snap> snaps = ViaRouting.lookup(encodingManager, request.getPoints(), solver.createSnapFilter(), locationIndex, request.getSnapPreventions(), request.getPointHints(), directedEdgeFilter, request.getHeadings());
    ghRsp.addDebugInfo("idLookup:" + sw.stop().getSeconds() + "s");
    QueryGraph queryGraph = QueryGraph.create(ghStorage, snaps);
    PathCalculator pathCalculator = solver.createPathCalculator(queryGraph);
    boolean passThrough = getPassThrough(request.getHints());
    boolean forceCurbsides = getForceCurbsides(request.getHints());
    if (passThrough)
        throw new IllegalArgumentException("Alternative paths and " + PASS_THROUGH + " at the same time is currently not supported");
    if (!request.getCurbsides().isEmpty())
        throw new IllegalArgumentException("Alternative paths do not support the " + CURBSIDE + " parameter yet");
    ViaRouting.Result result = ViaRouting.calcPaths(request.getPoints(), queryGraph, snaps, directedEdgeFilter, pathCalculator, request.getCurbsides(), forceCurbsides, request.getHeadings(), passThrough);
    if (result.paths.isEmpty())
        throw new RuntimeException("Empty paths for alternative route calculation not expected");
    // each path represents a different alternative and we do the path merging for each of them
    PathMerger pathMerger = createPathMerger(request, solver.weighting, queryGraph);
    for (Path path : result.paths) {
        PointList waypoints = getWaypoints(snaps);
        ResponsePath responsePath = pathMerger.doWork(waypoints, Collections.singletonList(path), encodingManager, translationMap.getWithFallBack(request.getLocale()));
        ghRsp.add(responsePath);
    }
    ghRsp.getHints().putObject("visited_nodes.sum", result.visitedNodes);
    ghRsp.getHints().putObject("visited_nodes.average", (float) result.visitedNodes / (snaps.size() - 1));
    return ghRsp;
}
Also used : ResponsePath(com.graphhopper.ResponsePath) GHResponse(com.graphhopper.GHResponse) Snap(com.graphhopper.storage.index.Snap) ResponsePath(com.graphhopper.ResponsePath) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph)

Example 17 with QueryGraph

use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.

the class MiniGraphUI method createAlgo.

private RoutingAlgorithm createAlgo(GraphHopper hopper) {
    Profile profile = hopper.getProfiles().iterator().next();
    if (useCH) {
        RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName());
        logger.info("CH algo, profile: " + profile.getName());
        QueryGraph qGraph = QueryGraph.create(hopper.getGraphHopperStorage(), fromRes, toRes);
        QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph);
        return new CHDebugAlgo(queryRoutingCHGraph, mg);
    } else {
        LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName());
        RoutingAlgorithmFactory algoFactory = (g, w, opts) -> {
            RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts);
            if (algo instanceof AStarBidirection) {
                return new DebugAStarBi(g, w, opts.getTraversalMode(), mg).setApproximation(((AStarBidirection) algo).getApproximation());
            } else if (algo instanceof AStar) {
                return new DebugAStar(g, w, opts.getTraversalMode(), mg);
            } else if (algo instanceof DijkstraBidirectionRef) {
                return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg);
            } else if (algo instanceof Dijkstra) {
                return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg);
            }
            return algo;
        };
        AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI);
        logger.info("algoOpts:" + algoOpts + ", weighting: " + landmarks.getWeighting() + ", profile: " + profile.getName());
        QueryGraph qGraph = QueryGraph.create(graph, fromRes, toRes);
        return algoFactory.createAlgo(qGraph, landmarks.getWeighting(), algoOpts);
    }
}
Also used : RoutingCHGraph(com.graphhopper.storage.RoutingCHGraph) Arrays(java.util.Arrays) GraphHopperConfig(com.graphhopper.GraphHopperConfig) EdgeFilter(com.graphhopper.routing.util.EdgeFilter) QueryRoutingCHGraph(com.graphhopper.routing.querygraph.QueryRoutingCHGraph) com.graphhopper.routing(com.graphhopper.routing) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) LandmarkStorage(com.graphhopper.routing.lm.LandmarkStorage) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) StopWatch(com.graphhopper.util.StopWatch) LMRoutingAlgorithmFactory(com.graphhopper.routing.lm.LMRoutingAlgorithmFactory) MouseWheelEvent(java.awt.event.MouseWheelEvent) DecimalEncodedValue(com.graphhopper.routing.ev.DecimalEncodedValue) Profile(com.graphhopper.config.Profile) MouseAdapter(java.awt.event.MouseAdapter) Graph(com.graphhopper.storage.Graph) GraphHopper(com.graphhopper.GraphHopper) FlagEncoder(com.graphhopper.routing.util.FlagEncoder) IntIndexedContainer(com.carrotsearch.hppc.IntIndexedContainer) Logger(org.slf4j.Logger) BBox(com.graphhopper.util.shapes.BBox) PMap(com.graphhopper.util.PMap) Algorithms(com.graphhopper.util.Parameters.Algorithms) BooleanEncodedValue(com.graphhopper.routing.ev.BooleanEncodedValue) CHProfile(com.graphhopper.config.CHProfile) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph) PointList(com.graphhopper.util.PointList) MouseEvent(java.awt.event.MouseEvent) GHBitSet(com.graphhopper.coll.GHBitSet) java.awt(java.awt) GHTBitSet(com.graphhopper.coll.GHTBitSet) NodeAccess(com.graphhopper.storage.NodeAccess) MouseWheelListener(java.awt.event.MouseWheelListener) Snap(com.graphhopper.storage.index.Snap) FetchMode(com.graphhopper.util.FetchMode) LMProfile(com.graphhopper.config.LMProfile) AllEdgesIterator(com.graphhopper.routing.util.AllEdgesIterator) javax.swing(javax.swing) QueryRoutingCHGraph(com.graphhopper.routing.querygraph.QueryRoutingCHGraph) RoutingCHGraph(com.graphhopper.storage.RoutingCHGraph) QueryRoutingCHGraph(com.graphhopper.routing.querygraph.QueryRoutingCHGraph) LMRoutingAlgorithmFactory(com.graphhopper.routing.lm.LMRoutingAlgorithmFactory) Profile(com.graphhopper.config.Profile) CHProfile(com.graphhopper.config.CHProfile) LMProfile(com.graphhopper.config.LMProfile) LandmarkStorage(com.graphhopper.routing.lm.LandmarkStorage) LMRoutingAlgorithmFactory(com.graphhopper.routing.lm.LMRoutingAlgorithmFactory) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph)

Example 18 with QueryGraph

use of com.graphhopper.routing.querygraph.QueryGraph 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 19 with QueryGraph

use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.

the class BlockAreaWeightingTest method testBlockVirtualEdges_QueryGraph.

@Test
public void testBlockVirtualEdges_QueryGraph() {
    GraphEdgeIdFinder.BlockArea bArea = new GraphEdgeIdFinder.BlockArea(graph);
    // add base graph edge to fill caches and trigger edgeId cache search (without virtual edges)
    GHIntHashSet set = new GHIntHashSet();
    set.add(0);
    bArea.add(new Circle(0.0025, 0.0025, 1), set);
    LocationIndex index = new LocationIndexTree(graph, graph.getDirectory()).prepareIndex();
    Snap snap = index.findClosest(0.005, 0.005, EdgeFilter.ALL_EDGES);
    QueryGraph queryGraph = QueryGraph.create(graph, snap);
    BlockAreaWeighting instance = new BlockAreaWeighting(new FastestWeighting(encoder), bArea);
    EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(snap.getClosestNode());
    int blockedEdges = 0, totalEdges = 0;
    while (iter.next()) {
        if (Double.isInfinite(instance.calcEdgeWeight(iter, false)))
            blockedEdges++;
        totalEdges++;
    }
    assertEquals(1, blockedEdges);
    assertEquals(2, totalEdges);
}
Also used : Circle(com.graphhopper.util.shapes.Circle) GraphEdgeIdFinder(com.graphhopper.storage.GraphEdgeIdFinder) GHIntHashSet(com.graphhopper.coll.GHIntHashSet) LocationIndex(com.graphhopper.storage.index.LocationIndex) Snap(com.graphhopper.storage.index.Snap) LocationIndexTree(com.graphhopper.storage.index.LocationIndexTree) EdgeIterator(com.graphhopper.util.EdgeIterator) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph) Test(org.junit.jupiter.api.Test)

Example 20 with QueryGraph

use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.

the class Router method routeVia.

protected GHResponse routeVia(GHRequest request, Solver solver) {
    GHResponse ghRsp = new GHResponse();
    StopWatch sw = new StopWatch().start();
    DirectedEdgeFilter directedEdgeFilter = solver.createDirectedEdgeFilter();
    List<Snap> snaps = ViaRouting.lookup(encodingManager, request.getPoints(), solver.createSnapFilter(), locationIndex, request.getSnapPreventions(), request.getPointHints(), directedEdgeFilter, request.getHeadings());
    ghRsp.addDebugInfo("idLookup:" + sw.stop().getSeconds() + "s");
    // (base) query graph used to resolve headings, curbsides etc. this is not necessarily the same thing as
    // the (possibly implementation specific) query graph used by PathCalculator
    QueryGraph queryGraph = QueryGraph.create(ghStorage, snaps);
    PathCalculator pathCalculator = solver.createPathCalculator(queryGraph);
    boolean passThrough = getPassThrough(request.getHints());
    boolean forceCurbsides = getForceCurbsides(request.getHints());
    ViaRouting.Result result = ViaRouting.calcPaths(request.getPoints(), queryGraph, snaps, directedEdgeFilter, pathCalculator, request.getCurbsides(), forceCurbsides, request.getHeadings(), passThrough);
    if (request.getPoints().size() != result.paths.size() + 1)
        throw new RuntimeException("There should be exactly one more point than paths. points:" + request.getPoints().size() + ", paths:" + result.paths.size());
    // here each path represents one leg of the via-route and we merge them all together into one response path
    ResponsePath responsePath = concatenatePaths(request, solver.weighting, queryGraph, result.paths, getWaypoints(snaps));
    responsePath.addDebugInfo(result.debug);
    ghRsp.add(responsePath);
    ghRsp.getHints().putObject("visited_nodes.sum", result.visitedNodes);
    ghRsp.getHints().putObject("visited_nodes.average", (float) result.visitedNodes / (snaps.size() - 1));
    return ghRsp;
}
Also used : ResponsePath(com.graphhopper.ResponsePath) GHResponse(com.graphhopper.GHResponse) Snap(com.graphhopper.storage.index.Snap) QueryGraph(com.graphhopper.routing.querygraph.QueryGraph)

Aggregations

QueryGraph (com.graphhopper.routing.querygraph.QueryGraph)37 Snap (com.graphhopper.storage.index.Snap)32 Test (org.junit.jupiter.api.Test)18 QueryRoutingCHGraph (com.graphhopper.routing.querygraph.QueryRoutingCHGraph)17 LocationIndexTree (com.graphhopper.storage.index.LocationIndexTree)16 EdgeIteratorState (com.graphhopper.util.EdgeIteratorState)11 Path (com.graphhopper.routing.Path)9 Weighting (com.graphhopper.routing.weighting.Weighting)9 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)7 RoutingAlgorithm (com.graphhopper.routing.RoutingAlgorithm)6 FastestWeighting (com.graphhopper.routing.weighting.FastestWeighting)6 PMap (com.graphhopper.util.PMap)6 ArrayList (java.util.ArrayList)6 GraphHopper (com.graphhopper.GraphHopper)5 GHPoint (com.graphhopper.util.shapes.GHPoint)5 ValueSource (org.junit.jupiter.params.provider.ValueSource)5 Graph (com.graphhopper.storage.Graph)4 LocationIndex (com.graphhopper.storage.index.LocationIndex)4 GHResponse (com.graphhopper.GHResponse)3 ResponsePath (com.graphhopper.ResponsePath)3