Search in sources :

Example 31 with QueryResult

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

the class RoundTripRoutingTemplate method generateValidPoint.

private QueryResult generateValidPoint(GHPoint from, double distanceInMeters, double heading, EdgeFilter edgeFilter) {
    int tryCount = 0;
    while (true) {
        GHPoint generatedPoint = Helper.DIST_EARTH.projectCoordinate(from.getLat(), from.getLon(), distanceInMeters, heading);
        QueryResult qr = locationIndex.findClosest(generatedPoint.getLat(), generatedPoint.getLon(), edgeFilter);
        if (qr.isValid())
            return qr;
        tryCount++;
        distanceInMeters *= 0.95;
        if (tryCount >= maxRetries)
            return null;
    }
}
Also used : QueryResult(com.graphhopper.storage.index.QueryResult) GHPoint(com.graphhopper.util.shapes.GHPoint) GHPoint(com.graphhopper.util.shapes.GHPoint)

Example 32 with QueryResult

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

the class GtfsReader method connectStopsToStreetNetwork.

private void connectStopsToStreetNetwork() {
    EdgeFilter filter = new EverythingButPt(encoder);
    for (Stop stop : feed.stops.values()) {
        QueryResult locationQueryResult = walkNetworkIndex.findClosest(stop.stop_lat, stop.stop_lon, filter);
        int streetNode;
        if (!locationQueryResult.isValid()) {
            streetNode = i++;
            nodeAccess.setNode(streetNode, stop.stop_lat, stop.stop_lon);
            graph.edge(streetNode, streetNode, 0.0, false);
        } else {
            streetNode = locationQueryResult.getClosestNode();
        }
        gtfsStorage.getStationNodes().put(stop.stop_id, streetNode);
    }
}
Also used : QueryResult(com.graphhopper.storage.index.QueryResult) Stop(com.conveyal.gtfs.model.Stop) EdgeFilter(com.graphhopper.routing.util.EdgeFilter)

Example 33 with QueryResult

use of com.graphhopper.storage.index.QueryResult 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));
        if (osmFile.contains("krautsand"))
            hopper.setMinNetworkSize(0, 0);
        // 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(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)

Example 34 with QueryResult

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

the class RoundTripRoutingTemplate method lookup.

@Override
public List<QueryResult> lookup(List<GHPoint> points, FlagEncoder encoder) {
    if (points.size() != 1 || ghRequest.getPoints().size() != 1)
        throw new IllegalArgumentException("For round trip calculation exactly one point is required");
    final double distanceInMeter = ghRequest.getHints().getDouble(RoundTrip.DISTANCE, 10000);
    final long seed = ghRequest.getHints().getLong(RoundTrip.SEED, 0L);
    double initialHeading = ghRequest.getFavoredHeading(0);
    final int roundTripPointCount = Math.min(20, ghRequest.getHints().getInt(RoundTrip.POINTS, 2 + (int) (distanceInMeter / 50000)));
    final GHPoint start = points.get(0);
    TourStrategy strategy = new MultiPointTour(new Random(seed), distanceInMeter, roundTripPointCount, initialHeading);
    queryResults = new ArrayList<>(2 + strategy.getNumberOfGeneratedPoints());
    EdgeFilter edgeFilter = new DefaultEdgeFilter(encoder);
    QueryResult startQR = locationIndex.findClosest(start.lat, start.lon, edgeFilter);
    if (!startQR.isValid())
        throw new PointNotFoundException("Cannot find point 0: " + start, 0);
    queryResults.add(startQR);
    GHPoint last = start;
    for (int i = 0; i < strategy.getNumberOfGeneratedPoints(); i++) {
        double heading = strategy.getHeadingForIteration(i);
        QueryResult result = generateValidPoint(last, strategy.getDistanceForIteration(i), heading, edgeFilter);
        if (result == null) {
            ghResponse.addError(new IllegalStateException("Could not find a valid point after " + maxRetries + " tries, for the point:" + last));
            return Collections.emptyList();
        }
        last = result.getSnappedPoint();
        queryResults.add(result);
    }
    queryResults.add(startQR);
    return queryResults;
}
Also used : PointNotFoundException(com.graphhopper.util.exceptions.PointNotFoundException) TourStrategy(com.graphhopper.routing.util.tour.TourStrategy) GHPoint(com.graphhopper.util.shapes.GHPoint) DefaultEdgeFilter(com.graphhopper.routing.util.DefaultEdgeFilter) QueryResult(com.graphhopper.storage.index.QueryResult) MultiPointTour(com.graphhopper.routing.util.tour.MultiPointTour) Random(java.util.Random) EdgeFilter(com.graphhopper.routing.util.EdgeFilter) DefaultEdgeFilter(com.graphhopper.routing.util.DefaultEdgeFilter) GHPoint(com.graphhopper.util.shapes.GHPoint)

Example 35 with QueryResult

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

the class RoundTripRoutingTemplate method calcPaths.

@Override
public List<Path> calcPaths(QueryGraph queryGraph, RoutingAlgorithmFactory algoFactory, AlgorithmOptions algoOpts) {
    pathList = new ArrayList<>(queryResults.size() - 1);
    AvoidEdgesWeighting avoidPathWeighting = new AvoidEdgesWeighting(algoOpts.getWeighting());
    avoidPathWeighting.setEdgePenaltyFactor(5);
    algoOpts = AlgorithmOptions.start(algoOpts).algorithm(Parameters.Algorithms.ASTAR_BI).weighting(avoidPathWeighting).build();
    algoOpts.getHints().put(Algorithms.AStarBi.EPSILON, 2);
    long visitedNodesSum = 0L;
    QueryResult start = queryResults.get(0);
    for (int qrIndex = 1; qrIndex < queryResults.size(); qrIndex++) {
        RoutingAlgorithm algo = algoFactory.createAlgo(queryGraph, algoOpts);
        // instead getClosestNode (which might be a virtual one and introducing unnecessary tails of the route)
        // use next tower node -> getBaseNode or getAdjNode
        // Later: remove potential route tail
        QueryResult startQR = queryResults.get(qrIndex - 1);
        int startNode = (startQR == start) ? startQR.getClosestNode() : startQR.getClosestEdge().getBaseNode();
        QueryResult endQR = queryResults.get(qrIndex);
        int endNode = (endQR == start) ? endQR.getClosestNode() : endQR.getClosestEdge().getBaseNode();
        Path path = algo.calcPath(startNode, endNode);
        visitedNodesSum += algo.getVisitedNodes();
        pathList.add(path);
        // it is important to avoid previously visited nodes for future paths
        avoidPathWeighting.addEdges(path.calcEdges());
    }
    ghResponse.getHints().put("visited_nodes.sum", visitedNodesSum);
    ghResponse.getHints().put("visited_nodes.average", (float) visitedNodesSum / (queryResults.size() - 1));
    return pathList;
}
Also used : QueryResult(com.graphhopper.storage.index.QueryResult) AvoidEdgesWeighting(com.graphhopper.routing.weighting.AvoidEdgesWeighting) GHPoint(com.graphhopper.util.shapes.GHPoint)

Aggregations

QueryResult (com.graphhopper.storage.index.QueryResult)39 GHPoint (com.graphhopper.util.shapes.GHPoint)20 Test (org.junit.Test)20 FastestWeighting (com.graphhopper.routing.weighting.FastestWeighting)4 LocationIndex (com.graphhopper.storage.index.LocationIndex)4 Weighting (com.graphhopper.routing.weighting.Weighting)3 LocationIndexTree (com.graphhopper.storage.index.LocationIndexTree)3 GHRequest (com.graphhopper.GHRequest)2 GHResponse (com.graphhopper.GHResponse)2 EdgeFilter (com.graphhopper.routing.util.EdgeFilter)2 EdgeIteratorState (com.graphhopper.util.EdgeIteratorState)2 PointNotFoundException (com.graphhopper.util.exceptions.PointNotFoundException)2 GHPoint3D (com.graphhopper.util.shapes.GHPoint3D)2 IntArrayList (com.carrotsearch.hppc.IntArrayList)1 IntObjectMap (com.carrotsearch.hppc.IntObjectMap)1 Stop (com.conveyal.gtfs.model.Stop)1 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 GraphHopper (com.graphhopper.GraphHopper)1 GHIntObjectHashMap (com.graphhopper.coll.GHIntObjectHashMap)1