Repository navigation
Split flag encoders into encoded values and tag parsers - #2561
Conversation
karussell
left a comment
There was a problem hiding this comment.
Thanks a lot for this refactoring! I really like it :) The separation makes a lot of sense and is like I imagined it. And even more classes can now easier dissolve.
The only bigger thinking I had about the TagParserBundle as it wasn't quite clear what it does or maybe you have just a better name for it (?)
Do you think TagParserBundle is useful for non-OSM data or why are e.g. the TagParsers not directly used from OSMReader?
There is only one implementation of FlagEncoder left
Maybe we should link to VehicleTagParser in the javadoc of this class for legacy reasons until it is removed? (and also update our documentation -> but maybe it makes more sense to update it after the entire refactoring is done)
Move Access enum out of EncodingManager
Do we need the prefiltering of VehicleTagParser.getAccess at all? It seems that getAccess is already called in handleWayTags and we could remove the Access enum. (And for access tests we could test against changes in intsRef or something?)
Remove special handling of VehicleTagParsers in TagParserBundle (acceptWay method)
Why is this special handling currently necessary? Because of handleNodeTags?
Vehicle-specific max speeds are currently duplicated between VehicleEncodedValues and VehicleTagParsers
Should we (for now) use static constants to avoid a difference?
(Maybe this problem is solved when we use the max_speed only as indication of how large the EV range should be created and the actual used maximum speed is dependent on the outcome of the OSMReader parsing. As it is only used later for the Weightings (and only required for A*), I think.)
encoder.supportsTurnCosts()
I can see that we could remove this method now. Shall I create a PR for this PR or shall we do this afterwards?
| em.addEncodedValue(new SimpleBooleanEncodedValue("bike_access"), false); | ||
| } else if (encoder instanceof BikeCommonTagParser) { | ||
| em.addEncodedValue(new SimpleBooleanEncodedValue("bike_access", true), false); | ||
| } else if (encoder.getName().contains("bike") || encoder.getName().contains("mtb")) { |
There was a problem hiding this comment.
Maybe we need encoder.isBike()? (or resurrect encoder.getTransportationMode ;) and add a method there )
There was a problem hiding this comment.
Ideally I would like to get rid of these defaults anyway (see other comment) :)
| // this needs to be in sync with the default EVs added in EncodingManager.Builder#build. ideally I would like to remove | ||
| // all these defaults and just use the config as the single source of truth |
There was a problem hiding this comment.
I understand what you mean, but IMO something that is required and can't be configured (at least not through the config file) shouldn't be in the config file (?)
But I would be fine too if we throw an exception if a required encoded value is missing (otherwise, if we completely ignore this problem then graphhopper would throw an exception too late).
(Or we remove the default EVs from the EncodingManager only and add them together with the TagParsers here or something?)
And if we assume the config to be the single source of truth, would you create a tag parser for every encoded value (and throw an exception if a required EV is missing) or should the tag parsers be specified separately in the config?
There was a problem hiding this comment.
I understand what you mean, but IMO something that is required and can't be configured (at least not through the config file) shouldn't be in the config file (?)
Let's see. Currently RoadAccess is required mostly because it is required by FastestWeighting. But I think it is debatable if FastestWeighting should even include such a priority thing and we want to switch to using CustomWeighting anyway, so I think we could get rid of this requirement. Then we have the road class and roundabout EVs, which are used for instructions. Roundabout is also used by some vehicle tag parsers (but not all). Maybe someone uses GraphHopper and does not need instructions, so it does not seem to be strictly required either. Another one is RoadEnvironment which is used for Tunnel/Bridge elevation interpolation. Currently we do not require it there, but ignore the interpolation if it is missing (which seems ugly in case we assume the interpolation is always desired).
So we have some encoded values that are required for certain parts of the library, but not necessarily for all use cases.
The other question is whether or not such encoded values should somehow be added by default. Currently they are not just used as defaults somewhere in the GraphHopper class, but they are added in EncodingManager.Builder.build. So there is no way to create an EncodingManager without these encoded values. I don't like this, because the encoded values might be needed in many cases, but not all.
The other reason why I don't like the default encoded values is that we already provide a way to specify which encoded values shall be included for a GraphHopper instance. To me this seems easier to understand when this list is definitive. I don't want to first specify some encoded values in the config.yml file and then browse the complicated Java code to find out that some more are added through the backdoor.
But I would be fine too if we throw an exception if a required encoded value is missing (otherwise, if we completely ignore this problem then graphhopper would throw an exception too late).
Yes, I fully agree. If some feature needs some encoded value it should error when the encoded value is missing. But if the feature is not used/enabled/etc. the requirement of the encoded value is gone so everything should work without it.
(Or we remove the default EVs from the EncodingManager only and add them together with the TagParsers here or something?)
Yes. Adding them in EncodingManager.Builder.build is the worst part of the default EVs I think. Because this means that we enforce them on a very low level where it is not clear whether they are required or not. The problem when we not add them on this low level is that we need to add them explicitly when they are needed (in many tests for example). But in some cases we will also not need to add them because we weren't using them. This is one example of what I meant with "How to deal with boilerplate code, especially after above changes?" Still, I think it is the right thing to do and adding them can be reduced to one call of some static helper method or something.
And if we assume the config to be the single source of truth, would you create a tag parser for every encoded value (and throw an exception if a required EV is missing) or should the tag parsers be specified separately in the config?
Currently we have graph.encoded_values and graph.flag_encoders. So far graph.encoded_values should have really been called graph.tag_parsers, because it controlled the list of tag parsers, which in turn specified which encoded values will be created (apart from the default ones). I kept it as before to avoid too many changes in this PR, but maybe we need to think about this again. I use the list of encoded values to create both the encoded values and the tag parsers (this is why there is an EncodedValueFactory again, but this time it is actually being used each time we create a GraphHopper instance). So as it stands all we'd have to do would be adding something like road_environment to graph.encoded_values and this would add the RoadEnvironment EV to the encoded values and add the tag parser as well. But I think we should get rid of graph.flag_encoders and the VehicleTagParsers are a little different, because they require multiple encoded values. This seems to require a bit more thought so I would do it after this PR.
There was a problem hiding this comment.
Adding them in EncodingManager.Builder.build is the worst part of the default EVs I think.
I see. Ok, then let's init them via a static helper method in the tests (or where necessary) and for the config we have no defaults and only explicitly init them. (but now we cannot easily remove the exception in getEncodedValue and instead have to introduce a hasEncodedValue check in a few places before we could remove it)
There was a problem hiding this comment.
Ok. But let's do this after this PR?
…en vehicle tag parsers and encoded values
|
Thanks for the review!
Thanks! This is encouraging.
The TagParserBundle doesn't have a very central role here. It just bundles the different parsers as needed for the OSMReader. The alternative would be passing the
Yes the documentation will need a complete overhaul. I think we should do this when the dust settles a bit :)
Yes we need some kind of pre-filtering, because this way we can exclude lots of ways during the first pass so we don't need to store the node coordinates for these. The most basic filtering would be simply one that checks for the highway tag, but when we use motorized vehicles for example it also helps a lot to exclude paths, footways and such (or motorways for non-motorized vehicles). But I agree that the prefiltering does not necessarily need to be so vehicle specific and I think at some point we already agreed we could just use some kind of configurable accept list in config.yml. For this PR I wanted to just keep the previous behavior so I would keep the method for now and change this later.
Because of the acceptWay method.
done
👍
Let's do this afterwards. |
Yes, sounds good :)
👍 |
|
I renamed TagParserBundle to OSMParsers. |
|
Thanks! |
* fix travis release for tagged commits; use jdk 17 instead of 11 for github releases * allow skipping the LM constraint check for A* (graphhopper#2544) * LM constraint should be ignored for A* * make it possible to skip checkLMConstraints call * move checkLMConstraints call to LMSolver. Fix createSolver for mixed preparations * avoid fundamental default change but throw proper exception when lm.disable parameter missing * Add names for travis build jobs (to be shown under 'Jobs and Stages on GitHub)' * Disable doclint explicitly * travis: only keep release build, related to graphhopper#2552 * Clean up javadoc comments (graphhopper#2569) * fix javadoc errors * remove javadoc plugin * make comment more readable * include javadoc again, revert unreadable comments * disable doclint for javadoc * Add flex alternatives to measurement * Do not remove SPT elements from the priority queue, speeds up flexible algorithms (graphhopper#2571) * Split flag encoders into encoded values and tag parsers (graphhopper#2561) * Remove final from VehicleEncodedValues * Log available country rules (graphhopper#2579) Co-authored-by: Thomas Butz <[email protected]> * Give access to vehicle tag parsers * Update bestFwd/BwdEntry for flexible algorithms when deleting SPT entries, fix graphhopper#2581 * Travis: Fix warnings in build config validation It said: Build config validation root: deprecated key sudo (The key `sudo` has no effect anymore.) root: missing os, using the default linux root: key matrix is an alias for jobs, using jobs * Add VehicleEncodedValues#isHGV * Use more recent node/npm versions to fix the build (graphhopper#2583) * Update readme for 5.3 * update deployment guide (graphhopper#2576) * update deployment guide * Update deploy.md * review comments * mention max_visited_nodes * Replace deprecated dropwizard parameter types (graphhopper#2574) Co-authored-by: Thomas Butz <[email protected]> * Use epsilon=0.9 for LM map-matching * Update changelog * Use edge keys consistently, store keys in CH shortcuts (graphhopper#2567) * Add comment about slow non-CH alternatives * Remove outdated/wrong comments * Add a mapmatching test * Remove 'shared' encoded values with $ sign in name (graphhopper#2585) * remove OSMAccessParser * removed $ from encoded values * no if clause necessary * fix changelog * downgrade todonow * Matrix client improvements (graphhopper#2587) * tmp * fix tests * update okhttp to 4.9.3 * fixes regarding code review Co-authored-by: easbar <[email protected]> * European toll fallback rules (graphhopper#2450) Co-authored-by: Thomas Butz <[email protected]> * use for loop in PathDetailsBuilderFactory as discussed in graphhopper#2585 (graphhopper#2589) * Fix: Put back block_private and block_fords for racingbike, this got lost in graphhopper#2561 * Make motor vehicle and hgv properties configurable for roads encoder (graphhopper#2594) * Disable edge+alt measurements, they take too long * Use separate deleted flag for SPTEntry, prevent exception when calculating routes with non-feasible approximator (graphhopper#2600) Also revert epsilon=0.9 'fix' in map matching now that we know what is going on * LMApproximator: Align variable names with equation numbers * Log map-matching took value in ms instead of seconds (graphhopper#2591) Co-authored-by: Andi <[email protected]> * rename StringIndex to EdgeKVStorage in preparation for graphhopper#2597 * windows does not need a separate documentation due to WSL (graphhopper#2599) * windows does not need a separate documentation due to WSL * link to install steps directly * EdgeKVStorage: store more than Strings (graphhopper#2597) * copied code and tests from byteindex branch * a bit more docu and tests * behaviour change: throw exception if string is too long and so cut string before storing way_name * renamed StringIndex -> EdgeKVStorage * more consistent: reject null values for all cases * include lost changes again * ensure same version of storage is used * changes from review * fix variable names for key handling * comments to javadoc * better 'compression' in case of identical map with byte[] array * throw exception earlier * Fix bug in non-CH AlternativeRoute (graphhopper#2603) * fix plateau-end check * Revert "Disable edge+alt measurements, they take too long" This reverts commit fb39266. * increase count to 10 for Measurement * AlternativeRoute: follow up refactoring, graphhopper#2603 * MiniGraphUI fixes to make it work again * move quickstart info into more prominent installation of README (graphhopper#2605) * Measurement: reduce routingCH_alt after it was accidentally raised in graphhopper#2603 * Remove GraphHopperStorage (graphhopper#2606) * Rename: GraphHopper#getGraphHopperStorage -> GraphHopper#getBaseGraph * Remove GraphHopperStorage * reduce benchmark load e.g. exclude too slow LM16 case * AlternativeRoute: closer to CH version; default is now a better compromise of speed vs. alternatives found (alternative rate is 1.8 for DE and 1.9 for bavaria) * Move/Rename: EncodingManager.Access -> WayAccess * AlternativeRoute: fix test * Clean up EncodingManager Builder * minor: Use Bike/FootNetwork.KEY * Rename freshFlags -> refreshFlags * BaseGraph: remove copying flags on write, see graphhopper#2593 * added elevation data to reduce internet-dependence while running test * Add comment about GraphHopper#init * Merged graphhopper#2593, i.e. revert b8d9b55 Co-authored-by: Andi <[email protected]> Co-authored-by: Thomas Butz <[email protected]> * Add another elevation file used in tests * Use access and speed EVs rather than flag encoder for GHUtility#setSpeed * Fix broken imports * More use access and speed EVs instead of encoder for GHUtility#setSpeed * Replace flag encoder with turn cost encoded value in turn cost provider * Remove FlagEncoder from ShortestWeighting and CustomWeighting * Find strongly-connected components of station (stop) graph (graphhopper#2608) * Load EncodingManager from properties instead of config (graphhopper#2607) * Helper.cutString should be only for KVStorage and reduce length to 250 to fix graphhopper#2609 * CHPreparationGraph bug fix: unsigned shift required (and increase limit for getKeyWithFlags graphhopper#2567) * make error message more clear * CHPreparationGraph: revert to previously correct signed shift * Increase maximum edge-based CH key for preparation to 2^30 again (graphhopper#2612) * Add test for large edge ID, graphhopper#2612 * custom_model: introduce value expression (graphhopper#2568) * value expression: findMax needs to be evaluated * less strict if * or + operator * refactored to findMinMax * made core tests pass * fix some more tests * fix more tests * add encoded values to initialization plus tests * check minimum for custom_model of query * improve on check of minimum and negative factors * less overhead for constant values * use Double.parse instead of ExpressionEvaluator if number to significantly improve speed * minor cosmetics * clarify LATER and removed TODO NOW * adapted docs * minor optimization and cleanup * fix FindMinMax.checkLMConstraints call * do not allow / as operation * reduce power and complexity of right hand side a bit more and allow only a single EncodedValue for now * better readable via extra MinMax class instead of double[] * exclude changes from master * a bit more comments * Create weighting after graph in two tests * Update custom model editor: operator values are strings now * Update custom model editor: validation + auto-complete for rhs expressions (graphhopper#2615) * Allow graph.encoded_values for which there is no tag parser * Use actual speed maximum rather than flagEncoder#getMaxSpeed() for weighting.getMinWeight() (graphhopper#2614) * Rename getMin/MaxInt -> getMin/MaxStorableInt, getMaxSetValueOrMax -> getMaxOrMaxStorable (graphhopper#2616) * Remove FlagEncoder#getMaxSpeed() (graphhopper#2619) * Remove car/bike_access evs from DefaultEncodedValueFactory, was added only for graphhopper#2523 * CustomModelParser: no need for max speed * EdgeKVStorage: store name and ref tags separately (graphhopper#2598) * copied code and tests from byteindex branch * a bit more docu and tests * behaviour change: throw exception if string is too long and so cut string before storing way_name * renamed StringIndex -> EdgeKVStorage * store name and ref tags separately; create separate path detail for ref; use ref as fallback in instruction text * added text to changelog * minor comment changes * review: fix comments * review comments and add getValue method to avoid creating HashMaps * try if speed up was really from the change getKeyValues->edge.getValue * Revert "try if speed up was really from the change getKeyValues->edge.getValue" This reverts commit 58a34d6. Co-authored-by: easbar <[email protected]> * update i18n * Remove FlagEncoder (graphhopper#2611) * EdgeKVStorage: remove smallCache as too much complexity. we accept disk usage increases by 12% and more uniq keys later possible * Move outdoor vehicles list * Relax speed EV requirement for EncodingManager#getVehicles * Check vehicle instead of access/speed in checkProfilesConsistency * reduce distance when average_speed path details can be missing, fixes graphhopper#2620 * Valid if PathDetail is null (graphhopper#2618) * Valid if object is null * Adding my name in contributors * Adjusting indentation * Update CONTRIBUTORS.md Co-authored-by: Rafael Telles <[email protected]> Co-authored-by: Peter <[email protected]> * Support for forward & backward key value pairs (graphhopper#2622) * fix test * minor update to docs for map matching * Update README.md * add more info to exception * profiles.md: updated rhs to strings * minor test change to avoid downloading elevation tile * CustomModelParser: minor cleanup * EncodedValue: bug fix for negateReverseDirection * ConditionalExpressionVisitor: allow '-' as unary operation * fixed link to CGIAR attribution * make global time&distance values consistent with path details and instructions (graphhopper#2626) * make global time&distance values consistent with time&distance path details and also the sum of time&distance of the instructions * minor simplification * mention change in changelog * minor comment fix for graphhopper#2626 * Update github actions v2->v3 * Include destination in instructions (graphhopper#2624) * support for destination and add test for non repetitive instructions when destination is included * include destination:ref * add missing osm file * try getKeyValues instead getValue * try speed of getKeyValues (fetching REVERSE_STATE necessary as getKeyValues is align with 'internal' storage direction) * use simpler edge.getValue call again * Make profile resolving more flexible for web API (graphhopper#2629) * ProfileResolver only resolves name of the profile (graphhopper#2629) * car: do not pass jersey_barrier https://www.openstreetmap.org/node/8857224952 * move cut string method to EdgeKVStorage * EdgeKVStorage: no need for cacheSize parameter anymore * Examples: remove incorrect comment * fix PathDetails e.g. -1 as default for DecimalDetails doesn't work as a value of the EV could be negative too * renamed DouglasPeucker to RamerDouglasPeucker * client-hc: add examples to get translated ("raw") turn instructions * HeightTile: minor correction, DecimalEncodedValueImpl: minor clarification * EdgeKVStorage: allow 32 bits (graphhopper#2632) * allow 32 bits instead of just 31 for EdgeKVStorage * remove incorrect exception * minor change to wayGeo limit check * Maps: Hide gpx export button when custom model box is open, fix graphhopper#2635 * Add hint about custom_model_file vs. custom_model to exception error message (graphhopper#2638) * Add comma in routing logs * Move code that creates EncodingManager from properties to EncodingManager * Return boolean result from BaseGraph#loadExisting * Move code that puts EncodingManager into properties to EncodingManager * add hgt provider * AbstractTiffElevationProvider: use correct long cast * pt: hint on how to use multiple files * Add BaseGraph#debugPrint * new edge smoothing: "ramer" (graphhopper#2634) * initial version of new edge smoothing * improve comments * let's switch the order: first do sampling, then smoothing * use moving_average as name and a few more comments * use same max_elevation like in example config * fix moving_average * again moving_average rename * New average_slope EV (graphhopper#2645) * initial version of new edge smoothing * improve comments * let's switch the order: first do sampling, then smoothing * encoded values for elevation-aware routing: average_slope and max_slope * for tunnels and bridges ignore elevation changes for pillar nodes * SlopeSetter -> SlopeCalculator * fix link for GTFS demo file for graphhopper#2639 * removed defaultIsInfinity and fix bug in DecimalEncodedValueImpl (graphhopper#2646) * removed defaultIsInfinity and fix bug in DecimalEncodedValueImpl * changelog: fix issue number * for useMaximumAsInfinity: also throw an exception if value is too big, but not for infinity * fix merge of master * Revert "for useMaximumAsInfinity: also throw an exception if value is too big, but not for infinity" This reverts commit e3d8826. * print warning if max_width, max_weight etc values are too large * fix link for GTFS demo file for graphhopper#2639 * Revert "fix link for GTFS demo file for graphhopper#2639" This reverts commit d9bb4b9. * NOTICE: updated dependencies and copyright * make ramer edge smoothing more robust, graphhopper#2634 * TurnCostParser: no need for method createTurnCostEncodedValues * improvements for bike (graphhopper#2631) * lower speed for bad smoothness and steps; avoid hazmat; faster if paving_stones * clean up of smoothness handling * revert to 4kmh pushing section speed and tweak speed for certain surfaces * mtb+racing: do not overwrite highway and surface speed if identical in subclass * consider multiple from members for no_entry (graphhopper#2648) * allow configuring turn costs and TransportationMode for RoadsTagParser, related to graphhopper#2460 * add hgv enum to make truck access configurable * add test for hgv encoded value * for now do not log as too many warnings, graphhopper#2646 * SlopeCalculator: skip calculation if PointList is empty or 2D only * Do not get elevations for nodes we don't need while parsing OSM * Custom weighting calcEdgeMillis truncate instead of round * just for consistency and easier migration with/from FastestWeighting * CustomWeighting: handle special case for barrier edges with distance==0 and average_speed>0 * Maps: Add slope detail to elevation diagram (graphhopper#2654) * Custom and fastest weighting calcEdgeMillis round instead of truncate * otherwise they are not always the same, because one multiplies by 3600 and the other by 3.6*1000 ... * Fix pt tests * Disable flaky test * custom and fastest calcEdgeMillis again: make them actually the same * Validate that osm ids are not negative (graphhopper#2652) * Add comment about negative osm ids, code formatting * OSMParsers: don't accept null TagParser * replace car4wd with roads and a custom_model (graphhopper#2651) * Revert "OSMParsers: don't accept null TagParser" This reverts commit 8f5c7b2. * Add urban density encoded value to identify built-up areas (graphhopper#2637) * Rename Development -> UrbanDensity (graphhopper#2637) * Support ";" access delimiter for car access. (graphhopper#2655) * Support ";" access delimiter for car access. One example is motor_vehicle = agricultural;forestry * Add support for ";" access delimiter for MotorcycleTagParser and road_access EV. * Move logic for access delimiter handling for ";" from RoadAccess into OSMRoadAccessParser * Fix for OSMRoadAccessParserTest * map match without graphhopper class (graphhopper#2657) * Solve Viterbi problem with Dijkstra to calculate fewer routes * Solve Viterbi problem with Dijkstra to calculate fewer routes * use 6.x/6.0 in readme * announcement * fix critical bug in client-hc for Matrix API * SBI Algo Co-authored-by: Peter <[email protected]> Co-authored-by: easbar <[email protected]> Co-authored-by: otbutz <[email protected]> Co-authored-by: Thomas Butz <[email protected]> Co-authored-by: Michael Zilske <[email protected]> Co-authored-by: Robin <[email protected]> Co-authored-by: Andi <[email protected]> Co-authored-by: Rafael Sanches Telles <[email protected]> Co-authored-by: Rafael Telles <[email protected]> Co-authored-by: Alexey Abel <[email protected]> Co-authored-by: Lukas Weber <[email protected]> Co-authored-by: ratrun <[email protected]>
FlagEncoders used to be both a collection of some vehicle-specific encoded values and code that parsed OSM tags. This PR separates these two concerns.
There is only one implementation of
FlagEncoderleft, which is now calledVehicleEncodedValues. It is unrelated to OSM tag parsing and basically it is just a conglomerate of access, speed, turn_cost etc. encoded values, a name and a maximum speed. It does not really serve a central purpose, but is still there for legacy reasons. There are different static methods to createVehicleEncodedValuesthe way we used to do for the different vehicles. For exampleVehicleEncodedValues#createBikehas a priority EV, butVehicleEncodedValues#createCardoes not. This way many tests could remain unchanged, but otherwise there is no real purpose for these methods either.EncodingManager is just a collection of encoded values and no longer related to parsing OSM tags. It still maintains a list of FlagEncoders to support the frequently used
EncodingManager#getEncoder, which in turn is needed mostly because theAbstractWeightingconstructor takes aFlagEncoder. But this will be removed in Remove FlagEncoder #2611.The old FlagEncoders now implement the TagParser interface, e.g. CarFlagEncoder is now CarTagParser. They all receive the encoded values they read/write via their constructors. The createEncodedValues method is gone.
There is a new class
TagParserBundleOSMParsers that represents a collection of multiple tag parsers and is used by OSMReader. What used to beEncodingManager#handleWayTagsis nowTagParserBundle#handleWayTagsOSMParsers#handleWayTagsfor example.AbstractFlagEncoder is now VehicleTagParser and
TagParserBundleOSMParsers still distinguishes VehicleTagParsers from normal TagParsers. The main reason for this is that this way we can easily implementTagParserBundleOSMParsers#acceptWay. Otherwise I think this should be considered legacy. Also there should no longer be a separate VehicleTagParserFactory.Some things left to do (maybe not here):
TagParserBundleOSMParsers (acceptWay method)