Search in sources :

Example 1 with CustomModel

use of com.graphhopper.util.CustomModel in project graphhopper by graphhopper.

the class GraphHopperManaged method resolveCustomModelFiles.

public static List<Profile> resolveCustomModelFiles(String customModelFolder, List<Profile> profiles) {
    ObjectMapper yamlOM = Jackson.initObjectMapper(new ObjectMapper(new YAMLFactory()));
    ObjectMapper jsonOM = Jackson.newObjectMapper();
    List<Profile> newProfiles = new ArrayList<>();
    for (Profile profile : profiles) {
        if (!CustomWeighting.NAME.equals(profile.getWeighting())) {
            newProfiles.add(profile);
            continue;
        }
        Object cm = profile.getHints().getObject("custom_model", null);
        if (cm != null) {
            try {
                // custom_model can be an object tree (read from config) or an object (e.g. from tests)
                CustomModel customModel = jsonOM.readValue(jsonOM.writeValueAsBytes(cm), CustomModel.class);
                newProfiles.add(new CustomProfile(profile).setCustomModel(customModel));
                continue;
            } catch (Exception ex) {
                throw new RuntimeException("Cannot load custom_model from " + cm + " for profile " + profile.getName(), ex);
            }
        }
        String customModelFileName = profile.getHints().getString("custom_model_file", "");
        if (customModelFileName.isEmpty())
            throw new IllegalArgumentException("Missing 'custom_model' or 'custom_model_file' field in profile '" + profile.getName() + "'. To use default specify custom_model_file: empty");
        if ("empty".equals(customModelFileName))
            newProfiles.add(new CustomProfile(profile).setCustomModel(new CustomModel()));
        else {
            if (customModelFileName.contains(File.separator))
                throw new IllegalArgumentException("Use custom_model_folder for the custom_model_file parent");
            // Somehow dropwizard makes it very hard to find out the folder of config.yml -> use an extra parameter for the folder
            File file = Paths.get(customModelFolder).resolve(customModelFileName).toFile();
            try {
                CustomModel customModel = (customModelFileName.endsWith(".json") ? jsonOM : yamlOM).readValue(file, CustomModel.class);
                newProfiles.add(new CustomProfile(profile).setCustomModel(customModel));
            } catch (Exception ex) {
                throw new RuntimeException("Cannot load custom_model from location " + customModelFileName + " for profile " + profile.getName(), ex);
            }
        }
    }
    return newProfiles;
}
Also used : ArrayList(java.util.ArrayList) CustomProfile(com.graphhopper.routing.weighting.custom.CustomProfile) CustomProfile(com.graphhopper.routing.weighting.custom.CustomProfile) Profile(com.graphhopper.config.Profile) CustomModel(com.graphhopper.util.CustomModel) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 2 with CustomModel

use of com.graphhopper.util.CustomModel in project graphhopper by graphhopper.

the class CustomModelParserTest method setPriorityForRoadClass.

@Test
void setPriorityForRoadClass() {
    CustomModel customModel = new CustomModel();
    customModel.addToPriority(If("road_class == PRIMARY", MULTIPLY, 0.5));
    CustomWeighting.EdgeToDoubleMapping priorityMapping = CustomModelParser.createWeightingParameters(customModel, encodingManager, avgSpeedEnc, encoder.getMaxSpeed(), null).getEdgeToPriorityMapping();
    GraphHopperStorage graph = new GraphBuilder(encodingManager).create();
    EdgeIteratorState edge1 = graph.edge(0, 1).setDistance(100).set(roadClassEnc, RoadClass.PRIMARY);
    EdgeIteratorState edge2 = graph.edge(1, 2).setDistance(100).set(roadClassEnc, RoadClass.SECONDARY);
    assertEquals(0.5, priorityMapping.get(edge1, false), 1.e-6);
    assertEquals(1.0, priorityMapping.get(edge2, false), 1.e-6);
}
Also used : EdgeIteratorState(com.graphhopper.util.EdgeIteratorState) GraphBuilder(com.graphhopper.storage.GraphBuilder) CustomModel(com.graphhopper.util.CustomModel) GraphHopperStorage(com.graphhopper.storage.GraphHopperStorage) Test(org.junit.jupiter.api.Test)

Example 3 with CustomModel

use of com.graphhopper.util.CustomModel in project graphhopper by graphhopper.

the class RouteResourceCustomModelTest method createConfig.

private static GraphHopperServerConfiguration createConfig() {
    GraphHopperServerConfiguration config = new GraphHopperServerTestConfiguration();
    config.getGraphHopperConfiguration().putObject("graph.flag_encoders", "bike,car,foot,wheelchair,roads").putObject("prepare.min_network_size", 200).putObject("datareader.file", "../core/files/north-bayreuth.osm.gz").putObject("graph.location", DIR).putObject("graph.encoded_values", "max_height,max_weight,max_width,hazmat,toll,surface,track_type").putObject("custom_model_folder", "./src/test/resources/com/graphhopper/application/resources").setProfiles(Arrays.asList(new Profile("wheelchair"), new CustomProfile("roads").setCustomModel(new CustomModel()).setVehicle("roads"), new CustomProfile("car").setCustomModel(new CustomModel()).setVehicle("car"), new CustomProfile("bike").setCustomModel(new CustomModel().setDistanceInfluence(0)).setVehicle("bike"), new Profile("bike_fastest").setWeighting("fastest").setVehicle("bike"), new CustomProfile("truck").setVehicle("car").putHint("custom_model_file", "truck.yml"), new CustomProfile("cargo_bike").setVehicle("bike").putHint("custom_model_file", "cargo_bike.yml"), new CustomProfile("json_bike").setVehicle("bike").putHint("custom_model_file", "json_bike.json"), new Profile("foot_profile").setVehicle("foot").setWeighting("fastest"), new CustomProfile("car_no_unclassified").setCustomModel(new CustomModel(new CustomModel().addToPriority(If("road_class == UNCLASSIFIED", LIMIT, 0)))).setVehicle("car"), new CustomProfile("custom_bike").setCustomModel(new CustomModel().addToSpeed(If("road_class == PRIMARY", LIMIT, 28)).addToPriority(If("max_width < 1.2", MULTIPLY, 0))).setVehicle("bike"), new CustomProfile("custom_bike2").setCustomModel(new CustomModel(new CustomModel().addToPriority(If("road_class == TERTIARY || road_class == TRACK", MULTIPLY, 0)))).setVehicle("bike"), new CustomProfile("custom_bike3").setCustomModel(new CustomModel(new CustomModel().addToSpeed(If("road_class == TERTIARY || road_class == TRACK", MULTIPLY, 10)).addToSpeed(If("true", LIMIT, 40)))).setVehicle("bike"))).setCHProfiles(Arrays.asList(new CHProfile("truck"), new CHProfile("car_no_unclassified")));
    return config;
}
Also used : CHProfile(com.graphhopper.config.CHProfile) GraphHopperServerConfiguration(com.graphhopper.application.GraphHopperServerConfiguration) GraphHopperServerTestConfiguration(com.graphhopper.application.util.GraphHopperServerTestConfiguration) CustomProfile(com.graphhopper.routing.weighting.custom.CustomProfile) CustomProfile(com.graphhopper.routing.weighting.custom.CustomProfile) Profile(com.graphhopper.config.Profile) CHProfile(com.graphhopper.config.CHProfile) CustomModel(com.graphhopper.util.CustomModel)

Example 4 with CustomModel

use of com.graphhopper.util.CustomModel in project graphhopper by graphhopper.

the class PriorityRoutingTest method testMaxPriority.

@Test
void testMaxPriority() {
    BikeFlagEncoder encoder = new BikeFlagEncoder();
    EncodingManager em = EncodingManager.create(encoder);
    GraphHopperStorage graph = new GraphBuilder(em).create();
    NodeAccess na = graph.getNodeAccess();
    na.setNode(0, 48.0, 11.0);
    na.setNode(1, 48.1, 11.1);
    na.setNode(2, 48.2, 11.2);
    na.setNode(3, 48.3, 11.3);
    na.setNode(4, 48.1, 11.0);
    na.setNode(5, 48.2, 11.1);
    // 0 - 1 - 2 - 3
    // \- 4 - 5 -/
    double dist1 = 0;
    dist1 += maxSpeedEdge(em, graph, 0, 1, encoder, 1.0).getDistance();
    dist1 += maxSpeedEdge(em, graph, 1, 2, encoder, 1.0).getDistance();
    dist1 += maxSpeedEdge(em, graph, 2, 3, encoder, 1.0).getDistance();
    final double maxPrio = PriorityCode.getFactor(PriorityCode.BEST.getValue());
    double dist2 = 0;
    dist2 += maxSpeedEdge(em, graph, 0, 4, encoder, maxPrio).getDistance();
    dist2 += maxSpeedEdge(em, graph, 4, 5, encoder, maxPrio).getDistance();
    dist2 += maxSpeedEdge(em, graph, 5, 3, encoder, maxPrio).getDistance();
    // the routes 0-1-2-3 and 0-4-5-3 have similar distances (and use max speed everywhere)
    // ... but the shorter route 0-1-2-3 has smaller priority
    assertEquals(40101, dist1, 1);
    assertEquals(43005, dist2, 1);
    // A* and Dijkstra should yield the same path (the max priority must be taken into account by weighting.getMinWeight)
    {
        PriorityWeighting weighting = new PriorityWeighting(encoder, new PMap(), TurnCostProvider.NO_TURN_COST_PROVIDER);
        Path pathDijkstra = new Dijkstra(graph, weighting, TraversalMode.NODE_BASED).calcPath(0, 3);
        Path pathAStar = new AStar(graph, weighting, TraversalMode.NODE_BASED).calcPath(0, 3);
        assertEquals(pathDijkstra.calcNodes(), pathAStar.calcNodes());
        assertEquals(IntArrayList.from(0, 4, 5, 3), pathAStar.calcNodes());
    }
    {
        CustomModel customModel = new CustomModel();
        CustomWeighting weighting = CustomModelParser.createWeighting(encoder, em, TurnCostProvider.NO_TURN_COST_PROVIDER, customModel);
        Path pathDijkstra = new Dijkstra(graph, weighting, TraversalMode.NODE_BASED).calcPath(0, 3);
        Path pathAStar = new AStar(graph, weighting, TraversalMode.NODE_BASED).calcPath(0, 3);
        assertEquals(pathDijkstra.calcNodes(), pathAStar.calcNodes());
        assertEquals(IntArrayList.from(0, 4, 5, 3), pathAStar.calcNodes());
    }
    {
        CustomModel customModel = new CustomModel();
        // now we even increase the priority in the custom model, which also needs to be accounted for in weighting.getMinWeight
        customModel.addToPriority(Statement.If("road_class == MOTORWAY", Statement.Op.MULTIPLY, 3));
        CustomWeighting weighting = CustomModelParser.createWeighting(encoder, em, TurnCostProvider.NO_TURN_COST_PROVIDER, customModel);
        Path pathDijkstra = new Dijkstra(graph, weighting, TraversalMode.NODE_BASED).calcPath(0, 3);
        Path pathAStar = new AStar(graph, weighting, TraversalMode.NODE_BASED).calcPath(0, 3);
        assertEquals(pathDijkstra.calcNodes(), pathAStar.calcNodes());
        assertEquals(IntArrayList.from(0, 4, 5, 3), pathAStar.calcNodes());
    }
}
Also used : NodeAccess(com.graphhopper.storage.NodeAccess) PMap(com.graphhopper.util.PMap) CustomModel(com.graphhopper.util.CustomModel) GraphHopperStorage(com.graphhopper.storage.GraphHopperStorage) CustomWeighting(com.graphhopper.routing.weighting.custom.CustomWeighting) GraphBuilder(com.graphhopper.storage.GraphBuilder) PriorityWeighting(com.graphhopper.routing.weighting.PriorityWeighting) Test(org.junit.jupiter.api.Test)

Example 5 with CustomModel

use of com.graphhopper.util.CustomModel in project graphhopper by graphhopper.

the class DefaultWeightingFactory method createWeighting.

@Override
public Weighting createWeighting(Profile profile, PMap requestHints, boolean disableTurnCosts) {
    // Merge profile hints with request hints, the request hints take precedence.
    // Note that so far we do not check if overwriting the profile hints actually works with the preparation
    // for LM/CH. Later we should also limit the number of parameters that can be used to modify the profile.
    // todo: since we are not dealing with block_area here yet we cannot really apply any merging rules
    // for it, see discussion here: https://github.com/graphhopper/graphhopper/pull/1958#discussion_r395462901
    PMap hints = new PMap();
    hints.putAll(profile.getHints());
    hints.putAll(requestHints);
    FlagEncoder encoder = encodingManager.getEncoder(profile.getVehicle());
    TurnCostProvider turnCostProvider;
    if (profile.isTurnCosts() && !disableTurnCosts) {
        if (!encoder.supportsTurnCosts())
            throw new IllegalArgumentException("Encoder " + encoder + " does not support turn costs");
        int uTurnCosts = hints.getInt(Parameters.Routing.U_TURN_COSTS, INFINITE_U_TURN_COSTS);
        turnCostProvider = new DefaultTurnCostProvider(encoder, ghStorage.getTurnCostStorage(), uTurnCosts);
    } else {
        turnCostProvider = NO_TURN_COST_PROVIDER;
    }
    String weightingStr = toLowerCase(profile.getWeighting());
    if (weightingStr.isEmpty())
        throw new IllegalArgumentException("You have to specify a weighting");
    Weighting weighting = null;
    if (CustomWeighting.NAME.equalsIgnoreCase(weightingStr)) {
        if (!(profile instanceof CustomProfile))
            throw new IllegalArgumentException("custom weighting requires a CustomProfile but was profile=" + profile.getName());
        CustomModel queryCustomModel = requestHints.getObject(CustomModel.KEY, null);
        CustomProfile customProfile = (CustomProfile) profile;
        if (queryCustomModel != null)
            queryCustomModel.checkLMConstraints(customProfile.getCustomModel());
        queryCustomModel = CustomModel.merge(customProfile.getCustomModel(), queryCustomModel);
        weighting = CustomModelParser.createWeighting(encoder, encodingManager, turnCostProvider, queryCustomModel);
    } else if ("shortest".equalsIgnoreCase(weightingStr)) {
        weighting = new ShortestWeighting(encoder, turnCostProvider);
    } else if ("fastest".equalsIgnoreCase(weightingStr)) {
        if (encoder.supports(PriorityWeighting.class))
            weighting = new PriorityWeighting(encoder, hints, turnCostProvider);
        else
            weighting = new FastestWeighting(encoder, hints, turnCostProvider);
    } else if ("curvature".equalsIgnoreCase(weightingStr)) {
        if (encoder.supports(CurvatureWeighting.class))
            weighting = new CurvatureWeighting(encoder, hints, turnCostProvider);
    } else if ("short_fastest".equalsIgnoreCase(weightingStr)) {
        weighting = new ShortFastestWeighting(encoder, hints, turnCostProvider);
    }
    if (weighting == null)
        throw new IllegalArgumentException("Weighting '" + weightingStr + "' not supported");
    return weighting;
}
Also used : FlagEncoder(com.graphhopper.routing.util.FlagEncoder) PMap(com.graphhopper.util.PMap) CustomProfile(com.graphhopper.routing.weighting.custom.CustomProfile) CustomModel(com.graphhopper.util.CustomModel) CustomWeighting(com.graphhopper.routing.weighting.custom.CustomWeighting)

Aggregations

CustomModel (com.graphhopper.util.CustomModel)12 Test (org.junit.jupiter.api.Test)8 EdgeIteratorState (com.graphhopper.util.EdgeIteratorState)5 CustomProfile (com.graphhopper.routing.weighting.custom.CustomProfile)4 Profile (com.graphhopper.config.Profile)3 GraphHopperServerConfiguration (com.graphhopper.application.GraphHopperServerConfiguration)2 GraphHopperServerTestConfiguration (com.graphhopper.application.util.GraphHopperServerTestConfiguration)2 CustomWeighting (com.graphhopper.routing.weighting.custom.CustomWeighting)2 GraphBuilder (com.graphhopper.storage.GraphBuilder)2 GraphHopperStorage (com.graphhopper.storage.GraphHopperStorage)2 PMap (com.graphhopper.util.PMap)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)1 CHProfile (com.graphhopper.config.CHProfile)1 LMProfile (com.graphhopper.config.LMProfile)1 FlagEncoder (com.graphhopper.routing.util.FlagEncoder)1 PriorityWeighting (com.graphhopper.routing.weighting.PriorityWeighting)1 NodeAccess (com.graphhopper.storage.NodeAccess)1 JsonFeature (com.graphhopper.util.JsonFeature)1 File (java.io.File)1