Skip to content

Commit

Permalink
refactor: Cleanup routing profile management (#1790)
Browse files Browse the repository at this point in the history
  • Loading branch information
aoles committed May 15, 2024
2 parents 738c50c + 56e4f73 commit 2740e85
Show file tree
Hide file tree
Showing 12 changed files with 581 additions and 544 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.heigit.ors.api.errors.CommonResponseEntityExceptionHandler;
import org.heigit.ors.api.requests.export.ExportRequest;
import org.heigit.ors.api.requests.export.ExportApiRequest;
import org.heigit.ors.api.responses.export.json.JsonExportResponse;
import org.heigit.ors.api.services.ExportService;
import org.heigit.ors.exceptions.*;
Expand Down Expand Up @@ -68,7 +68,7 @@ public void getGetMapping() throws MissingParameterException {

@PostMapping
@Operation(hidden = true)
public String getPostMapping(@RequestBody ExportRequest request) throws MissingParameterException {
public String getPostMapping(@RequestBody ExportApiRequest request) throws MissingParameterException {
throw new MissingParameterException(ExportErrorCodes.MISSING_PARAMETER, "profile");
}

Expand Down Expand Up @@ -97,7 +97,7 @@ public void getInvalidResponseType() throws StatusCodeException {
)
})
public JsonExportResponse getDefault(@Parameter(description = "Specifies the route profile.", required = true, example = "driving-car") @PathVariable APIEnums.Profile profile,
@Parameter(description = "The request payload", required = true) @RequestBody ExportRequest request) throws StatusCodeException {
@Parameter(description = "The request payload", required = true) @RequestBody ExportApiRequest request) throws StatusCodeException {
return getJsonExport(profile, request);
}

Expand All @@ -116,7 +116,7 @@ public JsonExportResponse getDefault(@Parameter(description = "Specifies the rou
})
public JsonExportResponse getJsonExport(
@Parameter(description = "Specifies the profile.", required = true, example = "driving-car") @PathVariable APIEnums.Profile profile,
@Parameter(description = "The request payload", required = true) @RequestBody ExportRequest request) throws StatusCodeException {
@Parameter(description = "The request payload", required = true) @RequestBody ExportApiRequest request) throws StatusCodeException {
request.setProfile(profile);
request.setResponseType(APIEnums.ExportResponseType.JSON);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

@Schema(title = "Graph export Service", name = "graphExportService", description = "Graph export service endpoint.")
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class ExportRequest extends APIRequest {
public class ExportApiRequest extends APIRequest {
public static final String PARAM_ID = "id";
public static final String PARAM_BBOX = "bbox";
public static final String PARAM_PROFILE = "profile";
Expand Down Expand Up @@ -45,7 +45,7 @@ public class ExportRequest extends APIRequest {
private boolean debug;

@JsonCreator
public ExportRequest(@JsonProperty(value = PARAM_BBOX, required = true) List<List<Double>> bbox) {
public ExportApiRequest(@JsonProperty(value = PARAM_BBOX, required = true) List<List<Double>> bbox) {
this.bbox = bbox;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
import com.google.common.primitives.Doubles;
import com.graphhopper.util.shapes.BBox;
import org.heigit.ors.api.EndpointsProperties;
import org.heigit.ors.api.requests.export.ExportRequest;
import org.heigit.ors.api.requests.export.ExportApiRequest;
import org.heigit.ors.common.StatusCode;
import org.heigit.ors.exceptions.InternalServerException;
import org.heigit.ors.exceptions.ParameterValueException;
import org.heigit.ors.exceptions.StatusCodeException;
import org.heigit.ors.export.ExportErrorCodes;
import org.heigit.ors.export.ExportResult;
import org.heigit.ors.routing.RoutingProfile;
import org.heigit.ors.routing.RoutingProfileManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
Expand All @@ -23,19 +25,22 @@ public ExportService(EndpointsProperties endpointsProperties) {
this.endpointsProperties = endpointsProperties;
}

public ExportResult generateExportFromRequest(ExportRequest exportApiRequest) throws StatusCodeException {
public ExportResult generateExportFromRequest(ExportApiRequest exportApiRequest) throws StatusCodeException {
org.heigit.ors.export.ExportRequest exportRequest = this.convertExportRequest(exportApiRequest);

try {
return RoutingProfileManager.getInstance().computeExport(exportRequest);
RoutingProfile rp = RoutingProfileManager.getInstance().getProfileFromType(exportRequest.getProfileType());
if (rp == null)
throw new InternalServerException(ExportErrorCodes.UNKNOWN, "Unable to find an appropriate routing profile.");
return exportRequest.computeExport(rp);
} catch (StatusCodeException e) {
throw e;
} catch (Exception e) {
throw new StatusCodeException(StatusCode.INTERNAL_SERVER_ERROR, ExportErrorCodes.UNKNOWN);
}
}

private org.heigit.ors.export.ExportRequest convertExportRequest(ExportRequest exportApiRequest) throws StatusCodeException {
private org.heigit.ors.export.ExportRequest convertExportRequest(ExportApiRequest exportApiRequest) throws StatusCodeException {
org.heigit.ors.export.ExportRequest exportRequest = new org.heigit.ors.export.ExportRequest();

if (exportApiRequest.hasId())
Expand All @@ -47,7 +52,7 @@ private org.heigit.ors.export.ExportRequest convertExportRequest(ExportRequest e
profileType = convertRouteProfileType(exportApiRequest.getProfile());
exportRequest.setProfileType(profileType);
} catch (Exception e) {
throw new ParameterValueException(ExportErrorCodes.INVALID_PARAMETER_VALUE, ExportRequest.PARAM_PROFILE);
throw new ParameterValueException(ExportErrorCodes.INVALID_PARAMETER_VALUE, ExportApiRequest.PARAM_PROFILE);
}

exportRequest.setBoundingBox(convertBBox(exportApiRequest.getBbox()));
Expand All @@ -58,7 +63,7 @@ private org.heigit.ors.export.ExportRequest convertExportRequest(ExportRequest e

BBox convertBBox(List<List<Double>> coordinates) throws ParameterValueException {
if (coordinates.size() != 2) {
throw new ParameterValueException(ExportErrorCodes.INVALID_PARAMETER_VALUE, ExportRequest.PARAM_BBOX);
throw new ParameterValueException(ExportErrorCodes.INVALID_PARAMETER_VALUE, ExportApiRequest.PARAM_BBOX);
}

double[] coords = {};
Expand All @@ -72,7 +77,7 @@ BBox convertBBox(List<List<Double>> coordinates) throws ParameterValueException

private double[] convertSingleCoordinate(List<Double> coordinate) throws ParameterValueException {
if (coordinate.size() != 2) {
throw new ParameterValueException(ExportErrorCodes.INVALID_PARAMETER_VALUE, ExportRequest.PARAM_BBOX);
throw new ParameterValueException(ExportErrorCodes.INVALID_PARAMETER_VALUE, ExportApiRequest.PARAM_BBOX);
}

return new double[]{coordinate.get(0), coordinate.get(1)};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.heigit.ors.api.requests.matrix.MatrixRequest;
import org.heigit.ors.api.requests.matrix.MatrixRequestEnums;
import org.heigit.ors.api.requests.routing.RouteRequest;
import org.heigit.ors.exceptions.InternalServerException;
import org.heigit.ors.exceptions.ParameterValueException;
import org.heigit.ors.exceptions.ServerLimitExceededException;
import org.heigit.ors.exceptions.StatusCodeException;
Expand All @@ -13,6 +14,7 @@
import org.heigit.ors.matrix.MatrixSearchParameters;
import org.heigit.ors.api.APIEnums;
import org.heigit.ors.routing.RoutingErrorCodes;
import org.heigit.ors.routing.RoutingProfile;
import org.heigit.ors.routing.RoutingProfileManager;
import org.heigit.ors.routing.RoutingProfileType;
import org.locationtech.jts.geom.Coordinate;
Expand All @@ -36,7 +38,10 @@ public MatrixResult generateMatrixFromRequest(MatrixRequest matrixRequest) throw
org.heigit.ors.matrix.MatrixRequest coreRequest = this.convertMatrixRequest(matrixRequest);

try {
return RoutingProfileManager.getInstance().computeMatrix(coreRequest);
RoutingProfile rp = RoutingProfileManager.getInstance().getProfileFromType(coreRequest.getProfileType(), !coreRequest.getFlexibleMode());
if (rp == null)
throw new InternalServerException(MatrixErrorCodes.UNKNOWN, "Unable to find an appropriate routing profile.");
return coreRequest.computeMatrix(rp);
} catch (StatusCodeException e) {
throw e;
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,16 @@
package org.heigit.ors.api.services;

import com.graphhopper.GraphHopper;
import com.graphhopper.routing.util.AccessFilter;
import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.GraphHopperStorage;
import com.graphhopper.util.PMap;
import org.heigit.ors.api.requests.snapping.SnappingApiRequest;
import org.heigit.ors.common.StatusCode;
import org.heigit.ors.exceptions.InternalServerException;
import org.heigit.ors.exceptions.ParameterValueException;
import org.heigit.ors.exceptions.PointNotFoundException;
import org.heigit.ors.exceptions.StatusCodeException;
import org.heigit.ors.matrix.MatrixSearchContext;
import org.heigit.ors.matrix.MatrixSearchContextBuilder;
import org.heigit.ors.routing.RoutingProfile;
import org.heigit.ors.routing.RoutingProfileManager;
import org.heigit.ors.routing.RoutingProfileType;
import org.heigit.ors.routing.WeightingMethod;
import org.heigit.ors.routing.graphhopper.extensions.ORSWeightingFactory;
import org.heigit.ors.snapping.SnappingErrorCodes;
import org.heigit.ors.snapping.SnappingRequest;
import org.heigit.ors.snapping.SnappingResult;
import org.heigit.ors.util.ProfileTools;
import org.locationtech.jts.geom.Coordinate;
import org.springframework.stereotype.Service;

Expand All @@ -34,10 +23,10 @@ public SnappingResult generateSnappingFromRequest(SnappingApiRequest snappingApi
SnappingRequest snappingRequest = this.convertSnappingRequest(snappingApiRequest);

try {
RoutingProfileManager rpm = RoutingProfileManager.getInstance();
RoutingProfile rp = rpm.getProfiles().getRouteProfile(snappingRequest.getProfileType());
GraphHopper gh = rp.getGraphhopper();
return computeResult(snappingRequest, gh);
RoutingProfile rp = RoutingProfileManager.getInstance().getProfileFromType(snappingRequest.getProfileType());
if (rp == null)
throw new InternalServerException(SnappingErrorCodes.UNKNOWN, "Unable to find an appropriate routing profile.");
return snappingRequest.computeResult(rp);
} catch (PointNotFoundException e) {
throw new StatusCodeException(StatusCode.NOT_FOUND, SnappingErrorCodes.POINT_NOT_FOUND, e.getMessage());
} catch (StatusCodeException e) {
Expand Down Expand Up @@ -81,21 +70,4 @@ private static Coordinate convertLocation(List<Double> location) throws StatusCo
return new Coordinate(location.get(0), location.get(1));
}

public SnappingResult computeResult(SnappingRequest snappingRequest, GraphHopper gh) throws Exception {
String encoderName = RoutingProfileType.getEncoderName(snappingRequest.getProfileType());
FlagEncoder flagEncoder = gh.getEncodingManager().getEncoder(encoderName);
PMap hintsMap = new PMap();
int weightingMethod = WeightingMethod.RECOMMENDED; // Only needed to create the profile string
ProfileTools.setWeightingMethod(hintsMap, weightingMethod, snappingRequest.getProfileType(), false);
ProfileTools.setWeighting(hintsMap, weightingMethod, snappingRequest.getProfileType(), false);
String profileName = ProfileTools.makeProfileName(encoderName, hintsMap.getString("weighting", ""), false);
GraphHopperStorage ghStorage = gh.getGraphHopperStorage();
String graphDate = ghStorage.getProperties().get("datareader.import.date");

// TODO: replace usage of matrix search context by snapping-specific class
MatrixSearchContextBuilder builder = new MatrixSearchContextBuilder(ghStorage, gh.getLocationIndex(), AccessFilter.allEdges(flagEncoder.getAccessEnc()), true);
Weighting weighting = new ORSWeightingFactory(ghStorage, gh.getEncodingManager()).createWeighting(gh.getProfile(profileName), hintsMap, false);
MatrixSearchContext mtxSearchCntx = builder.create(ghStorage.getBaseGraph(), null, weighting, profileName, snappingRequest.getLocations(), snappingRequest.getLocations(), snappingRequest.getMaximumSearchRadius());
return new SnappingResult(mtxSearchCntx.getSources().getLocations(), graphDate);
}
}
118 changes: 115 additions & 3 deletions ors-engine/src/main/java/org/heigit/ors/export/ExportRequest.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,48 @@
package org.heigit.ors.export;

import com.graphhopper.GraphHopper;
import com.graphhopper.routing.util.AccessFilter;
import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.Graph;
import com.graphhopper.storage.NodeAccess;
import com.graphhopper.storage.index.LocationIndex;
import com.graphhopper.util.EdgeExplorer;
import com.graphhopper.util.EdgeIterator;
import com.graphhopper.util.EdgeIteratorState;
import com.graphhopper.util.PMap;
import com.graphhopper.util.shapes.BBox;
import org.apache.log4j.Logger;
import org.heigit.ors.common.Pair;
import org.heigit.ors.common.ServiceRequest;
import org.heigit.ors.routing.RoutingProfile;
import org.heigit.ors.routing.RoutingProfileType;
import org.heigit.ors.routing.WeightingMethod;
import org.heigit.ors.routing.graphhopper.extensions.WheelchairAttributes;
import org.heigit.ors.routing.graphhopper.extensions.storages.GraphStorageUtils;
import org.heigit.ors.routing.graphhopper.extensions.storages.OsmIdGraphStorage;
import org.heigit.ors.routing.graphhopper.extensions.storages.WheelchairAttributesGraphStorage;
import org.heigit.ors.util.ProfileTools;
import org.locationtech.jts.geom.Coordinate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ExportRequest extends ServiceRequest {
private BBox bbox;
private static final Logger LOGGER = Logger.getLogger(ExportRequest.class);
private BBox boundingBox;

private int profileType = -1;

private boolean debug;

public BBox getBoundingBox() {
return this.bbox;
return this.boundingBox;
}

public void setBoundingBox(BBox bbox) {
this.bbox = bbox;
this.boundingBox = bbox;
}

public int getProfileType() {
Expand All @@ -33,4 +60,89 @@ public void setDebug(boolean debug) {
public boolean debug() {
return debug;
}

public ExportResult computeExport(RoutingProfile routingProfile) {
ExportResult res = new ExportResult();

GraphHopper gh = routingProfile.getGraphhopper();
String encoderName = RoutingProfileType.getEncoderName(getProfileType());
Graph graph = gh.getGraphHopperStorage().getBaseGraph();

PMap hintsMap = new PMap();
int weightingMethod = WeightingMethod.FASTEST;
ProfileTools.setWeightingMethod(hintsMap, weightingMethod, getProfileType(), false);
String profileName = ProfileTools.makeProfileName(encoderName, hintsMap.getString("weighting_method", ""), false);
Weighting weighting = gh.createWeighting(gh.getProfile(profileName), hintsMap);

FlagEncoder flagEncoder = gh.getEncodingManager().getEncoder(encoderName);
EdgeExplorer explorer = graph.createEdgeExplorer(AccessFilter.outEdges(flagEncoder.getAccessEnc()));


// filter graph for nodes in Bounding Box
LocationIndex index = gh.getLocationIndex();
NodeAccess nodeAccess = graph.getNodeAccess();
BBox bbox = getBoundingBox();

ArrayList<Integer> nodesInBBox = new ArrayList<>();
index.query(bbox, edgeId -> {
// According to GHUtility.getEdgeFromEdgeKey, edgeIds are calculated as edgeKey/2.
EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2);
int baseNode = edge.getBaseNode();
int adjNode = edge.getAdjNode();

if (bbox.contains(nodeAccess.getLat(baseNode), nodeAccess.getLon(baseNode))) {
nodesInBBox.add(baseNode);
}
if (bbox.contains(nodeAccess.getLat(adjNode), nodeAccess.getLon(adjNode))) {
nodesInBBox.add(adjNode);
}
});

LOGGER.debug("Found %d nodes in bbox.".formatted(nodesInBBox.size()));

if (nodesInBBox.isEmpty()) {
// without nodes, no export can be calculated
res.setWarning(new ExportWarning(ExportWarning.EMPTY_BBOX));
return res;
}

// calculate node coordinates
for (int from : nodesInBBox) {
Coordinate coord = new Coordinate(nodeAccess.getLon(from), nodeAccess.getLat(from));
res.addLocation(from, coord);

EdgeIterator iter = explorer.setBaseNode(from);
while (iter.next()) {
int to = iter.getAdjNode();
if (nodesInBBox.contains(to)) {
double weight = weighting.calcEdgeWeight(iter, false, EdgeIterator.NO_EDGE);
Pair<Integer, Integer> p = new Pair<>(from, to);
res.addEdge(p, weight);

if (debug()) {
Map<String, Object> extra = new HashMap<>();
extra.put("edge_id", iter.getEdge());
WheelchairAttributesGraphStorage storage = GraphStorageUtils.getGraphExtension(gh.getGraphHopperStorage(), WheelchairAttributesGraphStorage.class);
if (storage != null) {
WheelchairAttributes attributes = new WheelchairAttributes();
byte[] buffer = new byte[WheelchairAttributesGraphStorage.BYTE_COUNT];
storage.getEdgeValues(iter.getEdge(), attributes, buffer);
if (attributes.hasValues()) {
extra.put("incline", attributes.getIncline());
extra.put("surface_quality_known", attributes.isSurfaceQualityKnown());
extra.put("suitable", attributes.isSuitable());
}
}
OsmIdGraphStorage storage2 = GraphStorageUtils.getGraphExtension(gh.getGraphHopperStorage(), OsmIdGraphStorage.class);
if (storage2 != null) {
extra.put("osm_id", storage2.getEdgeValue(iter.getEdge()));
}
res.addEdgeExtra(p, extra);
}
}
}
}

return res;
}
}

0 comments on commit 2740e85

Please sign in to comment.