Skip to content

Infer default speed limits #2392

Closed
Closed

Description

@westnordost

This issue ticket's purpose is to

  1. get feedback from you guys if inferring default speed limits is desired at all
  2. get feedback from you guys if the default speed limit data as provided is in a format you are able to make use of etc.
  3. finally, serve as a starting-area / feature request to implement this

Assumptions

The maximum allowed speed on any given road is an important factor to rate the costing of edges in the graph and travel time.

maxspeed coverage in OSM is sketchy and likely will always be: Currently, only about 12% of all roads have a speed limit tagged.

Additionally, maxspeed is just for cars. Other vehicles such as trucks, buses, motorhomes, cars with trailers or motorcycles will, depending on the road type, have different maximum speed limits that are often below the signed one.

Implicit speed limits

When speed limits are not signed, the default speed limits apply. (Maybe more so outside the United States. I heard that in the US, things are usually always explicitly signed.) Regardless of the reason why maxspeed is missing - nothing is signed or information is still missing - the actual speed limits can be inferred by looking at the legislation.

For example, in Hungary, the default speed limits are as follows

  • 20 km/h on a living street
  • 30 km/h on a bicycle road
  • 50 km/h on any other urban road
  • 90 km/h on a non-urban road, except for vehicles pulling a trailer, with a GVWR of 3.5t, buses or trucks for which it is 70 km/h
  • 110 km/h on motorroads, except for the vehicle types mentioned above for which it is still 70 km/h
  • 130 km/h on a motorway. For buses however, it's 100 km/h. For vehicles, pulling a trailer, with a GVWR of 3.5t or more and trucks, it is 80 km/h

So, if a road in Hungary is tagged with e.g. highway=living_street or motorroad=yes, we can easily infer the implicit speed limit from the above information. Hungary however is a rather easy example.

Sourcing implicit speed limits

The legislations as the one above have been collected over the years on the OSM wiki page Default speed limits in a well-researched (with links to the actual legislation) and machine-readable form. @ianthetechie and me have been working on a Python parser for this table that outputs the information in it as a JSON-file so that it can easily be consumed by (routing) software.

This is how it currently looks like: default_speeds.json

See how it looks for Hungary
"HU": [
    {
      "filter": "highway=living_street or living_street=yes",
      "name": "living street",
      "tags": {
        "maxspeed": "20"
      }
    },
    {
      "filter": "bicycle_road=yes or cyclestreet=yes",
      "name": "bicycle road",
      "tags": {
        "maxspeed": "30"
      }
    },
    {
      "filter": "{is_urban}",
      "name": "urban",
      "tags": {
        "maxspeed": "50"
      }
    },
    {
      "tags": {
        "maxspeed": "90",
        "maxspeed:bus": "70",
        "maxspeed:hgv": "70",
        "maxspeed:conditional": "70 @ (weightrating>3.5); 70 @ (trailer)"
      }
    },
    {
      "filter": "motorroad=yes",
      "name": "motorroad",
      "tags": {
        "maxspeed": "110",
        "maxspeed:bus": "70",
        "maxspeed:hgv": "70",
        "maxspeed:conditional": "70 @ (weightrating>3.5); 70 @ (trailer)"
      }
    },
    {
      "filter": "highway~^motorway(_link)?$",
      "name": "motorway",
      "tags": {
        "maxspeed": "130",
        "maxspeed:bus": "100",
        "maxspeed:hgv": "80",
        "maxspeed:conditional": "80 @ (weightrating>3.5); 80 @ (trailer)"
      }
    }
  ]

Inherent complexity

Already in the example for Hungary, the following becomes clear:

Filter-based mapping

There can not be a 1:1 mapping of highway=X to speed limit rules because

  • there is no (single) tag for "urban road". It may be sourced from other information such as source:maxspeed=HU:urban and similar tags, by looking at the location of traffic_sign=city_limit signs, whether or not a road is in- or outside of a respective city limit boundary or fuzzily by looking at tags such as lit=yes/no and similar (because roads outside of settlements are usually not lit)
  • sometimes different tags are synonymous in OSM
  • sometimes the legal road type matches multiple different tags on OSM
  • sometimes the legal road type depends on such things as whether a road is lit or not (e.g. United Kingdom), whether the oncoming traffic is segregated (e.g. Germany) or whether the road is paved at all (e.g. Georgia, US)

Instead, it must be based on filtering by OSM tags. For example, the default speed limit in Illinois for roads where the oncoming traffic is segregated and there are 2 or more lanes in each direction would be 65 mph. For interstates, it would be 70 mph.
The filters (in pseudo-Overpass-Wizard, ~ meaning it would be a regex-match) for that would be:

  • oneway ~ ^yes|-1$ and lanes >= 2 and dual_carriageway != no -> 65 mph
  • ref ~ ^I and highway ~ ^motorway|motorway_link$ -> 70 mph

To have a parser for such pseudo-Overpass-Wizard syntax adds quite some complexity, I believe.

Rules for when multiple road types match

For example, a bicycle road is also an urban road, so both filters match for an urban bicycle road. Which speed limit applies?
The wiki page explains the rules for which the right road type should be selected. This is not super complex, but still adds to it before one can make proper use of the data.

Reverse country/state geocoder

Not every motorway with a ref code starting with I is an US interstate highway. This rule may only be applied in the US. Thus, the router must know in which country/state any given road is located. (Should be no problem though if you use a database with geospatial extensions. I can give pointers.)

Advanced maxspeed and maxspeed:conditional parsing

The information in the default speed limits table is translated into OSM tags, including maxspeed:conditional and maxspeed:<vehicle type>. Thus, to interpret the limits correctly, it's necessary for the (router) software to also parse the information in these tags correctly.
Whether this adds complexity or not depends on if Graphhopper can already parse these, as these are normal OSM maxspeed tags.

Your Feedback necessary

So, the mentioned parser hasn't been worked on for quite some time because we need feedback from you. No point in creating something if it isn't used or doesn't even have the chance of being used. See the points at the very beginning of this ticket.

I may have some time in the near future to improve on this and also maintain the source data, so:

Do you think this data is useful? Can you work with this data? What is necessary to work with it? Do you have suggestions on how else this data could be represented? Do you have other questions?


I posted the same ticket also at Valhalla. Not at OSRM because it seems to be in maintenance mode.

Activity

  1. otbutz commented on Sep 23, 2021

    @otbutz
    Contributor

    This rule may only be applied in the US. Thus, the router must know in which country/state any given road is located.

    This is already a solved problem. See CountryRule and our border polygons

    We've a lack of country specific implementations though and things like urban/non-urban are yet to be solved.

  2. westnordost commented on Sep 23, 2021

    @westnordost
    Author

    This rule may only be applied in the US. Thus, the router must know in which country/state any given road is located.

    This is already a solved problem. See CountryRule and our border polygons

    Cool! I see you put the border polygons into a spatial index before accessing it, so the point-in-polygon check only needs to be done for one or a few polygons instead of all. If you need it even a bit faster, there is also https://github.com/westnordost/countryboundaries because in many cases, no pip-checks need to be done at all anymore. But this is a bit off topic I guess.

    We've a lack of country specific implementations though and things like urban/non-urban are yet to be solved.

    I see, so currently, Graphhopper doesn't know for any given (e.g.) highway=unclassified whether a speed limit of about 50 km/h (urban) or 70-100 km/h (rural) speed limit applies if none is given? How is this treated currently?

    There are some solutions for this. I think the easiest would be to start interpreting source:maxspeed=...:urban-like tags but for a fuzzy match, other tags could be looked at too, e.g. shoulder (usually only outside settlements), sidewalk (usually only inside), lit (usually only inside) etc.

  3. westnordost commented on Sep 23, 2021

    @westnordost
    Author

    Yes, the boundaries file of JOSM is really precise (I contributed to it myself). The precision is about that one can be sure that every hamlet and maybe even every road is on the right side of the border.

  4. otbutz commented on Sep 23, 2021

    @otbutz
    Contributor

    How is this treated currently?

    Global default values which is kinda ugly:

    // autobahn
    defaultSpeedMap.put("motorway", 100);
    defaultSpeedMap.put("motorway_link", 70);
    defaultSpeedMap.put("motorroad", 90);
    // bundesstraße
    defaultSpeedMap.put("trunk", 70);
    defaultSpeedMap.put("trunk_link", 65);
    // linking bigger town
    defaultSpeedMap.put("primary", 65);
    defaultSpeedMap.put("primary_link", 60);
    // linking towns + villages
    defaultSpeedMap.put("secondary", 60);
    defaultSpeedMap.put("secondary_link", 50);
    // streets without middle line separation
    defaultSpeedMap.put("tertiary", 50);
    defaultSpeedMap.put("tertiary_link", 40);
    defaultSpeedMap.put("unclassified", 30);
    defaultSpeedMap.put("residential", 30);
    // spielstraße
    defaultSpeedMap.put("living_street", 5);
    defaultSpeedMap.put("service", 20);
    // unknown road
    defaultSpeedMap.put("road", 20);
    // forestry stuff
    defaultSpeedMap.put("track", 15);
    trackTypeSpeedMap.put("grade1", 20); // paved
    trackTypeSpeedMap.put("grade2", 15); // now unpaved - gravel mixed with ...
    trackTypeSpeedMap.put("grade3", 10); // ... hard and soft materials
    trackTypeSpeedMap.put(null, defaultSpeedMap.get("track"));
    // limit speed on bad surfaces to 30 km/h
    badSurfaceSpeed = 30;
    maxPossibleSpeed = 140;

    I think the easiest would be to start interpreting source:maxspeed=...:urban-like tags

    We could pass our rules down to the OSMMaxSpeedParser to accomplish this.

    Offtopic: i really dig your app. IMHO one of the best tools to easily contribute to OSM.

  5. otbutz commented on Sep 23, 2021

    @otbutz
    Contributor

    We could factor in landuse to detect urban roads. But that's a metric shitton of point-in-polygon lookups.

  6. karussell commented on Sep 23, 2021

    @karussell
    Member

    I see, so currently, Graphhopper doesn't know for any given (e.g.) highway=unclassified whether a speed limit of about 50 km/h (urban) or 70-100 km/h (rural) speed limit applies if none is given? How is this treated currently?

    We have some work done for our commercial Routing API (we called it "speedmodels") which we would like to open source. Basically we collected (and manually created) raster images from several data sources that define urban areas and then we have some logic to set the estimated speeds (based on urban/rural and road class etc). This is also what you see at GraphHopper Maps. And as we are working on reducing the differences of the open source routing engine and our Routing API this is probably the next big task for us and the community :)

    One problem is also that this code is old, not easy to extend and limited to raster data, so maybe the best way would be to rewrite it from scratch to fill something like a is_rural encoding value.

    I think the easiest would be to start interpreting

    Every island solution will either cause problems or require a post-processing step where the neighboring street segments needs to be touched as well to avoid strange detours around these "single" obstacles. See the issue #382.

    IMHO one of the best tools to easily contribute to OSM.

    Kudos from me to you @westnordost too 👍 !

    We could factor in landuse to detect urban roads. But that's a metric shitton of point-in-polygon lookups.

    The problem is here more that the coverage for that is not great everywhere outside Europe.

  7. westnordost commented on Sep 23, 2021

    @westnordost
    Author

    We could factor in landuse to detect urban roads. But that's a metric shitton of point-in-polygon lookups.

    Plus, landuse=residential is often cut to explicitly not include the roads and sidewalks, e.g. https://www.openstreetmap.org/#map=18/53.57070/9.97422

    If you are doing something geospatial, probably point-in-polygon checks with admin boundary relations... oh wait, nevermind, that won't work. https://www.openstreetmap.org/relation/445840#map=13/53.5076/9.5882

    We really need a is_urban=yes/no tag in OSM, don't we? Currently, what comes closest to that is zone:traffic=DE:urban which follows the source:maxspeed/maxspeed:type scheme of <country_code>:<road_type> but as far as I understand, may also be set when a maxspeed sign is present because it just describes the location of the street, not what maxspeed should be valid in the absence of a sign (only). Anyway, I guess for router software, that difference in definition doesn't matter.

  8. karussell commented on Sep 23, 2021

    @karussell
    Member

    We really need a is_urban=yes/no tag in OSM

    I would not want to set this tag on all OSM ways :) ... having the urban boundaries relations complete would fix this already, but even they are sparse for small towns even (not to mention hamlets etc). So I guess external sources (like "AI work" from satellite images) are our best source.

  9. westnordost commented on Sep 23, 2021

    @westnordost
    Author

    having the urban boundaries relations complete would fix this already

    But how? This boundary obviously also includes rural roads https://www.openstreetmap.org/relation/445840#map=13/53.5076/9.5882

  10. karussell commented on Sep 23, 2021

    @karussell
    Member

    Ok, they would fix it probably not 100% ;) but this would be already better than relying on some rough raster images (what we currently do) and likely the incorrectly contained (bigger) rural roads contain the maxspeed tag already. To make it really 100% we would need indeed a new relation defining an area where the default maxspeed should be considered to avoid tagging every single way.
    Or the more pragmatic solution: we always use the urban boundaries and assume default maxspeed but every way, which would get an incorrect max. speed, would need an explicit maxspeed tag.

  11. westnordost commented on Sep 23, 2021

    @westnordost
    Author

    So, back the OP topic: Do you think the data in the wiki in the form currently shown in the JSON would be useful and could be made use of? What would need to be done do enable this? Do you for example have the capability to parse a filter syntax similar to the one used in the JSON already? Can you already interpret (all the) maxspeed conditional rules, and the maxspeed:<vehicle_type> rules?

  12. otbutz commented on Sep 23, 2021

    @otbutz
    Contributor

    The first step should be to harmonize min/max/avg speed handling. see #2266

    We should probably deal with upper and lower bounds for max speed in country rules and derive the average speed from those values.

    e.g:

    • max_speed is tagged with 80kmh -> lower=80, upper=80
    • tertiary in DE -> lower=50, upper=100

    This would allow us to use the values provided by the OSM wiki and yield more detailed avg speeds per country.

  13. karussell commented on Sep 23, 2021

    @karussell
    Member

    So, back the OP topic:

    To have a parser for such pseudo-Overpass-Wizard syntax adds quite some complexity, I believe.

    Yes, but probably doable. Would it be possible to change this notation? Something without "full regex support" and just *, like:

    highway*=motorway or highway*=motorway_link (I hope I correctly interpreted the regex match ~?)

    Same for the oneway:

    (oneway*=yes or oneway*=-1) and ...

    This way we could even use our internal janino engine to interpret the filters. (see our custom weightings for examples of them)

  14. westnordost commented on Sep 23, 2021

    @westnordost
    Author

    highway*=motorway or highway*=motorway_link (I hope I correctly interpreted the regex match ~?)

    I think it would. Or replacing regexes with (... or .... or ... or). Looking at https://wiki.openstreetmap.org/wiki/Default_speed_limits#Road_Type_to_tag_filters_table the number of regex used is managable.

    I do by the way have in StreetComplete (an even more complex) syntax parser and I guess it would be possible to outsource this into a library if there is interest. It is written in Kotlin though. This is also a JVM language, but comes with Kotlin Standard Library for JVM as default dependency which weights 1.4 MB.

    An example of a more complex expression the parser is able to parse:
    https://github.com/streetcomplete/StreetComplete/blob/master/app/src/main/java/de/westnordost/streetcomplete/quests/sidewalk/AddSidewalk.kt#L27-L47

  15. 29 remaining items

  16. easbar commented on Aug 22, 2022

    @easbar
    Member

    Yes I thought the same and it looked pretty strange:

    image

    One of the files starts like this:

    // IntelliJ API Decompiler stub source generated from a class file
    // Implementation of methods is not available
    
    package de.westnordost.osm_legal_default_speeds
    
    public final enum class Certitude private constructor() : kotlin.Enum<de.westnordost.osm_legal_default_speeds.Certitude> {
        Exact,
    
        FromMaxSpeed,
    
        Fuzzy,
    
        Fallback;
    }
    
    public final class LegalDefaultSpeeds public constructor(roadTypesByName: kotlin.collections.Map<kotlin.String, de.westnordost.osm_legal_default_speeds.RoadTypeFilter>, speedLimitsByCountryCode: kotlin.collections.Map<kotlin.String, kotlin.collections.List<de.westnordost.osm_legal_default_speeds.RoadType>>) {
        private final val roadTypeFilters: kotlin.collections.Map<kotlin.String, de.westnordost.osm_legal_default_speeds.RoadTypeTagFilterExpressions> /* compiled code */
  17. easbar commented on Aug 22, 2022

    @easbar
    Member

    Do you have an example where you used the artifact in an (otherwise Java-only) gradle project?

  18. westnordost commented on Aug 22, 2022

    @westnordost
    Author

    No. I've never used kotlin dependencies in Java projects, only the other way round. I'd also need to read up on that if there is anything special about it.

  19. westnordost commented on Aug 22, 2022

    @westnordost
    Author

    Did that decompiler decompile it to kotlin? Or is the above valid java (11) code?

  20. easbar commented on Aug 22, 2022

    @easbar
    Member

    Good point :) It's Kotlin code. So I probably need some maven plugin that invokes the Kotlin compiler. Then again, no, because the jar only contains bytecode I thought?

  21. westnordost commented on Aug 22, 2022

    @westnordost
    Author

    Yeah, you should not need the kotlin compiler. I think you included the klib, not the jar? Not sure how to tell maven to take the jar

  22. easbar commented on Aug 22, 2022

    @easbar
    Member

    I went two steps back and created a fresh Kotlin+Gradle project in IntelliJ, put

    dependencies {
        implementation('de.westnordost:osm-legal-default-speeds:1.1')
    }

    in build.gradle and got:

    Execution failed for task ':compileKotlin'.
    > Error while evaluating property 'filteredArgumentsMap' of task ':compileKotlin'
       > Could not resolve all files for configuration ':compileClasspath'.
          > Could not resolve de.westnordost:osm-legal-default-speeds:1.1.
            Required by:
                project :
             > No matching variant of de.westnordost:osm-legal-default-speeds:1.1 was found. The consumer was configured to find an API of a library compatible with Java 11, packaged as a jar, preferably optimized for standard JVMs, and its dependencies declared externally, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm' but:
                 - Variant 'nativeApiElements-published' capability de.westnordost:osm-legal-default-speeds:1.1 declares a library:
                     - Incompatible because this component declares a usage of 'kotlin-api' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'native' and the consumer needed an API of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm'
                     - Other compatible attributes:
                         - Doesn't say anything about how its dependencies are found (required its dependencies declared externally)
                         - Doesn't say anything about its target Java environment (preferred optimized for standard JVMs)
                         - Doesn't say anything about its target Java version (required compatibility with Java 11)
                         - Doesn't say anything about its elements (required them packaged as a jar)
    

    Does that ring a bell?

  23. westnordost commented on Aug 22, 2022

    @westnordost
    Author

    No, doesn't ring a bell. I also do not quite understand what would be the problem and why "nativeApiElements" is even mentioned. There are no native api elements.

    Anyway, at this point, it looks very much that this is a packaging problem of the library itself and not a maven configuration problem in your project, so I created an issue there. westnordost/osm-legal-default-speeds#2

    In case you find anything, you are welcome to post anything on that ticket

  24. westnordost commented on Sep 28, 2022

    @westnordost
    Author
  25. otbutz commented on Feb 15, 2023

    @otbutz
    Contributor

    What's the current state of the project? Would be nice if we could integrate this :)

  26. westnordost commented on Feb 15, 2023

    @westnordost
    Author

    It's done

  27. karussell commented on Jun 12, 2023

    @karussell
    Member

    Integration done in #2810.

  28. added this to the 8.0 milestone on Jun 12, 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

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions