Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
### 5.0 [not yet released]

- OSMReader no longer sets the artificial estimated_distance tag, but sets the edge_distance and point_list tags for all
edges, the way_distance for selected ways and additionally the duration:seconds and speed_from_duration tags when the
duration tag is present (#2528)
- fixed speed calculation for ferry routes with duration tags (#2528)
- request gzipping for matrix and route clients (#2511)
- bugfix: client-hc now considers headings and custom models (#2009, #2535)
- the artificial tag duration:seconds is now a long, no longer a string, commit 6d81d8ae8de52987522991edd835e42c8d2046cf
Expand Down
130 changes: 105 additions & 25 deletions core/src/main/java/com/graphhopper/reader/osm/OSMReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package com.graphhopper.reader.osm;

import com.carrotsearch.hppc.IntLongMap;
import com.carrotsearch.hppc.LongArrayList;
import com.graphhopper.coll.GHIntLongHashMap;
import com.graphhopper.coll.GHLongHashSet;
import com.graphhopper.coll.GHLongLongHashMap;
Expand All @@ -39,6 +40,7 @@
import com.graphhopper.storage.TurnCostStorage;
import com.graphhopper.util.*;
import com.graphhopper.util.shapes.GHPoint;
import com.graphhopper.util.shapes.GHPoint3D;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -145,6 +147,7 @@ public void readGraph() throws IOException {
.setElevationProvider(eleProvider)
.setWayFilter(this::acceptWay)
.setSplitNodeFilter(this::isBarrierNode)
.setWayPreprocessor(this::preprocessWay)
.setRelationPreprocessor(this::preprocessRelations)
.setRelationProcessor(this::processRelation)
.setEdgeHandler(this::addEdge)
Expand Down Expand Up @@ -191,36 +194,33 @@ protected boolean isBarrierNode(ReaderNode node) {
return node.getTags().containsKey("barrier");
}

/**
* @return true if the length of the way shall be calculated and added as an artificial way tag
*/
protected boolean isCalculateWayDistance(ReaderWay way) {
return isFerry(way);
}

private boolean isFerry(ReaderWay way) {
return way.hasTag("route", "ferry", "shuttle_train");
}

/**
* This method is called during the second pass of {@link WaySegmentParser} and provides an entry point to enrich
* the given OSM way with additional tags before it is passed on to the tag parsers.
*/
protected void setArtificialWayTags(PointList pointList, ReaderWay way, Map<String, Object> nodeTags) {
protected void setArtificialWayTags(PointList pointList, ReaderWay way, double distance, Map<String, Object> nodeTags) {
way.setTag("node_tags", nodeTags);
// Estimate length of ways containing a route tag e.g. for ferry speed calculation
double firstLat = pointList.getLat(0), firstLon = pointList.getLon(0);
double lastLat = pointList.getLat(pointList.size() - 1), lastLon = pointList.getLon(pointList.size() - 1);
way.setTag("edge_distance", distance);
way.setTag("point_list", pointList);

// we have to remove existing artificial tags, because we modify the way even though there can be multiple edges
// per way. sooner or later we should separate the artificial ('edge') tags from the way, see discussion here:
// https://github.com/graphhopper/graphhopper/pull/2457#discussion_r751155404
way.removeTag("estimated_distance");
double estimatedDist = distCalc.calcDist(firstLat, firstLon, lastLat, lastLon);
way.setTag("estimated_distance", estimatedDist);

way.removeTag("duration:seconds");
if (way.getTag("duration") != null) {
try {
long durationInSeconds = OSMReaderUtility.parseDuration(way.getTag("duration"));
way.setTag("duration:seconds", durationInSeconds);
} catch (Exception ex) {
LOGGER.warn("Parsing error in way with OSMID=" + way.getId() + " : " + ex.getMessage());
}
}

way.removeTag("country");
way.removeTag("country_rule");
way.removeTag("custom_areas");

List<CustomArea> customAreas;
if (areaIndex != null) {
double middleLat;
Expand All @@ -229,6 +229,8 @@ protected void setArtificialWayTags(PointList pointList, ReaderWay way, Map<Stri
middleLat = pointList.getLat(pointList.size() / 2);
middleLon = pointList.getLon(pointList.size() / 2);
} else {
double firstLat = pointList.getLat(0), firstLon = pointList.getLon(0);
double lastLat = pointList.getLat(pointList.size() - 1), lastLon = pointList.getLon(pointList.size() - 1);
middleLat = (firstLat + lastLat) / 2;
middleLon = (firstLon + lastLon) / 2;
}
Expand Down Expand Up @@ -313,27 +315,27 @@ protected void addEdge(int fromIndex, int toIndex, PointList pointList, ReaderWa
distance = maxDistance;
}

setArtificialWayTags(pointList, way, nodeTags);
setArtificialWayTags(pointList, way, distance, nodeTags);
IntsRef relationFlags = getRelFlagsMap(way.getId());
IntsRef edgeFlags = encodingManager.handleWayTags(way, relationFlags);
if (edgeFlags.isEmpty())
return;

EdgeIteratorState iter = ghStorage.edge(fromIndex, toIndex).setDistance(distance).setFlags(edgeFlags);
EdgeIteratorState edge = ghStorage.edge(fromIndex, toIndex).setDistance(distance).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(fromIndex, pointList.get(0));
checkCoordinates(toIndex, pointList.get(pointList.size() - 1));
iter.setWayGeometry(pointList.shallowCopy(1, pointList.size() - 1, false));
edge.setWayGeometry(pointList.shallowCopy(1, pointList.size() - 1, false));
}
encodingManager.applyWayTags(way, iter);
encodingManager.applyWayTags(way, edge);

checkDistance(iter);
checkDistance(edge);
if (osmWayIdSet.contains(way.getId())) {
getEdgeIdToOsmWayIdMap().put(iter.getEdge(), way.getId());
getEdgeIdToOsmWayIdMap().put(edge.getEdge(), way.getId());
}
}

Expand All @@ -354,6 +356,84 @@ else if (Math.abs(edgeDistance - geometryDistance) > tolerance)
+ ", difference: " + (edgeDistance - geometryDistance));
}

/**
* This method is called for each way during the second pass and before the way is split into edges.
* We currently use it to calculate the distance of a way and determine the speed based on the duration tag when
* it is present. This cannot be done on a per-edge basis, because the duration tag refers to the duration of the
* entire way.
*/
protected void preprocessWay(ReaderWay way, WaySegmentParser.CoordinateSupplier coordinateSupplier) {
if (!isCalculateWayDistance(way))
return;

double distance = calcDistance(way, coordinateSupplier);
if (Double.isNaN(distance)) {
// Some nodes were missing, and we cannot determine the distance. This can happen when ways are only
// included partially in an OSM extract. In this case we cannot calculate the speed either, so we return.
LOGGER.warn("Could not determine distance for OSM way: " + way.getId());
return;
}
way.setTag("way_distance", distance);

// For ways with a duration tag we determine the average speed. This is needed for e.g. ferry routes, because
// the duration tag is only valid for the entire way, and it would be wrong to use it after splitting the way
// into edges.
String durationTag = way.getTag("duration");
if (durationTag == null) {
// no duration tag -> we cannot derive speed. happens very frequently for short ferries, but also for some long ones, see: #2532
if (isFerry(way) && distance > 500_000)
LOGGER.warn("Long ferry OSM way without duration tag: " + way.getId() + ", distance: " + Math.round(distance / 1000.0) + " km");
return;
}
long durationInSeconds;
try {
durationInSeconds = OSMReaderUtility.parseDuration(durationTag);
} catch (Exception e) {
LOGGER.warn("Could not parse duration tag '" + durationTag + "' in OSM way: " + way.getId());
return;
}

double speedInKmPerHour = distance / 1000 / (durationInSeconds / 60.0 / 60.0);
if (speedInKmPerHour < 0.1d) {
// Often there are mapping errors like duration=30:00 (30h) instead of duration=00:30 (30min). In this case we
// ignore the duration tag. If no such cases show up anymore, because they were fixed, maybe raise the limit to find some more.
LOGGER.warn("Unrealistic low speed calculated from duration. Maybe the duration is too long, or it is applied to a way that only represents a part of the connection? OSM way: "
+ way.getId() + ". duration=" + durationTag + " (= " + Math.round(durationInSeconds / 60.0) +
" + minutes), distance=" + Math.round(distance / 1000.0) + "km");
return;
}
// These tags will be present if 1) isCalculateWayDistance was true for this way, 2) no OSM nodes were missing
// such that the distance could actually be calculated, 3) there was a duration tag we could parse, and 4) the
// derived speed was not unrealistically slow.
way.setTag("speed_from_duration", speedInKmPerHour);
way.setTag("duration:seconds", durationInSeconds);
}

/**
* @return the distance of the given way or NaN if some nodes were missing
*/
private double calcDistance(ReaderWay way, WaySegmentParser.CoordinateSupplier coordinateSupplier) {
LongArrayList nodes = way.getNodes();
// every way has at least two nodes according to our acceptWay function
GHPoint3D prevPoint = coordinateSupplier.getCoordinate(nodes.get(0));
if (prevPoint == null)
return Double.NaN;
boolean is3D = !Double.isNaN(prevPoint.ele);
double distance = 0;
for (int i = 1; i < nodes.size(); i++) {
GHPoint3D point = coordinateSupplier.getCoordinate(nodes.get(i));
if (point == null)
return Double.NaN;
if (Double.isNaN(point.ele) == is3D)
throw new IllegalStateException("There should be elevation data for either all points or no points at all. OSM way: " + way.getId());
distance += is3D
? distCalc.calcDist3D(prevPoint.lat, prevPoint.lon, prevPoint.ele, point.lat, point.lon, point.ele)
: distCalc.calcDist(prevPoint.lat, prevPoint.lon, point.lat, point.lon);
prevPoint = point;
}
return distance;
}

/**
* This method is called for each relation during the first pass of {@link WaySegmentParser}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.graphhopper.util.PointAccess;
import com.graphhopper.util.PointList;
import com.graphhopper.util.StopWatch;
import com.graphhopper.util.shapes.GHPoint3D;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -251,7 +252,7 @@ public void handleWay(ReaderWay way) {
List<SegmentNode> segment = new ArrayList<>(way.getNodes().size());
for (LongCursor node : way.getNodes())
segment.add(new SegmentNode(node.value, nodeData.getId(node.value)));
wayPreprocessor.preprocessWay(way);
wayPreprocessor.preprocessWay(way, osmNodeId -> nodeData.getCoordinates(nodeData.getId(osmNodeId)));
splitWayAtJunctionsAndEmptySections(segment, way);
}

Expand Down Expand Up @@ -411,7 +412,7 @@ public static class Builder {
private ElevationProvider elevationProvider = ElevationProvider.NOOP;
private Predicate<ReaderWay> wayFilter = way -> true;
private Predicate<ReaderNode> splitNodeFilter = node -> false;
private WayPreprocessor wayPreprocessor = way -> {
private WayPreprocessor wayPreprocessor = (way, supplier) -> {
};
private Consumer<ReaderRelation> relationPreprocessor = relation -> {
};
Expand Down Expand Up @@ -462,7 +463,7 @@ public Builder setSplitNodeFilter(Predicate<ReaderNode> splitNodeFilter) {
}

/**
* @param wayPreprocessor callback function that is called for each accepted OSM way during the first pass
* @param wayPreprocessor callback function that is called for each accepted OSM way during the second pass
*/
public Builder setWayPreprocessor(WayPreprocessor wayPreprocessor) {
this.wayPreprocessor = wayPreprocessor;
Expand Down Expand Up @@ -554,6 +555,15 @@ public interface RelationProcessor {
}

public interface WayPreprocessor {
void preprocessWay(ReaderWay way);
/**
* @param coordinateSupplier maps an OSM node ID (as it can be obtained by way.getNodes()) to the coordinates
* of this node. If elevation is disabled it will be NaN. Returns null if no such OSM
* node exists.
*/
void preprocessWay(ReaderWay way, CoordinateSupplier coordinateSupplier);
}

public interface CoordinateSupplier {
GHPoint3D getCoordinate(long osmNodeId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ protected AbstractFlagEncoder(int speedBits, double speedFactor, int maxTurnCost
}

protected void init(DateRangeParser dateRangeParser) {
ferrySpeedCalc = new FerrySpeedCalculator(speedFactor, maxPossibleSpeed, 30, 20, 5);
ferrySpeedCalc = new FerrySpeedCalculator(speedFactor / 2, maxPossibleSpeed, 5);

setConditionalTagInspector(new ConditionalOSMTagInspector(Collections.singletonList(dateRangeParser),
restrictions, restrictedValues, intendedValues, false));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,72 +1,43 @@
package com.graphhopper.routing.util;

import com.graphhopper.reader.ReaderWay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FerrySpeedCalculator {
private final double unknownSpeed, minSpeed, maxSpeed;

private static final Logger LOGGER = LoggerFactory.getLogger(FerrySpeedCalculator.class);
private final double speedFactor;
private final double unknownSpeed, longSpeed, shortSpeed, maxSpeed;

public FerrySpeedCalculator(double speedFactor, double maxSpeed, double longSpeed, double shortSpeed, double unknownSpeed) {
this.speedFactor = speedFactor;
this.unknownSpeed = unknownSpeed;
this.longSpeed = longSpeed;
this.shortSpeed = shortSpeed;
public FerrySpeedCalculator(double minSpeed, double maxSpeed, double unknownSpeed) {
this.minSpeed = minSpeed;
this.maxSpeed = maxSpeed;
this.unknownSpeed = unknownSpeed;
}

/**
* Special handling for ferry ways.
*/
public double getSpeed(ReaderWay way) {
// During the reader process we have converted the duration value into an artificial tag called "duration:seconds".
Long duration = way.getTag("duration:seconds", 0L);
// seconds to hours
double durationInHours = duration / 60d / 60d;
// Check if our graphhopper specific artificially created estimated_distance way tag is present
Number estimatedLength = way.getTag("estimated_distance", null);
if (durationInHours > 0) {
if (estimatedLength != null) {

@easbar easbar Mar 2, 2022 •

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.

estimatedLength == null can never happen.

@easbar easbar Mar 8, 2022 •

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.

I understand this now: Before #2448, #2457, cb38af6, estimatedLength == null could happen when the first/last OSM node of a ferry way was missing:

GHPoint estimatedCenter = null;
if (!Double.isNaN(firstLat) && !Double.isNaN(firstLon) && !Double.isNaN(lastLat) && !Double.isNaN(lastLon)) {
double estimatedDist = distCalc.calcDist(firstLat, firstLon, lastLat, lastLon);
// Add artificial tag for the estimated distance
way.setTag("estimated_distance", estimatedDist);
estimatedCenter = new GHPoint((firstLat + lastLat) / 2, (firstLon + lastLon) / 2);
}

And the reason we have to consider the distance of the entire way is that 1) the duration tag refers to the duration of the entire way and 2) ferry ways sometimes intersect and are thus split into several edges for which we cannot directly use the duration tag.

double estimatedLengthInKm = estimatedLength.doubleValue() / 1000;
// If duration AND distance is available we can calculate the speed more precisely
// and set both speed to the same value. Factor 1.4 slower because of waiting time!
double calculatedTripSpeed = estimatedLengthInKm / durationInHours / 1.4;
// Plausibility check especially for the case of wrongly used PxM format with the intention to
// specify the duration in minutes, but actually using months
if (calculatedTripSpeed > 0.01d) {
if (calculatedTripSpeed > maxSpeed) {
return maxSpeed;
}
// If the speed is lower than the speed we can store, we have to set it to the minSpeed, but > 0
if (Math.round(calculatedTripSpeed) < speedFactor / 2) {
return speedFactor / 2;
}
// todo: We currently face two problems related to ferry speeds:
// 1) We cannot account for waiting times for short ferries (when we do the ferry speed is slower than the slowest we can store)
// 2) When the ferry speed is larger than the maximum speed of the encoder (like 15km/h for foot) the
// ferry speed will be faster than what we can store.

return Math.round(calculatedTripSpeed);
} else {
long lastId = way.getNodes().isEmpty() ? -1 : way.getNodes().get(way.getNodes().size() - 1);
long firstId = way.getNodes().isEmpty() ? -1 : way.getNodes().get(0);
if (firstId != lastId)
LOGGER.warn("Unrealistic long duration ignored in way with way ID=" + way.getId() + " : Duration tag value="
+ way.getTag("duration") + " (=" + Math.round(duration / 60d) + " minutes)");
durationInHours = 0;
}
}
}

if (durationInHours == 0) {
if (estimatedLength != null && estimatedLength.doubleValue() <= 300)
return speedFactor / 2;
// unknown speed -> put penalty on ferry transport
return unknownSpeed;
} else if (durationInHours > 1) {
// lengthy ferries should be faster than short trip ferry
return longSpeed;
// OSMReader adds the artificial 'speed_from_duration', 'duration:seconds' and 'way_distance' tags that we can
// use to set the ferry speed. Otherwise we need to use fallback values.
double speedInKmPerHour = way.getTag("speed_from_duration", Double.NaN);
if (!Double.isNaN(speedInKmPerHour)) {
// we reduce the speed to account for waiting time (we increase the duration by 40%)
double speedWithWaitingTime = speedInKmPerHour / 1.4;
return Math.round(Math.max(minSpeed, Math.min(speedWithWaitingTime, maxSpeed)));
} else {
return shortSpeed;
// we have no speed value to work with because there was no valid duration tag.
// we have to take a guess based on the distance.
double wayDistance = way.getTag("way_distance", Double.NaN);
if (Double.isNaN(wayDistance))
// we don't know the distance of this way either. probably a broken way at the border of the map.
return unknownSpeed;
else if (wayDistance < 300)
// use the slowest possible speed for very short ferries
return minSpeed;
else {
// todo: distinguish speed based on the distance of the ferry, see #2532
return unknownSpeed;
}
}
}
}
Loading