Skip to content

Extend SpatialRules - #1799

Closed
otbutz wants to merge 35 commits into
graphhopper:masterfrom
otbutz:tollrules
Closed

otbutz wants to merge 35 commits into
graphhopper:masterfrom
otbutz:tollrules

Conversation

@otbutz

@otbutz otbutz commented Nov 19, 2019

Copy link
Copy Markdown
Contributor
  • allow to define fallback Toll values on a per country basis
  • add more countries

@otbutz

otbutz commented Nov 20, 2019

Copy link
Copy Markdown
Contributor Author

@karussell a few thoughts:

I'd like to extend the Country enum to include all existing countries(250) with their names. As i'm going to add rules for the most of Europe in this PR, we'll already need 7 bit to encode existing rules.

What are the benefits?

  • the code is generated once and shouldn't need any manual tinkering in the foreseeable future
  • we get code<->name relationship via Javadoc which lowers the possibility to confuse codes(e.g IRL/ISL)
  • the names could be used when returning path details
    DEFAULT("default"),
    /** Aruba */
    ABW("Aruba"),
    /** Afghanistan */
    AFG("Afghanistan"),
    /** Angola */
    AGO("Angola"),
    /** Anguilla */
    AIA("Anguilla"),
    /** Åland Islands */
    ALA("Åland Islands"),
    /** Albania */
    ALB("Albania"),

The aforementioned point of possible confusion also applies to the CountriesSpatialRuleFactory. We should ditch the String switch-case and use Country values instead as it's a CountriesSpatialRuleFactory after all. The SpatialRule.setBorders() call is also problematic and should probably deferred and only called once to ensure that implementers don't miss it.

I also thought about adding an interface which extends SpatialRule and enforces the use of country codes to obtain the id. Another annoyance is that the current rules extend DefaultSpatialRule with its getId() method being already implemented which might cause developers to forget that they need overwrite it.

What do you think about more fine grained configuration for spatial rules? Currently we allow to limit it via bbox which is fine for most cases but being able to select them via country codes or region aliases(europe,north america,etc) could be more flexible.

@karussell

karussell commented Nov 21, 2019 •

Copy link
Copy Markdown
Member

I really appreciate your work here as country-specific code is one of the weak points that we must solve.

My problem is that some unit/integration tests and the border geometry are missing. Instead of quantity I would rather start small, like with 2 or 3 countries that we tune towards quality. And already try to solve some of the code problems you mentioned to e.g. refactor the classes and interfaces etc. Maybe e.g. not only the border but also max_speed etc will end up in the configuration to avoid so many Java classes that do the same. And then hopefully other contributors would jump in to add their country file, they will do better than us as they know it best.

I don't see a big problem to extend this country code later and use a "default country" as fallback. We did this for other enums in the past and the graph will get incompatible and avoid problems. In fact frequent changes should be anticipated.

@otbutz

otbutz commented Nov 22, 2019

Copy link
Copy Markdown
Contributor Author

My problem is that some unit/integration tests and the border geometry are missing.

Yes, we're bit short on test coverage here. Adding basic test cases to check valid output for input combinations would be a good start. But at least the border geometries seem to be present or are you referring to border specific tests?

Instead of quantity I would rather start small, like with 2 or 3 countries that we tune towards quality. And already try to solve some of the code problems you mentioned to e.g. refactor the classes and interfaces etc. Maybe e.g. not only the border but also max_speed etc will end up in the configuration to avoid so many Java classes that do the same. And then hopefully other contributors would jump in to add their country file, they will do better than us as they know it best.

We won't get a full featured country ruleset over night that's for sure but it's the start of a gradual process. IMHO it's a bit easier for contributors to improve things which are already present and only need some minor tweaks. On the other hand i wanted to get a feel for handling country specific stuff first in order to decide which parts of the current model need to be changed or extended.

I don't see a big problem to extend this country code later and use a "default country" as fallback. We did this for other enums in the past and the graph will get incompatible and avoid problems. In fact frequent changes should be anticipated.

Oh, i thought it would be the other way around and you're trying to avoid frequent changes 😅

Current roadmap for this PR:

  • add the rules for the remaining European countries
  • refactor the existing classes to fix the problems mentioned above
  • add basic tests

@karussell

karussell commented Nov 22, 2019 •

Copy link
Copy Markdown
Member

Oh, i thought it would be the other way around and you're trying to avoid frequent changes sweat_smile

Aha :) ... where did you get the impression from?

But at least the border geometries seem to be present or are you referring to border specific tests?

Uh, strange. I have now searched at least 5 times but I cannot find any new json files. Where are they hidden :D ?

@otbutz

otbutz commented Nov 22, 2019

Copy link
Copy Markdown
Contributor Author

Oh, i thought it would be the other way around and you're trying to avoid frequent changes sweat_smile

Aha :) ... where did you get the impression from?

I thought that EncodedValue.getVersion() is guarding against unintentionally breaking compatibility with existing graphs. Didn't really think that it might be the other way around. But it makes sense though as the graph isn't really that "valuable".

But at least the border geometries seem to be present or are you referring to border specific tests?

Uh, strange. I have now searched at least 5 times but I cannot find any new json files. Where are they hidden :D ?

core/files/spatialrules/countries.geo.json seems to include the borders of all countries worldwide.

@karussell

karussell commented Nov 22, 2019 •

Copy link
Copy Markdown
Member

But it makes sense though as the graph isn't really that "valuable".

Yes, it protects from loading the wrong version as it will lead to exceptions or even silent reads of corrupted values. But this is for pure safety as we break the storage format frequently, it is not to force long-term stability, as you'll throw away the graph after X days anyway due to new OSM data.

core/files/spatialrules/countries.geo.json seems to include the borders of all countries worldwide

Ahaha, didn't know that - thanks! I can now remember that we had at least a few problems because the polygons there were not that proper (due to simplified lines). But that is for another issue.

I would still favor to include only countries where we at least have tested a route with and without the spatial rules and see that this rule is an improvement. I.e. if there is no problem, then we shouldn't fix it :). E.g. we currently do not really utilize the spatial index (and DataFlagEncoder will be hopefully removed soon) and so we should probably include it in the OSMMaxSpeedParser too? Then probably we should look up the SpatialRule only once and not once per TagParser (one time in toll parser + one time in the max_speed parser etc.).

And do you think we better should create one json file per country and include certain properties in those json files, so that we can avoid so many classes that contain basically constant numbers?

@otbutz

otbutz commented Nov 22, 2019 •

Copy link
Copy Markdown
Contributor Author

I would still favor to include only countries where we at least have tested a route with and without the spatial rules and see that this rule is an improvement. I.e. if there is no problem, then we shouldn't fix it :).

At least for toll they're a huge improvement because OSM is still lacking when it comes to data for commercial vehicles. That's the main reason my company wants to have these rules upstream and a sensible fallback value for max speed won't hurt either 😉

so we should probably include it in the OSMMaxSpeedParser too?

Good catch!

Then probably we should look up the SpatialRule only once and not once per TagParser (one time in toll parser + one time in the max_speed parser etc.).

Are we? The real lookup happens in the SpatialRuleParser and all other parsers check for the presence of a rule via the spatial_rule tag AFAIK:

SpatialRule spatialRule = readerWay.getTag("spatial_rule", null);
if (spatialRule != null)
accessValue = spatialRule.getAccess(readerWay.getTag("highway", ""), TransportationMode.MOTOR_VEHICLE, YES);

And do you think we better should create one json file per country and include certain properties in those json files, so that we can avoid so many classes that contain basically constant numbers?

Actually i'd argue that we should use one of the shapefiles provided by the Natural Earth project which is also being used to render the OSM map. These shapefiles receive updates on a regular basis, they are available in various resolutions and we profit from the many-eyes principle.

This would imply that we keep the actual rules in separate files which would only reference the affected country/countries using the countrycode but i'm not quite sure how to structure them. It's easy for maxspeed and toll but looking at the potential complexity of the road access matrix...yikes

Screenshot_2019-11-22 OSM tags for routing Access-Restrictions - OpenStreetMap Wiki

Mind you that the current approach seems to be geared towards country rules. Do we want to support rules for smaller entities like states/cities or even arbitrary ones? In that case we'd have to load multiple shape- or geojson files and the rule files would need to carry a key-value combination to reference the borders they're intended for eg ISOA3=DEU or ISO3166-2=DE-BY

@otbutz

otbutz commented Nov 22, 2019

Copy link
Copy Markdown
Contributor Author

and we would need to figure out how to handle priority for overlapping rules

@karussell

Copy link
Copy Markdown
Member

so we should probably include it in the OSMMaxSpeedParser too?
Good catch!

Ups, looks like we are already doing this in SpatialRuleParser and so this is already nicely decoupled from DataFlagEncoder.

And yes, you were right. The lookup is only done once and the special tag spatial_rule is set for all parsers.

Do we want to support rules for smaller entities like states/cities or even arbitrary ones?

Arbitrary would be very cool as then users could specify to avoid a custom area (constructions) or set a certain max or average speed for that area or similar. So basically the SpatialRule should be extendable to modify other attributes. And also then strings would be more appropriate for the area IDs than enums .. hmmh.

It's easy for maxspeed and toll but looking at the potential complexity of the road access matrix...yikes

Why is access so different to max_speed? At least for the most common scenarios we could let users define a country-dependent map like:

car.access:
   { motorway: true, primary: true }
bike.access:
   { cycleway: true, bridleway: true, ... }

Interesting. So this is very similar to the describe configurable Weighting in #1776 ... but no for routing, just for parsing.

and we would need to figure out how to handle priority for overlapping rules

First added, first rules :) ?

@otbutz

otbutz commented Nov 22, 2019

Copy link
Copy Markdown
Contributor Author

Quick summary

  1. Let the user configure a directory(e.g spatial_rules.shapefiles_dir) which may contain multiple shape files describing the areas he wants to manipulate:
shapes/
├── ne_50m_admin_0_countries.cpg
├── ne_50m_admin_0_countries.dbf
├── ne_50m_admin_0_countries.prj
├── ne_50m_admin_0_countries.shp
├── ne_50m_admin_0_countries.shx
├── us_states.cpg
├── us_states.dbf
├── us_states.prj
├── us_states.shp
└── us_states.shx
  1. The rules are specified using something like YAML or JSON and are kept in a second directory(e.g spatial_rules.rules_dir)
rules/
├── default.yml
├── austria.yml
├── germany.yml
├── netherlands.yml
├── california.yml
└── washington.yml
  1. A rule targets one or more areas by specifying key-value combinations which need to be present in the (multi)polygons. e.g ISOA3=DEU

Remaining problems

  • How do we decide which rule has the higher priority?
    • order of the files in the directory? -> IMHO a very bad idea
    • as part of the rule file? (e.g priority=100 for our standard country rules which would allow the user to define rules before and after ours)
  • How do we store the rule(s) which have been used in order to retrieve them later via PathDetails?
    • StringIndex?
  • How do we check if the rules/shapesfiles have been changed and we need to rebuild the graph?
    • Checksums?

@karussell

Copy link
Copy Markdown
Member

Let the user configure a directory(e.g spatial_rules.shapefiles_dir) which may contain multiple shape files describing the areas he wants to manipulate:

oh, but please no shapefiles :) ... geojson should be sufficient. This reminds me of our overlay data format which serves a very similar purpose:

https://raw.githubusercontent.com/graphhopper/graphhopper/master/core/src/test/resources/com/graphhopper/storage/change/overlaydata1.json

Remaining problems

Good questions :)

How do we check if the rules/shapesfiles have been changed and we need to rebuild the graph?

We don't check the changes to a .pbf file, so we should not do it here. We rebuild the graph only if the graph-cache folder is removed.

@otbutz

otbutz commented Nov 25, 2019

Copy link
Copy Markdown
Contributor Author

oh, but please no shapefiles :) ... geojson should be sufficient.

I'm more concerned about the quality of the data than the format. We could still use NaturalEarth data and convert it to geojson.

We don't check the changes to a .pbf file, so we should not do it here. We rebuild the graph only if the graph-cache folder is removed.

Sounds reasonable :)

@boldtrn

boldtrn commented Nov 25, 2019

Copy link
Copy Markdown
Member

Ahaha, didn't know that - thanks! I can now remember that we had at least a few problems because the polygons there were not that proper (due to simplified lines). But that is for another issue.

We could still use NaturalEarth data and convert it to geojson.

Our current dataset uses the NE data converted to geojson and simplified. AFAIK, the natural earth data is not accurate to the last meter but sort of resembles the border. Simplification adds some more inaccuracies as well.

I made some screenshots from the unsimplified natural earth data:

Screenshot from 2019-11-25 09-24-44
Screenshot from 2019-11-25 09-25-22
Screenshot from 2019-11-25 09-26-04

Our simplified version is slightly worse ins some places, but shouldn't be a lot worse.

Actually i'd argue that we should use one of the shapefiles provided by the Natural Earth project which is also being used to render the OSM map

Are you sure about that? I thought the OSM data is different to NE in many places?

and we would need to figure out how to handle priority for overlapping rules

Overlapping rules are not supported yet. I think the last rule in the geojson "wins". We would need to store multiple rules per array entry in the SpatialRuleArrayLookup. Once we can store multiple rules per array entry, we can think about how we can merge these rules, for example, assume the stricter rule.

@otbutz

otbutz commented Nov 25, 2019

Copy link
Copy Markdown
Contributor Author

Our current dataset uses the NE data converted to geojson and simplified.

I wasn't really aware that this is already the case 👍

AFAIK, the natural earth data is not accurate to the last meter but sort of resembles the border. Simplification adds some more inaccuracies as well.

Our simplified version is slightly worse ins some places, but shouldn't be a lot worse.

I think it's good enough for now. And geojson is an open standard so people are free to use country polygons with a higher resolution.

Are you sure about that? I thought the OSM data is different to NE in many places?

The international OSM style and the german fork both use the 110m admin0 dataset for the higher zoomlevels: https://github.com/gravitystorm/openstreetmap-carto/blob/master/INSTALL.md#manual-download

But I agree that rendering and routing are hardly comparable when it comes to the need for precision.

Overlapping rules are not supported yet. I think the last rule in the geojson "wins". We would need to store multiple rules per array entry in the SpatialRuleArrayLookup. Once we can store multiple rules per array entry, we can think about how we can merge these rules, for example, assume the stricter rule.

If we want to support user provided rules we need to figure this out first because it's going to be one of its major use cases IMHO. Graphhopper would ship with a set of default (country) rules which serve as a rough estimate and the user can provide more detailed ones to refine them.

@boldtrn

boldtrn commented Nov 25, 2019

Copy link
Copy Markdown
Member

The international OSM style and the german fork both use the 110m admin0 dataset for the higher zoomlevels: https://github.com/gravitystorm/openstreetmap-carto/blob/master/INSTALL.md#manual-download

Ah yes, for higher zoom levels this makes sense.

@otbutz

otbutz commented Nov 25, 2019

Copy link
Copy Markdown
Contributor Author

What would speak against using jts classes? This would solve the missing support of Polygons with holes and we could use existing SpatialIndex implementations.

@karussell

Copy link
Copy Markdown
Member

Nothing speaks against it. But then we would need a new geojson as the current simplified one contains overlapping geometries. There was an issue or comment somewhere about it.

@otbutz

otbutz commented Nov 26, 2019

Copy link
Copy Markdown
Contributor Author

I'd argue that overlapping border geometries are always problematic.

@karussell

Copy link
Copy Markdown
Member

I had another thought about country-specific rules. It is also related to #1280 where I just added yet another possibility (via CustomWeighting). With CustomWeighting we can customize the road access and max speed already. Of course I would not want to put all countries into one custom model but we could create one model per country e.g. custom_model_aut.yml and aut.geojson:

priority: road_class: { track: 0 }
max_speed: road_class: { trunk: 100, residential: 50 }

and then merge multiple models via CustomModel.merge.

So instead of a SpatialRule we would pick a CustomModel based on the GeoJSON. This would also solve the problem that access and max_speed could depend on vehicle properties (or lane count) instead of only TransportationMode.

The clear disadvantages are that this will only work with a CustomWeighting and relative late in the pipeline so that the max_speed and access are not explicitly stored. But we could even think about using only a CustomModel (without CustomWeighting?) and use new entries in the YAML to change existing encoded values like max_speed or introduce more like toll (see below).

The big advantages would that we could probably remove (parts of) the spatial rule functionality and get more flexibility without introducing yet another format.

Regarding your new use case:

allow to define fallback Toll values on a per country basis

that should move into another PR IMO. For now you could do this in a custom OSMTollParser (?)

btw: I'm entirely not sure if this here is a good idea, but I am thinking loud to push discussion into the direction to reduce the possibilities on how to handle area-specific stuff in GraphHopper and at the same time make it more powerful. Hopefully we can make progress here as country-specific rules would be a huge improvement regarding routing quality.

@otbutz

otbutz commented Jun 16, 2020

Copy link
Copy Markdown
Contributor Author

I think that we have to evaluate spatial rules in the import phase. All those point-in-polygon lookups are just way too costly to do this on a per request basis. This hits even harder if we use more detailed border polygons or if the user wants to use something like state level rules.

Reusing an existing format like CustomModel seems like a good idea. But we should think about what the scope of spatial rules should be. Do we want them to only provide fallback values if OSM values are not present? Do we want to cap/modify certain values e.g because we know that max speed for country x on roadclass y is value z?

And last but not least: i want to be able to retrieve the rule(s) via path details. e.g at which point did i cross the border

allow to define fallback Toll values on a per country basis

that should move into another PR IMO

Just an example but one of the main reasons my employer is interested in this topic.

@otbutz

otbutz commented Nov 19, 2021

Copy link
Copy Markdown
Contributor Author

I've opened #2450 for the toll fallback rules. The maxspeed rules will be subject of a different PR.

@otbutz otbutz closed this Nov 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants