use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.
the class QueryRoutingCHGraphTest method getWeight.
@Test
public void getWeight() {
// /---\
// 0-x-1-2
// 3
na.setNode(0, 50.00, 10.00);
na.setNode(1, 50.00, 10.10);
na.setNode(2, 50.00, 10.20);
EdgeIteratorState edge = addEdge(graph, 0, 1).set(encoder.getAverageSpeedEnc(), 90, 30);
addEdge(graph, 1, 2);
graph.freeze();
CHConfig chConfig = CHConfig.edgeBased("x", weighting);
CHStorage chStore = graph.createCHStorage(chConfig);
RoutingCHGraph routingCHGraph = graph.createCHGraph(chStore, chConfig);
CHStorageBuilder chBuilder = new CHStorageBuilder(chStore);
chBuilder.setIdentityLevels();
chBuilder.addShortcutEdgeBased(0, 2, PrepareEncoder.getScDirMask(), 20, 0, 1, 0, 1);
// without query graph
RoutingCHEdgeIterator iter = routingCHGraph.createOutEdgeExplorer().setBaseNode(0);
assertNextShortcut(iter, 0, 2, 0, 1);
assertEquals(20, iter.getWeight(false), 1.e-6);
assertEquals(20, iter.getWeight(true), 1.e-6);
assertNextEdge(iter, 0, 1, 0);
assertEquals(285.89888, iter.getWeight(false), 1.e-6);
assertEquals(857.69664, iter.getWeight(true), 1.e-6);
assertEnd(iter);
// for incoming edges its the same
iter = routingCHGraph.createInEdgeExplorer().setBaseNode(0);
assertNextShortcut(iter, 0, 2, 0, 1);
assertEquals(20, iter.getWeight(false), 1.e-6);
assertEquals(20, iter.getWeight(true), 1.e-6);
assertNextEdge(iter, 0, 1, 0);
assertEquals(285.89888, iter.getWeight(false), 1.e-6);
assertEquals(857.69664, iter.getWeight(true), 1.e-6);
assertEnd(iter);
// now including virtual edges
Snap snap = new Snap(50.00, 10.05);
snap.setClosestEdge(edge);
snap.setWayIndex(0);
snap.setSnappedPosition(Snap.Position.EDGE);
snap.calcSnappedPoint(DistancePlaneProjection.DIST_PLANE);
QueryGraph queryGraph = QueryGraph.create(graph, Collections.singletonList(snap));
QueryRoutingCHGraph queryCHGraph = new QueryRoutingCHGraph(routingCHGraph, queryGraph);
iter = queryCHGraph.createOutEdgeExplorer().setBaseNode(0);
assertNextEdge(iter, 0, 3, 2);
// should be about half the weight as for the original edge as the query point is in the middle of the edge
assertEquals(142.9494, iter.getWeight(false), 1.e-4);
assertEquals(428.8483, iter.getWeight(true), 1.e-4);
assertNextShortcut(iter, 0, 2, 0, 1);
assertEquals(20, iter.getWeight(false), 1.e-6);
assertEquals(20, iter.getWeight(true), 1.e-6);
assertEnd(iter);
iter = queryCHGraph.createInEdgeExplorer().setBaseNode(0);
assertNextEdge(iter, 0, 3, 2);
assertEquals(142.9494, iter.getWeight(false), 1.e-4);
assertEquals(428.8483, iter.getWeight(true), 1.e-4);
assertNextShortcut(iter, 0, 2, 0, 1);
assertEquals(20, iter.getWeight(false), 1.e-6);
assertEquals(20, iter.getWeight(true), 1.e-6);
assertEnd(iter);
// at the virtual node
iter = queryCHGraph.createOutEdgeExplorer().setBaseNode(3);
assertNextEdge(iter, 3, 0, 2);
assertEquals(428.8483, iter.getWeight(false), 1.e-4);
assertEquals(142.9494, iter.getWeight(true), 1.e-4);
assertNextEdge(iter, 3, 1, 3);
assertEquals(142.9494, iter.getWeight(false), 1.e-4);
assertEquals(428.8483, iter.getWeight(true), 1.e-4);
assertEnd(iter);
iter = queryCHGraph.createInEdgeExplorer().setBaseNode(3);
assertNextEdge(iter, 3, 0, 2);
assertEquals(428.8483, iter.getWeight(false), 1.e-4);
assertEquals(142.9494, iter.getWeight(true), 1.e-4);
assertNextEdge(iter, 3, 1, 3);
assertEquals(142.9494, iter.getWeight(false), 1.e-4);
assertEquals(428.8483, iter.getWeight(true), 1.e-4);
assertEnd(iter);
// getting a single edge
RoutingCHEdgeIteratorState edgeState = queryCHGraph.getEdgeIteratorState(3, 3);
assertEdgeState(edgeState, 0, 3, 2);
assertEquals(142.9494, edgeState.getWeight(false), 1.e-4);
assertEquals(428.8483, edgeState.getWeight(true), 1.e-4);
edgeState = queryCHGraph.getEdgeIteratorState(3, 0);
assertEdgeState(edgeState, 3, 0, 2);
assertEquals(428.8483, edgeState.getWeight(false), 1.e-4);
assertEquals(142.9494, edgeState.getWeight(true), 1.e-4);
}
use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.
the class RandomizedRoutingTest method randomGraph_withQueryGraph.
/**
* Similar to {@link #randomGraph}, but using the {@link QueryGraph} as it is done in real usage.
*/
@ParameterizedTest
@ArgumentsSource(RepeatedFixtureProvider.class)
public void randomGraph_withQueryGraph(Supplier<Fixture> fixtureSupplier) {
Fixture f = fixtureSupplier.get();
final long seed = System.nanoTime();
final int numQueries = 50;
// we may not use an offset when query graph is involved, otherwise traveling via virtual edges will not be
// the same as taking the direct edge!
double pOffset = 0;
Random rnd = new Random(seed);
GHUtility.buildRandomGraph(f.graph, rnd, 50, 2.2, true, true, f.encoder.getAccessEnc(), f.encoder.getAverageSpeedEnc(), null, 0.7, 0.8, pOffset);
GHUtility.addRandomTurnCosts(f.graph, seed, f.encodingManager, f.encoder, f.maxTurnCosts, f.turnCostStorage);
// GHUtility.printGraphForUnitTest(f.graph, f.encoder);
f.preProcessGraph();
LocationIndexTree index = new LocationIndexTree(f.graph, f.dir);
index.prepareIndex();
List<String> strictViolations = new ArrayList<>();
for (int i = 0; i < numQueries; i++) {
List<Snap> snaps = createRandomSnaps(f.graph.getBounds(), index, rnd, 2, true, EdgeFilter.ALL_EDGES);
QueryGraph queryGraph = QueryGraph.create(f.graph, snaps);
int source = snaps.get(0).getClosestNode();
int target = snaps.get(1).getClosestNode();
Path refPath = new DijkstraBidirectionRef(queryGraph, queryGraph.wrapWeighting(f.weighting), f.traversalMode).calcPath(source, target);
Path path = f.createAlgo(queryGraph).calcPath(source, target);
strictViolations.addAll(f.comparePaths(refPath, path, source, target, seed));
}
// however, when there are too many deviations we fail
if (strictViolations.size() > 3) {
LOGGER.warn(strictViolations.toString());
fail("Too many strict violations: " + strictViolations.size() + " / " + numQueries + ", seed: " + seed);
}
}
use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.
the class GraphHopperGtfs method interpolateTransfers.
private void interpolateTransfers(HashMap<String, GtfsReader> readers, Map<String, Transfers> allTransfers) {
LOGGER.info("Looking for transfers");
final int maxTransferWalkTimeSeconds = ghConfig.getInt("gtfs.max_transfer_interpolation_walk_time_seconds", 120);
GraphHopperStorage graphHopperStorage = getGraphHopperStorage();
QueryGraph queryGraph = QueryGraph.create(graphHopperStorage, Collections.emptyList());
Weighting transferWeighting = createWeighting(getProfile("foot"), new PMap());
final GraphExplorer graphExplorer = new GraphExplorer(queryGraph, ptGraph, transferWeighting, getGtfsStorage(), RealtimeFeed.empty(), true, true, false, 5.0, false, 0);
getGtfsStorage().getStationNodes().values().stream().distinct().map(n -> {
int streetNode = Optional.ofNullable(gtfsStorage.getPtToStreet().get(n)).orElse(-1);
return new Label.NodeId(streetNode, n);
}).forEach(stationNode -> {
MultiCriteriaLabelSetting router = new MultiCriteriaLabelSetting(graphExplorer, true, false, false, 0, new ArrayList<>());
router.setLimitStreetTime(Duration.ofSeconds(maxTransferWalkTimeSeconds).toMillis());
for (Label label : router.calcLabels(stationNode, Instant.ofEpochMilli(0))) {
if (label.parent != null) {
if (label.edge.getType() == GtfsStorage.EdgeType.EXIT_PT) {
GtfsStorage.PlatformDescriptor fromPlatformDescriptor = label.edge.getPlatformDescriptor();
Transfers transfers = allTransfers.get(fromPlatformDescriptor.feed_id);
for (PtGraph.PtEdge ptEdge : ptGraph.edgesAround(stationNode.ptNode)) {
if (ptEdge.getType() == GtfsStorage.EdgeType.ENTER_PT) {
GtfsStorage.PlatformDescriptor toPlatformDescriptor = ptEdge.getAttrs().platformDescriptor;
LOGGER.debug(fromPlatformDescriptor + " -> " + toPlatformDescriptor);
if (!toPlatformDescriptor.feed_id.equals(fromPlatformDescriptor.feed_id)) {
LOGGER.debug(" Different feed. Inserting transfer with " + (int) (label.streetTime / 1000L) + " s.");
insertInterpolatedTransfer(label, toPlatformDescriptor, readers);
} else {
List<Transfer> transfersToStop = transfers.getTransfersToStop(toPlatformDescriptor.stop_id, routeIdOrNull(toPlatformDescriptor));
if (transfersToStop.stream().noneMatch(t -> t.from_stop_id.equals(fromPlatformDescriptor.stop_id))) {
LOGGER.debug(" Inserting transfer with " + (int) (label.streetTime / 1000L) + " s.");
insertInterpolatedTransfer(label, toPlatformDescriptor, readers);
}
}
}
}
}
}
}
});
}
use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.
the class IsochroneExample method main.
public static void main(String[] args) {
String relDir = args.length == 1 ? args[0] : "";
GraphHopper hopper = createGraphHopperInstance(relDir + "core/files/andorra.osm.pbf");
// get encoder from GraphHopper instance
EncodingManager encodingManager = hopper.getEncodingManager();
FlagEncoder encoder = encodingManager.getEncoder("car");
// snap some GPS coordinates to the routing graph and build a query graph
FastestWeighting weighting = new FastestWeighting(encoder);
Snap snap = hopper.getLocationIndex().findClosest(42.508679, 1.532078, new DefaultSnapFilter(weighting, encodingManager.getBooleanEncodedValue(Subnetwork.key("car"))));
QueryGraph queryGraph = QueryGraph.create(hopper.getGraphHopperStorage(), snap);
// run the isochrone calculation
ShortestPathTree tree = new ShortestPathTree(queryGraph, weighting, false, TraversalMode.NODE_BASED);
// find all nodes that are within a radius of 120s
tree.setTimeLimit(120_000);
AtomicInteger counter = new AtomicInteger(0);
// you need to specify a callback to define what should be done
tree.search(snap.getClosestNode(), label -> {
// see IsoLabel.java for more properties
// System.out.println("node: " + label.node + ", time: " + label.time + ", distance: " + label.distance);
counter.incrementAndGet();
});
assert counter.get() > 200;
}
use of com.graphhopper.routing.querygraph.QueryGraph in project graphhopper by graphhopper.
the class Router method routeRoundTrip.
protected GHResponse routeRoundTrip(GHRequest request, FlexSolver solver) {
GHResponse ghRsp = new GHResponse();
StopWatch sw = new StopWatch().start();
double startHeading = request.getHeadings().isEmpty() ? Double.NaN : request.getHeadings().get(0);
RoundTripRouting.Params params = new RoundTripRouting.Params(request.getHints(), startHeading, routerConfig.getMaxRoundTripRetries());
List<Snap> snaps = RoundTripRouting.lookup(request.getPoints(), solver.createSnapFilter(), locationIndex, params);
ghRsp.addDebugInfo("idLookup:" + sw.stop().getSeconds() + "s");
QueryGraph queryGraph = QueryGraph.create(ghStorage, snaps);
FlexiblePathCalculator pathCalculator = solver.createPathCalculator(queryGraph);
RoundTripRouting.Result result = RoundTripRouting.calcPaths(snaps, pathCalculator);
// we merge the different legs of the roundtrip into one response path
ResponsePath responsePath = concatenatePaths(request, solver.weighting, queryGraph, result.paths, getWaypoints(snaps));
ghRsp.add(responsePath);
ghRsp.getHints().putObject("visited_nodes.sum", result.visitedNodes);
ghRsp.getHints().putObject("visited_nodes.average", (float) result.visitedNodes / (snaps.size() - 1));
return ghRsp;
}
Aggregations