Skip to content

create a custom profile on Android #2717

Closed

Description

@RGregat

I'm using the Java-API in my Android-Project to create offline routing. With the standard profiles everything works as it should. My next goal is now to use the CustomProfile functionality.

graphHopper.setProfiles(
            Profile("car")
                .setVehicle("car")
                .setWeighting("fastest")
                .setTurnCosts(false),
            CustomProfile("my_car_profile")
                .setCustomModel(CustomModel()
                    .addToPriority(If("road_class == PRIMARY", Statement.Op.MULTIPLY, "0.5"))
                    .addToSpeed(If("road_class == PRIMARY", Statement.Op.LIMIT, "28"))
                    .setDistanceInfluence(69.0)
                    .setHeadingPenalty(22.0)
                )
                .setVehicle("car")
                .setWeighting("custom")
        )

The CustomProfile leads to an exception very deep in graphhopper CustomModelParser.java:createClazz::172. I havn't looked into the SimpleCompiler code yet.

Is the specification of the CustomProfile wrong, am I missing something?

I'm using com.graphhopper:graphhopper-core:6.2, but tested version 6.0 as well without luck.

Activity

  1. easbar commented on Jan 7, 2023

    @easbar
    Member

    This is probably because the Janino library needed for custom models is missing and I am not sure if it works with Android at all.

  2. karussell commented on Jan 7, 2023

    @karussell
    Member

    See this issue janino-compiler/janino#191. It is a mess with Android, but instead of messing with byte code, for GraphHopper it should be possible to create the Java source file via janino with a real JVM (openjdk) and use this class for Android instead of the inbuilt mechanism. (at least for profiles that are known at start)

    To create the Java Weighting class you specify -Dorg.codehaus.janino.source_debugging.enable=true as JVM (openjdk) parameter and the output directory -Dorg.codehaus.janino.source_debugging.dir=/home/user/somedir (the directory must exist). See CustomModelParser.

    To use this class you do:

    CustomModel customModel = new CustomModel()...
    CustomWeightingHelper prio = new <the_generated_class>();
    prio.init(lookup, avgSpeedEnc, priorityEnc, customModel.getAreas());
    CustomWeighting.Parameters parameters = new CustomWeighting.Parameters(prio::getSpeed, prio::getPriority, prio.getMaxSpeed(), prio.getMaxPriority(), customModel.getDistanceInfluence(), customModel.getHeadingPenalty());
    Weighting myWeighting = new CustomWeighting(accessEnc, speedEnc, turnCostProvider, parameters);

    Return this weighting from your own DefaultWeightingFactory and inject this into the GraphHopper class:

    GraphHopper graphHopper = new GraphHopper() {
      protected WeightingFactory createWeightingFactory() {
        return new DefaultWeightingFactory() {
           public Weighting createWeighting(Profile profile, PMap requestHints, boolean disableTurnCosts) {
                 if("custom".equals(profile.getWeighting()))
                    // see DefaultWeightingFactory on how to get the required objects like accessEnc, speedEnc, etc
                    return myWeighting;
                return super.createWeighting(profile, requestHints, disableTurnCosts);
           }
        }
      }
    }

    Please let us know if you have success with this approach. The same approach should be possible to make the latest GH version working for our iOS port.

  3. changed the title [-]Java API create a custom profile[/-] [+]Java API create a custom profile on Android[/+] on Jan 7, 2023
  4. changed the title [-]Java API create a custom profile on Android[/-] [+]create a custom profile on Android[/+] on Jan 7, 2023
  5. RGregat commented on Jan 8, 2023

    @RGregat
    Author

    First of all thx for the quick response. I have now copied the relevant Graphhoper Code into a Java-Project which I have created with the IntelliJ Idea IDE.
    Than I have added the additional parameters you have mentioned

    image

    After the execution I have got this java file

    package com.graphhopper.routing.weighting.custom;
    
    import com.graphhopper.routing.weighting.custom.CustomWeightingHelper;
    import com.graphhopper.routing.ev.EncodedValueLookup;
    import com.graphhopper.util.EdgeIteratorState;
    import com.graphhopper.routing.ev.*;
    import java.util.Map;
    
    public class JaninoCustomWeightingHelperSubclass2 extends CustomWeightingHelper {
    
        @Override public void init(
            EncodedValueLookup lookup,
            com.graphhopper.routing.ev.DecimalEncodedValue avgSpeedEnc,
            com.graphhopper.routing.ev.DecimalEncodedValue priorityEnc,
            Map<String, com.graphhopper.util.JsonFeature> areas
        ) {
            this.avg_speed_enc = avgSpeedEnc;
            this.priority_enc = priorityEnc;
            if (lookup.hasEncodedValue("road_class")) this.road_class_enc = (EnumEncodedValue) lookup.getEncodedValue("road_class", EncodedValue.class);
        }
    
        @Override public double getPriority(EdgeIteratorState edge, boolean reverse) {
            double value = super.getRawPriority(edge, reverse);
    
            return value;
        }
    
        @Override public double getSpeed(EdgeIteratorState edge, boolean reverse) {
            double value = super.getRawSpeed(edge, reverse);
            Enum road_class = reverse ? edge.getReverse((EnumEncodedValue) this.road_class_enc) : edge.get((EnumEncodedValue) this.road_class_enc);
    
            if (road_class == RoadClass.PRIMARY) {
                value = Math.min(value, 28);
            }
            return value;
        }
    
        @Override protected double getMaxSpeed() {
            return 135.0;
        }
    
        @Override protected double getMaxPriority() {
            return 1.0;
        }
    
        protected EnumEncodedValue road_class_enc;
    }

    Next step is to add this to my Android-Project. I keep you informed if that is working as well!

  6. RGregat commented on Jan 8, 2023

    @RGregat
    Author

    I have encountered a problem. CustomWeighting.Parameters is Package-Private and therefore I'm not able to use it to describe my CustomProfile. Any idea how to solve this issue? I already tried reflection, but the constructor CustomWeighting is not satisfied with just an Object.

    And where does avgSpeedEnc and priorityEnc actually come from?

  7. karussell commented on Jan 9, 2023

    @karussell
    Member

    @easbar what do you think about making this public? (IMO it is currently suboptimal that CustomWeighting is public but this Parameters class is not, although it is part of the public constructor)

  8. easbar commented on Jan 9, 2023

    @easbar
    Member

    Yes, sure.

  9. karussell commented on Jan 9, 2023

    @karussell
    Member

    @RGregat with the latest master this should be possible now.

    And where does avgSpeedEnc and priorityEnc actually come from?

    See the DefaultWeightingFactory:

    BooleanEncodedValue accessEnc = encodingManager.getBooleanEncodedValue(VehicleAccess.key(vehicle));
    DecimalEncodedValue speedEnc = encodingManager.getDecimalEncodedValue(VehicleSpeed.key(vehicle));
    DecimalEncodedValue priorityEnc = encodingManager.hasEncodedValue(VehiclePriority.key(vehicle))
            ? encodingManager.getDecimalEncodedValue(VehiclePriority.key(vehicle)) : null;
  10. RGregat commented on Jan 10, 2023

    @RGregat
    Author

    Thx for the change, I have now cloned this repository and added core and web-api as modules into my Android-Project. That is the only way to integrate the updates you made. I also found out that it is not enough to set the static class Parameter to public, the visibility of the constructor has to be changed as well to public.

    And just for anyone who is interested to add the source code directly

    1. Open a Terminal
    2. Navigate to the root folder of an Android Project
    3. Clone the complete Graphhopper Repository (well I think it is important to clone it directly into the root Android Project Folder, it should work from any place I guess)
    4. Enter the cloned graphhopper repository folder
    5. Execute gradlew init
    6. Start Android Studio
    7. Open the settings.gradle
    include ':graphhopper-core'
    include ':graphhopper-web-api'
    project(':graphhopper-core').projectDir = new File(rootDir, 'graphhopper/core')
    project(':graphhopper-web-api').projectDir = new File(rootDir, 'graphhopper/web-api')
    1. Open the build.gradle from the core project
    plugins {
        id 'java'
        //id 'com.graphhopper.java-conventions'
    }
    
    ...
    
    java {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    
    1. Open the build.gradle from the web-api project
    plugins {
        id 'java'
        //id 'com.graphhopper.java-conventions'
    }
    
    java {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    
    1. Press the sync button and double cross your fingers :)
  11. karussell commented on Jan 11, 2023

    @karussell
    Member

    and added core and web-api as modules into my Android-Project. That is the only way to integrate the updates you made

    After a new release of GraphHopper this won't be necessary, I guess.

    But finally it worked for you?

    the visibility of the constructor has to be changed as well to public.

    I've added this change as well.

  12. RGregat commented on Jan 11, 2023

    @RGregat
    Author

    After a new release of GraphHopper this won't be necessary, I guess.

    That is true, but It's also good to know how to add the lib as a module :)

  13. added a commit that references this issue on Jun 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions