use of com.graphhopper.routing.querygraph.QueryGraph 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.routing.querygraph.QueryGraph in project graphhopper by graphhopper.
the class PtLocationSnapper method snapAll.
public Result snapAll(List<GHLocation> locations, List<EdgeFilter> snapFilters) {
PointList points = new PointList(2, false);
ArrayList<Snap> pointSnaps = new ArrayList<>();
ArrayList<Supplier<Label.NodeId>> allSnaps = new ArrayList<>();
for (int i = 0; i < locations.size(); i++) {
GHLocation location = locations.get(i);
if (location instanceof GHPointLocation) {
GHPoint point = ((GHPointLocation) location).ghPoint;
final Snap closest = locationIndex.findClosest(point.lat, point.lon, snapFilters.get(i));
if (!closest.isValid()) {
IntHashSet result = new IntHashSet();
gtfsStorage.getStopIndex().findEdgeIdsInNeighborhood(point.lat, point.lon, 0, result::add);
gtfsStorage.getStopIndex().findEdgeIdsInNeighborhood(point.lat, point.lon, 1, result::add);
if (result.isEmpty()) {
throw new PointNotFoundException("Cannot find point: " + point, i);
}
IntCursor stopNodeId = result.iterator().next();
for (Map.Entry<GtfsStorage.FeedIdWithStopId, Integer> e : gtfsStorage.getStationNodes().entrySet()) {
if (e.getValue() == stopNodeId.value) {
Stop stop = gtfsStorage.getGtfsFeeds().get(e.getKey().feedId).stops.get(e.getKey().stopId);
final Snap stopSnap = new Snap(stop.stop_lat, stop.stop_lon);
stopSnap.setClosestNode(stopNodeId.value);
allSnaps.add(() -> new Label.NodeId(Optional.ofNullable(gtfsStorage.getPtToStreet().get(stopSnap.getClosestNode())).orElse(-1), stopSnap.getClosestNode()));
points.add(stopSnap.getQueryPoint().lat, stopSnap.getQueryPoint().lon);
}
}
} else {
pointSnaps.add(closest);
allSnaps.add(() -> new Label.NodeId(closest.getClosestNode(), Optional.ofNullable(gtfsStorage.getStreetToPt().get(closest.getClosestNode())).orElse(-1)));
points.add(closest.getSnappedPoint());
}
} else if (location instanceof GHStationLocation) {
final Snap stopSnap = findByStopId((GHStationLocation) location, i);
allSnaps.add(() -> new Label.NodeId(Optional.ofNullable(gtfsStorage.getPtToStreet().get(stopSnap.getClosestNode())).orElse(-1), stopSnap.getClosestNode()));
points.add(stopSnap.getQueryPoint().lat, stopSnap.getQueryPoint().lon);
}
}
// modifies pointSnaps!
QueryGraph queryGraph = QueryGraph.create(graphHopperStorage, pointSnaps);
List<Label.NodeId> nodes = new ArrayList<>();
for (Supplier<Label.NodeId> supplier : allSnaps) {
nodes.add(supplier.get());
}
return new Result(queryGraph, nodes, points);
}
Aggregations