use of com.graphhopper.storage.index.Snap in project graphhopper by graphhopper.
the class QueryGraphTest method testTurnCostsProperlyPropagated_Issue282.
@Test
public void testTurnCostsProperlyPropagated_Issue282() {
FlagEncoder encoder = new CarFlagEncoder(5, 5, 15);
EncodingManager em = EncodingManager.create(encoder);
GraphHopperStorage graphWithTurnCosts = new GraphBuilder(em).withTurnCosts(true).create();
TurnCostStorage turnExt = graphWithTurnCosts.getTurnCostStorage();
DecimalEncodedValue turnCostEnc = em.getDecimalEncodedValue(TurnCost.key(encoder.toString()));
NodeAccess na = graphWithTurnCosts.getNodeAccess();
na.setNode(0, .00, .00);
na.setNode(1, .00, .01);
na.setNode(2, .01, .01);
EdgeIteratorState edge0 = GHUtility.setSpeed(60, true, true, encoder, graphWithTurnCosts.edge(0, 1).setDistance(10));
EdgeIteratorState edge1 = GHUtility.setSpeed(60, true, true, encoder, graphWithTurnCosts.edge(2, 1).setDistance(10));
Weighting weighting = new FastestWeighting(encoder, new DefaultTurnCostProvider(encoder, graphWithTurnCosts.getTurnCostStorage()));
// no turn costs initially
assertEquals(0, weighting.calcTurnWeight(edge0.getEdge(), 1, edge1.getEdge()), .1);
// now use turn costs
turnExt.set(turnCostEnc, edge0.getEdge(), 1, edge1.getEdge(), 10);
assertEquals(10, weighting.calcTurnWeight(edge0.getEdge(), 1, edge1.getEdge()), .1);
// now use turn costs with query graph
Snap res1 = createLocationResult(0.000, 0.005, edge0, 0, Snap.Position.EDGE);
Snap res2 = createLocationResult(0.005, 0.010, edge1, 0, Snap.Position.EDGE);
QueryGraph qGraph = QueryGraph.create(graphWithTurnCosts, res1, res2);
weighting = qGraph.wrapWeighting(weighting);
int fromQueryEdge = GHUtility.getEdge(qGraph, res1.getClosestNode(), 1).getEdge();
int toQueryEdge = GHUtility.getEdge(qGraph, res2.getClosestNode(), 1).getEdge();
assertEquals(10, weighting.calcTurnWeight(fromQueryEdge, 1, toQueryEdge), .1);
graphWithTurnCosts.close();
}
use of com.graphhopper.storage.index.Snap in project graphhopper by graphhopper.
the class QueryGraphTest method testVirtualEdgeDistance.
@Test
public void testVirtualEdgeDistance() {
// x
// -----
// | |
// 0 1
NodeAccess na = g.getNodeAccess();
na.setNode(0, 0, 0);
na.setNode(1, 0, 1);
// dummy node to make sure graph bounds are valid
na.setNode(2, 2, 2);
DistanceCalc distCalc = DistancePlaneProjection.DIST_PLANE;
double dist = 0;
dist += distCalc.calcDist(0, 0, 1, 0);
dist += distCalc.calcDist(1, 0, 1, 1);
dist += distCalc.calcDist(1, 1, 0, 1);
GHUtility.setSpeed(60, true, true, encoder, g.edge(0, 1).setDistance(dist)).setWayGeometry(Helper.createPointList(1, 0, 1, 1));
LocationIndexTree index = new LocationIndexTree(g, new RAMDirectory());
index.prepareIndex();
Snap snap = index.findClosest(1.01, 0.7, EdgeFilter.ALL_EDGES);
QueryGraph queryGraph = lookup(snap);
// the sum of the virtual edge distances adjacent to the virtual node should be equal to the distance
// of the real edge, so the 'distance' from 0 to 1 is the same no matter if we travel on the query graph or the
// real graph
EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(3);
double virtualEdgeDistanceSum = 0;
while (iter.next()) {
virtualEdgeDistanceSum += iter.getDistance();
}
double directDist = g.getEdgeIteratorState(0, 1).getDistance();
assertEquals(directDist, virtualEdgeDistanceSum, 1.e-3);
}
use of com.graphhopper.storage.index.Snap in project graphhopper by graphhopper.
the class PrepareContractionHierarchiesTest method testStallOnDemandViaVirtuaNode_issue1574.
@Test
public void testStallOnDemandViaVirtuaNode_issue1574() {
// this test reproduces the issue that appeared in issue1574
// the problem is very intricate and a combination of all these things:
// * contraction hierarchies
// * stall-on-demand (without sod there is no problem, at least in this test)
// * shortcuts weight rounding
// * via nodes/virtual edges and the associated weight precision (without virtual nodes between source and target
// there is no problem, but this can happen for via routes
// * the fact that the CHLevelEdgeFilter always accepts virtual nodes
// here we will construct a special case where a connection is not found without the fix in #1574.
g = createGHStorage();
// use fastest weighting in this test to be able to fine-tune some weights via the speed (see below)
Weighting fastestWeighting = new FastestWeighting(carEncoder);
CHConfig chConfig = CHConfig.nodeBased("c", fastestWeighting);
// the following graph reproduces the issue. note that we will use the node ids as ch levels, so there will
// be a shortcut 3->2 visible at node 2 and another one 3->4 visible at node 3.
// we will fine-tune the edge-speeds such that without the fix node 4 will be stalled and node 5 will not get
// discovered. consequently, no path will be found, because only the forward search runs (from 0 to 7 the
// shortest path is strictly upward). node 4 is only stalled when node 2 gets stalled before, which in turn will
// happen due to the virtual node between 3 and 1.
//
// start 0 - 3 - x - 1 - 2
// \ |
// sc ---- 4 - 5 - 6 - 7 finish
GHUtility.setSpeed(60, true, true, carEncoder, g.edge(0, 3).setDistance(1));
EdgeIteratorState edge31 = GHUtility.setSpeed(60, true, true, carEncoder, g.edge(3, 1).setDistance(1));
GHUtility.setSpeed(60, true, true, carEncoder, g.edge(1, 2).setDistance(1));
EdgeIteratorState edge24 = GHUtility.setSpeed(60, true, true, carEncoder, g.edge(2, 4).setDistance(1));
GHUtility.setSpeed(60, true, true, carEncoder, g.edge(4, 5).setDistance(1));
GHUtility.setSpeed(60, true, true, carEncoder, g.edge(5, 6).setDistance(1));
GHUtility.setSpeed(60, true, true, carEncoder, g.edge(6, 7).setDistance(1));
updateDistancesFor(g, 0, 0.001, 0.0000);
updateDistancesFor(g, 3, 0.001, 0.0001);
updateDistancesFor(g, 1, 0.001, 0.0002);
updateDistancesFor(g, 2, 0.001, 0.0003);
updateDistancesFor(g, 4, 0.000, 0.0003);
updateDistancesFor(g, 5, 0.000, 0.0004);
updateDistancesFor(g, 6, 0.000, 0.0005);
updateDistancesFor(g, 7, 0.000, 0.0006);
// we use the speed to fine tune some weights:
// the weight of edge 3-1 is chosen such that node 2 gets stalled in the forward search via the incoming shortcut
// at node 2 coming from 3. this happens because due to the virtual node x between 3 and 1, the weight of the
// spt entry at 2 is different to the sum of the weights of the spt entry at node 3 and the shortcut edge. this
// is due to different floating point rounding arithmetic of shortcuts and virtual edges on the query graph.
edge31.set(carEncoder.getAverageSpeedEnc(), 12, 12);
// just stalling node 2 alone would not lead to connection not found, because the shortcut 3-4 still finds node
// 4. however, we can choose the weight of edge 2-4 such that node 4 also gets stalled via node 2.
// it is important that node 2 gets stalled before otherwise node 4 would have already be discovered.
// note that without the virtual node between 3 and 1 node 2 would not even be explored in the forward search,
// but because of the virtual node the strict upward search is modified and goes like 0-3-x-1-2.
edge24.set(carEncoder.getAverageSpeedEnc(), 27.5, 27.5);
// prepare ch, use node ids as levels
PrepareContractionHierarchies pch = createPrepareContractionHierarchies(g, chConfig);
PrepareContractionHierarchies.Result res = pch.useFixedNodeOrdering(NodeOrderingProvider.identity(g.getNodes())).doWork();
RoutingCHGraph routingCHGraph = g.createCHGraph(res.getCHStorage(), res.getCHConfig());
assertEquals(2, routingCHGraph.getEdges() - g.getEdges(), "there should be exactly two (bidirectional) shortcuts (2-3) and (3-4)");
// insert virtual node and edges
Snap snap = new Snap(0.0001, 0.0015);
snap.setClosestEdge(edge31);
snap.setSnappedPosition(Snap.Position.EDGE);
snap.setClosestNode(8);
snap.setWayIndex(0);
snap.calcSnappedPoint(new DistanceCalcEuclidean());
QueryGraph queryGraph = QueryGraph.create(g, snap);
// we make sure our weight fine tunings do what they are supposed to
double weight03 = getWeight(queryGraph, fastestWeighting, 0, 3, false);
double scWeight23 = weight03 + getEdge(routingCHGraph, 2, 3, true).getWeight(false);
double scWeight34 = weight03 + getEdge(routingCHGraph, 3, 4, false).getWeight(false);
double sptWeight2 = weight03 + getWeight(queryGraph, fastestWeighting, 3, 8, false) + getWeight(queryGraph, fastestWeighting, 8, 1, false) + getWeight(queryGraph, fastestWeighting, 1, 2, false);
double sptWeight4 = sptWeight2 + getWeight(queryGraph, fastestWeighting, 2, 4, false);
assertTrue(scWeight23 < sptWeight2, "incoming shortcut weight 3->2 should be smaller than sptWeight at node 2 to make sure 2 gets stalled");
assertTrue(sptWeight4 < scWeight34, "sptWeight at node 4 should be smaller than shortcut weight 3->4 to make sure node 4 gets stalled");
Path path = new CHRoutingAlgorithmFactory(routingCHGraph, queryGraph).createAlgo(new PMap()).calcPath(0, 7);
assertEquals(IntArrayList.from(0, 3, 8, 1, 2, 4, 5, 6, 7), path.calcNodes(), "wrong or no path found");
}
use of com.graphhopper.storage.index.Snap in project graphhopper by graphhopper.
the class SPTResource method doGet.
// Annotating this as application/json because errors come out as json, and
// IllegalArgumentExceptions are not mapped to a fixed mediatype, because in RouteResource, it could be GPX.
@GET
@Produces({ "text/csv", "application/json" })
public Response doGet(@Context UriInfo uriInfo, @QueryParam("profile") String profileName, @QueryParam("reverse_flow") @DefaultValue("false") boolean reverseFlow, @QueryParam("point") @NotNull GHPointParam point, @QueryParam("columns") String columnsParam, @QueryParam("time_limit") @DefaultValue("600") LongParam timeLimitInSeconds, @QueryParam("distance_limit") @DefaultValue("-1") LongParam distanceInMeter) {
StopWatch sw = new StopWatch().start();
PMap hintsMap = new PMap();
RouteResource.initHints(hintsMap, uriInfo.getQueryParameters());
hintsMap.putObject(Parameters.CH.DISABLE, true);
hintsMap.putObject(Parameters.Landmark.DISABLE, true);
if (Helper.isEmpty(profileName)) {
profileName = profileResolver.resolveProfile(hintsMap).getName();
removeLegacyParameters(hintsMap);
}
errorIfLegacyParameters(hintsMap);
Profile profile = graphHopper.getProfile(profileName);
if (profile == null)
throw new IllegalArgumentException("The requested profile '" + profileName + "' does not exist");
LocationIndex locationIndex = graphHopper.getLocationIndex();
Graph graph = graphHopper.getGraphHopperStorage();
Weighting weighting = graphHopper.createWeighting(profile, hintsMap);
BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileName));
if (hintsMap.has(Parameters.Routing.BLOCK_AREA)) {
GraphEdgeIdFinder.BlockArea blockArea = GraphEdgeIdFinder.createBlockArea(graph, locationIndex, Collections.singletonList(point.get()), hintsMap, new FiniteWeightFilter(weighting));
weighting = new BlockAreaWeighting(weighting, blockArea);
}
Snap snap = locationIndex.findClosest(point.get().lat, point.get().lon, new DefaultSnapFilter(weighting, inSubnetworkEnc));
if (!snap.isValid())
throw new IllegalArgumentException("Point not found:" + point);
QueryGraph queryGraph = QueryGraph.create(graph, snap);
NodeAccess nodeAccess = queryGraph.getNodeAccess();
TraversalMode traversalMode = profile.isTurnCosts() ? EDGE_BASED : NODE_BASED;
ShortestPathTree shortestPathTree = new ShortestPathTree(queryGraph, queryGraph.wrapWeighting(weighting), reverseFlow, traversalMode);
if (distanceInMeter.get() > 0) {
shortestPathTree.setDistanceLimit(distanceInMeter.get());
} else {
double limit = timeLimitInSeconds.get() * 1000;
shortestPathTree.setTimeLimit(limit);
}
final String COL_SEP = ",", LINE_SEP = "\n";
List<String> columns;
if (!Helper.isEmpty(columnsParam))
columns = Arrays.asList(columnsParam.split(","));
else
columns = Arrays.asList("longitude", "latitude", "time", "distance");
if (columns.isEmpty())
throw new IllegalArgumentException("Either omit the columns parameter or specify the columns via comma separated values");
Map<String, EncodedValue> pathDetails = new HashMap<>();
for (String col : columns) {
if (encodingManager.hasEncodedValue(col))
pathDetails.put(col, encodingManager.getEncodedValue(col, EncodedValue.class));
}
StreamingOutput out = output -> {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(output, Helper.UTF_CS))) {
StringBuilder sb = new StringBuilder();
for (String col : columns) {
if (sb.length() > 0)
sb.append(COL_SEP);
sb.append(col);
}
sb.append(LINE_SEP);
writer.write(sb.toString());
shortestPathTree.search(snap.getClosestNode(), l -> {
IsoLabelWithCoordinates label = isoLabelWithCoordinates(nodeAccess, l);
sb.setLength(0);
for (int colIndex = 0; colIndex < columns.size(); colIndex++) {
String col = columns.get(colIndex);
if (colIndex > 0)
sb.append(COL_SEP);
switch(col) {
case "node_id":
sb.append(label.nodeId);
continue;
case "prev_node_id":
sb.append(label.prevNodeId);
continue;
case "edge_id":
sb.append(label.edgeId);
continue;
case "prev_edge_id":
sb.append(label.prevEdgeId);
continue;
case "distance":
sb.append(label.distance);
continue;
case "prev_distance":
sb.append(label.prevCoordinate == null ? 0 : label.prevDistance);
continue;
case "time":
sb.append(label.timeMillis);
continue;
case "prev_time":
sb.append(label.prevCoordinate == null ? 0 : label.prevTimeMillis);
continue;
case "longitude":
sb.append(Helper.round6(label.coordinate.lon));
continue;
case "prev_longitude":
sb.append(label.prevCoordinate == null ? null : Helper.round6(label.prevCoordinate.lon));
continue;
case "latitude":
sb.append(Helper.round6(label.coordinate.lat));
continue;
case "prev_latitude":
sb.append(label.prevCoordinate == null ? null : Helper.round6(label.prevCoordinate.lat));
continue;
}
if (!EdgeIterator.Edge.isValid(label.edgeId))
continue;
EdgeIteratorState edge = queryGraph.getEdgeIteratorState(label.edgeId, label.nodeId);
if (edge == null)
continue;
if (col.equals(Parameters.Details.STREET_NAME)) {
sb.append(edge.getName().replaceAll(",", ""));
continue;
}
EncodedValue ev = pathDetails.get(col);
if (ev instanceof DecimalEncodedValue) {
DecimalEncodedValue dev = (DecimalEncodedValue) ev;
sb.append(reverseFlow ? edge.getReverse(dev) : edge.get(dev));
} else if (ev instanceof EnumEncodedValue) {
EnumEncodedValue eev = (EnumEncodedValue) ev;
sb.append(reverseFlow ? edge.getReverse(eev) : edge.get(eev));
} else if (ev instanceof BooleanEncodedValue) {
BooleanEncodedValue eev = (BooleanEncodedValue) ev;
sb.append(reverseFlow ? edge.getReverse(eev) : edge.get(eev));
} else if (ev instanceof IntEncodedValue) {
IntEncodedValue eev = (IntEncodedValue) ev;
sb.append(reverseFlow ? edge.getReverse(eev) : edge.get(eev));
} else {
throw new IllegalArgumentException("Unknown property " + col);
}
}
sb.append(LINE_SEP);
try {
writer.write(sb.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
logger.info("took: " + sw.stop().getSeconds() + ", visited nodes:" + shortestPathTree.getVisitedNodes() + ", " + uriInfo.getQueryParameters());
} catch (IOException e) {
throw new RuntimeException(e);
}
};
// Give media type explicitly since we are annotating CSV and JSON, because error messages are JSON.
return Response.ok(out).type("text/csv").build();
}
use of com.graphhopper.storage.index.Snap in project graphhopper by graphhopper.
the class ExtendedJsonResponseTest method getGpxExtension.
private List<State> getGpxExtension() {
List<State> list = new ArrayList<>();
Snap snap1 = new Snap(-3.4445, -38.9990) {
@Override
public GHPoint3D getSnappedPoint() {
return new GHPoint3D(-3.4446, -38.9996, 0);
}
};
Snap snap2 = new Snap(-3.4445, -38.9990) {
@Override
public GHPoint3D getSnappedPoint() {
return new GHPoint3D(-3.4449, -38.9999, 0);
}
};
list.add(new State(new Observation(new GHPoint(-3.4446, -38.9996)), snap1));
list.add(new State(new Observation(new GHPoint(-3.4448, -38.9999)), snap2));
return list;
}
Aggregations