Search in sources :

Example 21 with FlagEncoder

use of com.graphhopper.routing.util.FlagEncoder in project graphhopper by graphhopper.

the class LocationIndexTreeCHTest method testCHGraph.

@Test
public void testCHGraph() {
    GraphHopperStorage ghStorage = createGHStorage(new RAMDirectory(), encodingManager, false);
    CHGraph lg = ghStorage.getGraph(CHGraph.class);
    // 0
    // 1
    // 2
    // 3
    // 4
    NodeAccess na = ghStorage.getNodeAccess();
    na.setNode(0, 1, 0);
    na.setNode(1, 0.5, 0);
    na.setNode(2, 0, 0);
    na.setNode(3, -1, 1);
    na.setNode(4, -2, 2);
    EdgeIteratorState iter1 = ghStorage.edge(0, 1, 10, true);
    EdgeIteratorState iter2 = ghStorage.edge(1, 2, 10, true);
    EdgeIteratorState iter3 = ghStorage.edge(2, 3, 14, true);
    EdgeIteratorState iter4 = ghStorage.edge(3, 4, 14, true);
    // create shortcuts
    ghStorage.freeze();
    FlagEncoder car = encodingManager.getEncoder("car");
    long flags = car.setProperties(60, true, true);
    CHEdgeIteratorState iter5 = lg.shortcut(0, 2);
    iter5.setDistance(20).setFlags(flags);
    iter5.setSkippedEdges(iter1.getEdge(), iter2.getEdge());
    CHEdgeIteratorState iter6 = lg.shortcut(2, 4);
    iter6.setDistance(28).setFlags(flags);
    iter6.setSkippedEdges(iter3.getEdge(), iter4.getEdge());
    CHEdgeIteratorState tmp = lg.shortcut(0, 4);
    tmp.setDistance(40).setFlags(flags);
    tmp.setSkippedEdges(iter5.getEdge(), iter6.getEdge());
    LocationIndex index = createIndex(ghStorage, -1);
    assertEquals(2, findID(index, 0, 0.5));
}
Also used : CHEdgeIteratorState(com.graphhopper.util.CHEdgeIteratorState) FlagEncoder(com.graphhopper.routing.util.FlagEncoder) EdgeIteratorState(com.graphhopper.util.EdgeIteratorState) CHEdgeIteratorState(com.graphhopper.util.CHEdgeIteratorState) Test(org.junit.Test)

Example 22 with FlagEncoder

use of com.graphhopper.routing.util.FlagEncoder in project graphhopper by graphhopper.

the class SpatialRuleLookupHelper method buildAndInjectSpatialRuleIntoGH.

public static void buildAndInjectSpatialRuleIntoGH(GraphHopper graphHopper, CmdArgs args) {
    String spatialRuleLocation = args.get("spatial_rules.location", "");
    if (!spatialRuleLocation.isEmpty()) {
        try {
            final BBox maxBounds = BBox.parseBBoxString(args.get("spatial_rules.max_bbox", "-180, 180, -90, 90"));
            final InputStreamReader reader = new InputStreamReader(new FileInputStream(spatialRuleLocation), UTF_CS);
            final SpatialRuleLookup index = SpatialRuleLookupBuilder.buildIndex(new GHJsonFactory().create().fromJson(reader, JsonFeatureCollection.class), "ISO_A3", new CountriesSpatialRuleFactory(), .1, maxBounds);
            logger.info("Set spatial rule lookup with " + index.size() + " rules");
            final FlagEncoderFactory oldFEF = graphHopper.getFlagEncoderFactory();
            graphHopper.setFlagEncoderFactory(new FlagEncoderFactory() {

                @Override
                public FlagEncoder createFlagEncoder(String name, PMap configuration) {
                    if (name.equals(GENERIC)) {
                        return new DataFlagEncoder(configuration).setSpatialRuleLookup(index);
                    }
                    return oldFEF.createFlagEncoder(name, configuration);
                }
            });
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) DataFlagEncoder(com.graphhopper.routing.util.DataFlagEncoder) FlagEncoder(com.graphhopper.routing.util.FlagEncoder) PMap(com.graphhopper.util.PMap) SpatialRuleLookup(com.graphhopper.routing.util.spatialrules.SpatialRuleLookup) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) DataFlagEncoder(com.graphhopper.routing.util.DataFlagEncoder) BBox(com.graphhopper.util.shapes.BBox) GHJsonFactory(com.graphhopper.json.GHJsonFactory) JsonFeatureCollection(com.graphhopper.json.geo.JsonFeatureCollection) CountriesSpatialRuleFactory(com.graphhopper.routing.util.spatialrules.CountriesSpatialRuleFactory) FlagEncoderFactory(com.graphhopper.routing.util.FlagEncoderFactory)

Example 23 with FlagEncoder

use of com.graphhopper.routing.util.FlagEncoder in project graphhopper by graphhopper.

the class GraphHopperServlet method doGet.

@Override
public void doGet(HttpServletRequest httpReq, HttpServletResponse httpRes) throws ServletException, IOException {
    List<GHPoint> requestPoints = getPoints(httpReq, "point");
    GHResponse ghRsp = new GHResponse();
    double minPathPrecision = getDoubleParam(httpReq, WAY_POINT_MAX_DISTANCE, 1d);
    boolean writeGPX = "gpx".equalsIgnoreCase(getParam(httpReq, "type", "json"));
    boolean enableInstructions = writeGPX || getBooleanParam(httpReq, INSTRUCTIONS, true);
    boolean calcPoints = getBooleanParam(httpReq, CALC_POINTS, true);
    boolean enableElevation = getBooleanParam(httpReq, "elevation", false);
    boolean pointsEncoded = getBooleanParam(httpReq, "points_encoded", true);
    String vehicleStr = getParam(httpReq, "vehicle", "car");
    String weighting = getParam(httpReq, "weighting", "fastest");
    String algoStr = getParam(httpReq, "algorithm", "");
    String localeStr = getParam(httpReq, "locale", "en");
    StopWatch sw = new StopWatch().start();
    if (!ghRsp.hasErrors()) {
        try {
            if (requestPoints.isEmpty()) {
                throw new IllegalArgumentException("You have to pass at least one point");
            }
            List<Double> favoredHeadings = Collections.EMPTY_LIST;
            try {
                favoredHeadings = getDoubleParamList(httpReq, "heading");
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("heading list in wrong format: " + e.getMessage());
            }
            if (!encodingManager.supports(vehicleStr)) {
                throw new IllegalArgumentException("Vehicle not supported: " + vehicleStr);
            } else if (enableElevation && !hasElevation) {
                throw new IllegalArgumentException("Elevation not supported!");
            } else if (favoredHeadings.size() > 1 && favoredHeadings.size() != requestPoints.size()) {
                throw new IllegalArgumentException("The number of 'heading' parameters must be <= 1 " + "or equal to the number of points (" + requestPoints.size() + ")");
            }
            List<String> pointHints = Arrays.asList(getParams(httpReq, POINT_HINT));
            if (pointHints.size() > 0 && pointHints.size() != requestPoints.size()) {
                throw new IllegalArgumentException("If you pass " + POINT_HINT + ", you need to pass a hint for every point, empty hints will be ignored");
            }
            List<String> pathDetails = Arrays.asList(getParams(httpReq, PATH_DETAILS));
            FlagEncoder algoVehicle = encodingManager.getEncoder(vehicleStr);
            GHRequest request;
            if (favoredHeadings.size() > 0) {
                // if only one favored heading is specified take as start heading
                if (favoredHeadings.size() == 1) {
                    List<Double> paddedHeadings = new ArrayList<Double>(Collections.nCopies(requestPoints.size(), Double.NaN));
                    paddedHeadings.set(0, favoredHeadings.get(0));
                    request = new GHRequest(requestPoints, paddedHeadings);
                } else {
                    request = new GHRequest(requestPoints, favoredHeadings);
                }
            } else {
                request = new GHRequest(requestPoints);
            }
            initHints(request.getHints(), httpReq.getParameterMap());
            request.setVehicle(algoVehicle.toString()).setWeighting(weighting).setAlgorithm(algoStr).setLocale(localeStr).setPointHints(pointHints).setPathDetails(pathDetails).getHints().put(CALC_POINTS, calcPoints).put(INSTRUCTIONS, enableInstructions).put(WAY_POINT_MAX_DISTANCE, minPathPrecision);
            ghRsp = graphHopper.route(request);
        } catch (IllegalArgumentException ex) {
            ghRsp.addError(ex);
        }
    }
    float took = sw.stop().getSeconds();
    String infoStr = httpReq.getRemoteAddr() + " " + httpReq.getLocale() + " " + httpReq.getHeader("User-Agent");
    String logStr = httpReq.getQueryString() + " " + infoStr + " " + requestPoints + ", took:" + took + ", " + algoStr + ", " + weighting + ", " + vehicleStr;
    httpRes.setHeader("X-GH-Took", "" + Math.round(took * 1000));
    int alternatives = ghRsp.getAll().size();
    if (writeGPX && alternatives > 1)
        ghRsp.addError(new IllegalArgumentException("Alternatives are currently not yet supported for GPX"));
    if (ghRsp.hasErrors()) {
        logger.error(logStr + ", errors:" + ghRsp.getErrors());
    } else {
        PathWrapper altRsp0 = ghRsp.getBest();
        logger.info(logStr + ", alternatives: " + alternatives + ", distance0: " + altRsp0.getDistance() + ", time0: " + Math.round(altRsp0.getTime() / 60000f) + "min" + ", points0: " + altRsp0.getPoints().getSize() + ", debugInfo: " + ghRsp.getDebugInfo());
    }
    if (writeGPX) {
        if (ghRsp.hasErrors()) {
            httpRes.setStatus(SC_BAD_REQUEST);
            httpRes.getWriter().append(errorsToXML(ghRsp.getErrors()));
        } else {
            // no error => we can now safely call getFirst
            String xml = createGPXString(httpReq, httpRes, ghRsp.getBest());
            writeResponse(httpRes, xml);
        }
    } else {
        Map<String, Object> map = routeSerializer.toJSON(ghRsp, calcPoints, pointsEncoded, enableElevation, enableInstructions);
        Object infoMap = map.get("info");
        if (infoMap != null)
            ((Map) infoMap).put("took", Math.round(took * 1000));
        if (ghRsp.hasErrors())
            writeJsonError(httpRes, SC_BAD_REQUEST, objectMapper.getNodeFactory().pojoNode(map));
        else {
            writeJson(httpReq, httpRes, objectMapper.getNodeFactory().pojoNode(map));
        }
    }
}
Also used : FlagEncoder(com.graphhopper.routing.util.FlagEncoder) GHResponse(com.graphhopper.GHResponse) GHPoint(com.graphhopper.util.shapes.GHPoint) StopWatch(com.graphhopper.util.StopWatch) PathWrapper(com.graphhopper.PathWrapper) GHRequest(com.graphhopper.GHRequest) GHPoint(com.graphhopper.util.shapes.GHPoint)

Example 24 with FlagEncoder

use of com.graphhopper.routing.util.FlagEncoder in project graphhopper by graphhopper.

the class NodeContractor method initFromGraph.

void initFromGraph() {
    // todo: do we really need this method ? the problem is that ghStorage/prepareGraph can potentially be modified
    // between the constructor call and contractNode,calcShortcutCount etc. ...
    maxLevel = prepareGraph.getNodes() + 1;
    maxEdgesCount = ghStorage.getAllEdges().getMaxId();
    ignoreNodeFilter = new IgnoreNodeFilter(prepareGraph, maxLevel);
    FlagEncoder prepareFlagEncoder = prepareWeighting.getFlagEncoder();
    vehicleInExplorer = prepareGraph.createEdgeExplorer(new DefaultEdgeFilter(prepareFlagEncoder, true, false));
    vehicleOutExplorer = prepareGraph.createEdgeExplorer(new DefaultEdgeFilter(prepareFlagEncoder, false, true));
    prepareAlgo = new DijkstraOneToMany(prepareGraph, prepareWeighting, traversalMode);
}
Also used : FlagEncoder(com.graphhopper.routing.util.FlagEncoder) DijkstraOneToMany(com.graphhopper.routing.DijkstraOneToMany) DefaultEdgeFilter(com.graphhopper.routing.util.DefaultEdgeFilter)

Example 25 with FlagEncoder

use of com.graphhopper.routing.util.FlagEncoder in project graphhopper by graphhopper.

the class LMAlgoFactoryDecoratorTest method addWeighting.

@Test
public void addWeighting() {
    LMAlgoFactoryDecorator dec = new LMAlgoFactoryDecorator().setEnabled(true);
    dec.addWeighting("fastest");
    assertEquals(Arrays.asList("fastest"), dec.getWeightingsAsStrings());
    // special parameters like the maximum weight
    dec = new LMAlgoFactoryDecorator().setEnabled(true);
    dec.addWeighting("fastest|maximum=65000");
    dec.addWeighting("shortest|maximum=20000");
    assertEquals(Arrays.asList("fastest", "shortest"), dec.getWeightingsAsStrings());
    FlagEncoder car = new CarFlagEncoder();
    EncodingManager em = new EncodingManager(car);
    dec.addWeighting(new FastestWeighting(car)).addWeighting(new ShortestWeighting(car));
    dec.createPreparations(new GraphHopperStorage(new RAMDirectory(), em, false, new GraphExtension.NoOpExtension()), null);
    assertEquals(1, dec.getPreparations().get(0).getLandmarkStorage().getFactor(), .1);
    assertEquals(0.3, dec.getPreparations().get(1).getLandmarkStorage().getFactor(), .1);
}
Also used : EncodingManager(com.graphhopper.routing.util.EncodingManager) CarFlagEncoder(com.graphhopper.routing.util.CarFlagEncoder) FlagEncoder(com.graphhopper.routing.util.FlagEncoder) FastestWeighting(com.graphhopper.routing.weighting.FastestWeighting) CarFlagEncoder(com.graphhopper.routing.util.CarFlagEncoder) ShortestWeighting(com.graphhopper.routing.weighting.ShortestWeighting) RAMDirectory(com.graphhopper.storage.RAMDirectory) GraphHopperStorage(com.graphhopper.storage.GraphHopperStorage) Test(org.junit.Test)

Aggregations

FlagEncoder (com.graphhopper.routing.util.FlagEncoder)46 Test (org.junit.jupiter.api.Test)23 EncodingManager (com.graphhopper.routing.util.EncodingManager)19 CarFlagEncoder (com.graphhopper.routing.util.CarFlagEncoder)14 GraphBuilder (com.graphhopper.storage.GraphBuilder)14 EdgeIteratorState (com.graphhopper.util.EdgeIteratorState)13 GraphHopperStorage (com.graphhopper.storage.GraphHopperStorage)12 NodeAccess (com.graphhopper.storage.NodeAccess)10 Graph (com.graphhopper.storage.Graph)7 GHIntHashSet (com.graphhopper.coll.GHIntHashSet)6 Test (org.junit.Test)6 BikeFlagEncoder (com.graphhopper.routing.util.BikeFlagEncoder)5 FastestWeighting (com.graphhopper.routing.weighting.FastestWeighting)5 DecimalEncodedValue (com.graphhopper.routing.ev.DecimalEncodedValue)4 IntArrayList (com.carrotsearch.hppc.IntArrayList)3 GHBitSetImpl (com.graphhopper.coll.GHBitSetImpl)3 GHIntArrayList (com.graphhopper.coll.GHIntArrayList)3 LMProfile (com.graphhopper.config.LMProfile)3 ReaderWay (com.graphhopper.reader.ReaderWay)3 AllEdgesIterator (com.graphhopper.routing.util.AllEdgesIterator)3