Skip to content

OSMReader: Keep node tags until we create edges - #2430

Merged
easbar merged 18 commits into
masterfrom
keep_node_tags
Oct 25, 2021
Merged

easbar merged 18 commits into
masterfrom
keep_node_tags

Conversation

@easbar

@easbar easbar commented Oct 12, 2021 •

Copy link
Copy Markdown
Member

Instead of compressing the node and relation tags into node/relation'flags' early with this PR we keep the full node and relation tag data until we parse the ways in the second pass (but only for 'barrier' nodes and 'route' relations). This requires more memory, but it is actually not that bad, because there aren't so many barrier nodes and route relations. I did a little test and both master and this branch failed to run the import with Xmx=1100m, but succeeded for Xmx=1200m.

I keep the node tags in a List<Map<String, Object>> and use a separate LongIntMap to associate OSM node IDs with the indices into this list. The relations are grouped by the member way IDs LongMap<List<ReaderRelation>>. There is still room for improvement memory-wise, for example we could remove some of the tags like 'created' etc.

The goal here is to make the relation and node tag handling more flexible. With this PR we should be able to delay the creation of edge flags until we actually create the edges and get rid of EncodingManager#handleNodeTags and some others. Ultimately, this should help us in getting rid of FlagEncoder altogether.

Putting this as a Draft here, because maybe we should continue in this direction until we actually can remove e.g. handleNodeTags before merging.

Update:

We reverted the changes to relation flags for now as this increased memory usage during import in some cases.

@boldtrn

boldtrn commented Oct 12, 2021

Copy link
Copy Markdown
Member

Very interesting approach and this could improve barrier handling a lot if we had all the information of the node when we create the edge 👍

@easbar

easbar commented Oct 12, 2021

Copy link
Copy Markdown
Member Author

this could improve barrier handling a lot if we had all the information of the node when we create the edge

Yes this is the idea. 👍

There is also this OSMReader rewrite where we already get the full node+way+relation information for each edge:

/**
* This method is called for each segment an OSM way is split into during the second pass of {@link NewWaySegmentParser}.
*
* @param way the same OSM way object that was passed to {@link #setArtificialWayTags} earlier
* @param segment the OSM nodes belonging to this segment (tags included)
*/
private void handleEdge(ReaderWay way, List<ReaderNode> segment, boolean artificial) {
// no more loops or missing nodes, already split at barrier nodes and connects two tower nodes
// -> first and last nodes are tower nodes and the others are geometry
int fromGHId = getOrSetTowerNode(segment.get(0));
int toGHId = getOrSetTowerNode(segment.get(segment.size() - 1));
Object relationsObj = way.getTags().get("gh:relations");
List<ReaderRelation> relations = relationsObj != null ? (List<ReaderRelation>) relationsObj : emptyList();
IntsRef relFlags = encodingManager.createRelationFlags();
for (ReaderRelation relation : relations)
relFlags = encodingManager.handleRelationTags(relation, relFlags);
EncodingManager.AcceptWay acceptWay = new EncodingManager.AcceptWay();
encodingManager.acceptWay(way, acceptWay);
IntsRef edgeFlags = encodingManager.handleWayTags(way, acceptWay, relFlags);
if (edgeFlags.isEmpty())
return;
if (artificial) {
long nodeFlags = encodingManager.handleNodeTags(segment.get(0));
edgeFlags = IntsRef.deepCopyOf(edgeFlags);
// clear blocked directions from flags
for (BooleanEncodedValue accessEnc : encodingManager.getAccessEncFromNodeFlags(nodeFlags)) {
accessEnc.setBool(false, edgeFlags, false);
accessEnc.setBool(true, edgeFlags, false);
}
}
PointList pointList = new PointList(segment.size(), graph.getNodeAccess().is3D());
for (ReaderNode node : segment)
pointList.add(node.getLat(), node.getLon(), elevationProvider.getEle(node));
// Smooth the elevation before calculating the distance because the distance will be incorrect if calculated afterwards
if (config.isSmoothElevation())
GraphElevationSmoothing.smoothElevation(pointList);
// sample points along long edges
if (config.getLongEdgeSamplingDistance() < Double.MAX_VALUE && pointList.is3D())
pointList = EdgeSampling.sample(pointList, config.getLongEdgeSamplingDistance(), distCalc, elevationProvider);
if (config.getMaxWayPointDistance() > 0 && pointList.size() > 2)
simplifyAlgo.simplify(pointList);
double towerNodeDistance = distCalc.calcDistance(pointList);
if (towerNodeDistance < 0.001) {
// As investigation shows often two paths should have crossed via one identical point
// but end up in two very close points.
zeroCounter++;
towerNodeDistance = 0.001;
}
double maxDistance = (Integer.MAX_VALUE - 1) / 1000d;
if (Double.isNaN(towerNodeDistance)) {
LOGGER.warn("Bug in OSM or GraphHopper. Illegal tower node distance " + towerNodeDistance + " reset to 1m, osm way " + way.getId());
towerNodeDistance = 1;
}
if (Double.isInfinite(towerNodeDistance) || towerNodeDistance > maxDistance) {
// Too large is very rare and often the wrong tagging. See #435
// so we can avoid the complexity of splitting the way for now (new towernodes would be required, splitting up geometry etc)
LOGGER.warn("Bug in OSM or GraphHopper. Too big tower node distance " + towerNodeDistance + " reset to large value, osm way " + way.getId());
towerNodeDistance = maxDistance;
}
EdgeIteratorState edgeState = graph.edge(fromGHId, toGHId).setDistance(towerNodeDistance).setFlags(edgeFlags);
// If the entire way is just the first and last point, do not waste space storing an empty way geometry
if (pointList.size() > 2) {
// the geometry consists only of pillar nodes, but we check that the first and last points of the pointList
// are equal to the tower node coordinates
checkCoordinates(fromGHId, pointList.get(0));
checkCoordinates(toGHId, pointList.get(pointList.size() - 1));
// tower node coordinates are not included in way geometry
edgeState.setWayGeometry(pointList.shallowCopy(1, pointList.size() - 1, false));
}
encodingManager.applyWayTags(way, edgeState);
checkDistance(edgeState);
if (restrictionWayIds.contains(way.getId()))
edgeIdToOsmWayIdMap.put(edgeState.getEdge(), way.getId());
}

Not sure about this though, because it currently still performs a bit worse and requires more memory (even though memory can be reduced using MMAP). For now I think we should continue with this PR and focus on removing some of the FlagEncoder stuff.

easbar added 11 commits October 14, 2021 11:26
* we just add barrier edges at all barrier nodes no matter whether the road is accessible or not
# Conflicts:
#	core/src/main/java/com/graphhopper/reader/osm/OSMReader.java
# Conflicts:
#	core/src/main/java/com/graphhopper/reader/osm/OSMReader.java
#	core/src/main/java/com/graphhopper/routing/util/EncodingManager.java
#	core/src/test/java/com/graphhopper/reader/osm/OSMReaderTest.java
@easbar
easbar marked this pull request as ready for review October 18, 2021 04:45
@easbar

easbar commented Oct 18, 2021 •

Copy link
Copy Markdown
Member Author

I am now confident that this is the way we should proceed. So far we just keep the barrier node tags and add extra edges for all nodes with this tag. Later we can of course extend this approach so we can keep other node tags as well. E.g.we could pass node tags other than barrier to the tag parsers without creating extra edges as for barrier.

I'm still working on a rewrite of the OSMReader here: https://github.com/graphhopper/graphhopper/tree/reader2, but this PR is maybe the biggest functional (and performance-critical) change, so I kept it separate here.

This PR is a bit slower (<10%) than current master, but I think this is very reasonable considering that it also opens a lot of opportunities. The memory usage is increased as well and currently the biggest contribution is due to the relations. This is because there are a lot more route relations than barrier nodes. If we kept other node tags than barrier this might change.

Here is the memory footprint for the node and relation data for Germany (foot,bike+car):

java.util.ArrayList@13da7ab0d footprint:
     COUNT       AVG       SUM   DESCRIPTION
    441929        26  11608640   [B
         1   2160888   2160888   [Ljava.lang.Object;
    406758        34  13886704   [Ljava.util.HashMap$Node;
    441929        24  10606296   java.lang.String
         1        24        24   java.util.ArrayList
    406758        48  19524384   java.util.HashMap
    862227        32  27591264   java.util.HashMap$Node
   2559603            85378200   (total)


com.graphhopper.coll.GHLongIntBTree@52423092d footprint:
     COUNT       AVG       SUM   DESCRIPTION
      4067       416   1692336   [I
      4067       816   3319600   [J
        40       428     17144   [Lcom.graphhopper.coll.GHLongIntBTree$BTreeEntry;
         1        48        48   com.graphhopper.coll.GHLongIntBTree
      4067        40    162680   com.graphhopper.coll.GHLongIntBTree$BTreeEntry
     12242             5191808   (total)


com.carrotsearch.hppc.LongObjectScatterMap@5672a040d footprint:
     COUNT       AVG       SUM   DESCRIPTION
    339743        45  15377312   [B
         1  33554456  33554456   [J
   2801274        64 181154992   [Ljava.lang.Object;
    117057        75   8872112   [Ljava.util.HashMap$Node;
         1        16        16   com.carrotsearch.hppc.HashOrderMixing$3
         1        56        56   com.carrotsearch.hppc.LongObjectScatterMap
    117057        32   3745824   com.graphhopper.reader.ReaderRelation
    339743        24   8153832   java.lang.String
   2801273        24  67230552   java.util.ArrayList
    117057        48   5618736   java.util.HashMap
    985279        32  31528928   java.util.HashMap$Node
   7618486           355236816   (total)

The biggest contribution is due to the LongObjectScatterMap<List<ReaderRelation>> that maps each OSM way ID for which there are route relations to a list of relations that include this way as a member (~355MB). For the (barrier-only) node tags only around 85MB plus around 5MB for the mapping are needed. Thus the total is around 455MB. Assuming that the planet graph is around a factor x20 bigger than Germany and the number of relations is similar this would mean around 9GB of additional memory is required during the import. There is room for improvement of course because the relations map isn't memory-friendly at all. Still, not sure if this should be a priority at the moment considering that the CH preparation requires more memory anyway, especially when we run it for multiple profiles in parallel.

@easbar easbar added this to the 5.0 milestone Oct 18, 2021
@easbar

easbar commented Oct 23, 2021

Copy link
Copy Markdown
Member Author

Regarding the increased memory usage I think we have at least five options:

  1. Just merge this branch and live with the memory overhead. If landmarks or edge-based CH is enabled the main memory is used for the LM/CH prepration anyway, especially if prepare.lm/ch.threads > 1. Without any preparations or with node-based CH the memory overhead of this branch does mean we need a larger heap size though.

  2. Keep the relations flag approach we use in master for now. This way the relations are converted to flags already in pass1 so less memory is needed to keep them in memory. We won't be able to forward the relations directly to the tag parsers, but maybe this is not so important right now, because the FlagEncoders are not related to the relation flags.

  3. Use a data structure that keeps the full relation tag information, but is still more memory-efficient than LongObjectMap<List<ReaderRelation>>. Should be doable.

  4. Do not store the relation information at all and rather read the relations at the end of pass2. To apply the relations to edge flags we need a mapping between OSM way IDs and GH edge Ids, but overall this could mean less memory is needed compared to approach 1) (haven't tried this yet)

  5. keep the relation data as in 1), but save memory elsewhere. Particularly, I think we can get rid of elevation in PillarInfo, because it is sufficient to fetch the elevation data while reading the ways in pass2.

I would prefer 1) or 2) now so we can go on. Later we could try 3) or 4), and maybe try 5) as well.

@easbar

easbar commented Oct 24, 2021

Copy link
Copy Markdown
Member Author

I reverted the changes related to the relation flags here: df998e6 (approach number 2 above).

I then ran a base graph only import for germany-210101.osm.pbf from Geofabrik with a single profile (car) and graph.encoded_values: road_access,max_speed,road_environment,road_class_link,road_class,roundabout,surface,max_weight,hazmat,hazmat_tunnel,max_width,hazmat_water,max_height and also included elevation. I did this for master and for the keep_only_node_flags branch (this PR but with changes to relation flags reverted):

keep_only_node_flags master
3500m - -
3550m - 407s
3600m 364s 362s

So maybe we should just merge the changes related to the node flags for now and deal with relations later?

@easbar

easbar commented Oct 25, 2021

Copy link
Copy Markdown
Member Author

I just added the commit that reverts the relation flag changes to this PR (option 2). It seems like this is the easiest way for now and we can deal with relations later.

@easbar easbar changed the title OSMReader: Keep node tags and relations until we create edges OSMReader: Keep node tags until we create edges Oct 25, 2021
@karussell

Copy link
Copy Markdown
Member

Thanks for this nice work. It will make the handling downstream in the TagParsers easier.

}

public void setMembers(List<Member> members) {
this.members = members;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we do not need this yet (due to the revert)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok yes.

Comment on lines -701 to -709
public List<BooleanEncodedValue> getAccessEncFromNodeFlags(long importNodeFlags) {
List<BooleanEncodedValue> list = new ArrayList<>(edgeEncoders.size());
for (int i = 0; i < edgeEncoders.size(); i++) {
FlagEncoder encoder = edgeEncoders.get(i);
if (((1L << i) & importNodeFlags) != 0)
list.add(encoder.getAccessEnc());
}
return list;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is really nice!!

flags |= (encoder.isBarrier(node) ? 1L << i : 0);
public IntsRef handleNodeTags(Map<String, Object> nodeTags, IntsRef edgeFlags) {
for (AbstractFlagEncoder encoder : edgeEncoders) {
// todo: not sure yet: should we pass the reader node (because it includes the coordinates), or just the tag?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For now I would keep this? As the method might change soonish as we reconsider how handleWayTags+handleNodeTags+applyWayTags work and which method signature they should have?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, exactly.

return properties;
}

public void _setTags(Map<String, Object> properties) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could create a new constructor and allow directly assigning the properties Map.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

Comment on lines -93 to +98
DIJKSTRA + ",false,505",
ASTAR + ",false,438",
DIJKSTRA_BI + ",false,224",
ASTAR_BI + ",false,180",
ASTAR_BI + ",true,41",
DIJKSTRA_BI + ",true,41"
DIJKSTRA + ",false,511",
ASTAR + ",false,444",
DIJKSTRA_BI + ",false,228",
ASTAR_BI + ",false,184",
ASTAR_BI + ",true,36",
DIJKSTRA_BI + ",true,30"

@easbar easbar Oct 25, 2021 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These changes are due to the fact that we now add barrier edges for all barrier nodes, even those that do not block access. This way we have better control over which barriers should block access in the tag parsers.

@easbar
easbar merged commit 84a80fa into master Oct 25, 2021
@easbar
easbar deleted the keep_node_tags branch October 25, 2021 17:49
aoles added a commit to GIScience/graphhopper that referenced this pull request Apr 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants