use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.
the class AlternativeRouteTest method testCalcAlternatives.
@Test
public void testCalcAlternatives() throws Exception {
Weighting weighting = new FastestWeighting(carFE);
GraphHopperStorage g = createTestGraph(true, em);
AlternativeRoute altDijkstra = new AlternativeRoute(g, weighting, traversalMode);
altDijkstra.setMaxShareFactor(0.5);
altDijkstra.setMaxWeightFactor(2);
List<AlternativeRoute.AlternativeInfo> pathInfos = altDijkstra.calcAlternatives(5, 4);
checkAlternatives(pathInfos);
assertEquals(2, pathInfos.size());
DijkstraBidirectionRef dijkstra = new DijkstraBidirectionRef(g, weighting, traversalMode);
Path bestPath = dijkstra.calcPath(5, 4);
Path bestAlt = pathInfos.get(0).getPath();
Path secondAlt = pathInfos.get(1).getPath();
assertEquals(bestPath.calcNodes(), bestAlt.calcNodes());
assertEquals(bestPath.getWeight(), bestAlt.getWeight(), 1e-3);
assertEquals(Helper.createTList(5, 6, 3, 4), bestAlt.calcNodes());
// Note: here plateau is longer, even longer than optimum, but path is longer
// so which alternative is better? longer plateau.weight with bigger path.weight or smaller path.weight with smaller plateau.weight
// assertEquals(Helper.createTList(5, 1, 9, 2, 3, 4), secondAlt.calcNodes());
assertEquals(Helper.createTList(5, 6, 7, 8, 4), secondAlt.calcNodes());
assertEquals(1667.9, secondAlt.getWeight(), .1);
}
use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.
the class TripFromLabel method parsePathIntoLegs.
// We are parsing a string of edges into a hierarchical trip.
// One could argue that one should never write a parser
// by hand, because it is always ugly, but use a parser library.
// The code would then read like a specification of what paths through the graph mean.
private List<Trip.Leg> parsePathIntoLegs(List<Label.Transition> path, GraphExplorer graph, Weighting weighting, Translation tr) {
if (path.size() <= 1) {
return Collections.emptyList();
}
if (GtfsStorage.EdgeType.ENTER_PT == path.get(1).edge.edgeType) {
final GtfsStorage.FeedIdWithTimezone feedIdWithTimezone = gtfsStorage.getTimeZones().get(path.get(1).edge.timeZoneId);
List<Trip.Leg> result = new ArrayList<>();
long boardTime = -1;
List<Label.Transition> partition = null;
for (int i = 1; i < path.size(); i++) {
Label.Transition transition = path.get(i);
Label.EdgeLabel edge = path.get(i).edge;
if (edge.edgeType == GtfsStorage.EdgeType.BOARD) {
boardTime = transition.label.currentTime;
partition = new ArrayList<>();
}
if (partition != null) {
partition.add(path.get(i));
}
if (EnumSet.of(GtfsStorage.EdgeType.TRANSFER, GtfsStorage.EdgeType.LEAVE_TIME_EXPANDED_NETWORK).contains(edge.edgeType)) {
Geometry lineString = lineStringFromEdges(partition);
GtfsRealtime.TripDescriptor tripDescriptor;
try {
tripDescriptor = GtfsRealtime.TripDescriptor.parseFrom(realtimeFeed.getTripDescriptor(partition.get(0).edge.edgeIteratorState.getEdge()));
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
final StopsFromBoardHopDwellEdges stopsFromBoardHopDwellEdges = new StopsFromBoardHopDwellEdges(feedIdWithTimezone.feedId, tripDescriptor);
partition.stream().filter(e -> EnumSet.of(GtfsStorage.EdgeType.HOP, GtfsStorage.EdgeType.BOARD, GtfsStorage.EdgeType.DWELL).contains(e.edge.edgeType)).forEach(stopsFromBoardHopDwellEdges::next);
stopsFromBoardHopDwellEdges.finish();
List<Trip.Stop> stops = stopsFromBoardHopDwellEdges.stops;
result.add(new Trip.PtLeg(feedIdWithTimezone.feedId, partition.get(0).edge.nTransfers == 0, tripDescriptor.getTripId(), tripDescriptor.getRouteId(), edges(partition).map(edgeLabel -> edgeLabel.edgeIteratorState).collect(Collectors.toList()), stops, partition.stream().mapToDouble(t -> t.edge.distance).sum(), path.get(i - 1).label.currentTime - boardTime, lineString));
partition = null;
}
}
return result;
} else {
InstructionList instructions = new InstructionList(tr);
InstructionsFromEdges instructionsFromEdges = new InstructionsFromEdges(path.get(1).edge.edgeIteratorState.getBaseNode(), graph.getGraph(), weighting, weighting.getFlagEncoder(), graph.getNodeAccess(), tr, instructions);
int prevEdgeId = -1;
for (int i = 1; i < path.size(); i++) {
EdgeIteratorState edge = path.get(i).edge.edgeIteratorState;
instructionsFromEdges.next(edge, i, prevEdgeId);
prevEdgeId = edge.getEdge();
}
instructionsFromEdges.finish();
final Instant departureTime = Instant.ofEpochMilli(path.get(0).label.currentTime);
final Instant arrivalTime = Instant.ofEpochMilli(path.get(path.size() - 1).label.currentTime);
return Collections.singletonList(new Trip.WalkLeg("Walk", Date.from(departureTime), edges(path).map(edgeLabel -> edgeLabel.edgeIteratorState).collect(Collectors.toList()), lineStringFromEdges(path), edges(path).mapToDouble(edgeLabel -> edgeLabel.distance).sum(), instructions, Date.from(arrivalTime)));
}
}
use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.
the class GraphHopperOSMTest method createSquareGraphInstance.
private GraphHopper createSquareGraphInstance(boolean withCH) {
CarFlagEncoder carEncoder = new CarFlagEncoder();
EncodingManager encodingManager = new EncodingManager(carEncoder);
Weighting weighting = new FastestWeighting(carEncoder);
GraphHopperStorage g = new GraphHopperStorage(Collections.singletonList(weighting), new RAMDirectory(), encodingManager, false, new GraphExtension.NoOpExtension()).create(20);
// 2---3---4
// / | \
// 1----8----5
// / | /
// 0----7---6
NodeAccess na = g.getNodeAccess();
na.setNode(0, 0.000, 0.000);
na.setNode(1, 0.001, 0.000);
na.setNode(2, 0.002, 0.000);
na.setNode(3, 0.002, 0.001);
na.setNode(4, 0.002, 0.002);
na.setNode(5, 0.001, 0.002);
na.setNode(6, 0.000, 0.002);
na.setNode(7, 0.000, 0.001);
na.setNode(8, 0.001, 0.001);
g.edge(0, 1, 100, true);
g.edge(1, 2, 100, true);
g.edge(2, 3, 100, true);
g.edge(3, 4, 100, true);
g.edge(4, 5, 100, true);
g.edge(5, 6, 100, true);
g.edge(6, 7, 100, true);
g.edge(7, 0, 100, true);
g.edge(1, 8, 110, true);
g.edge(3, 8, 110, true);
g.edge(5, 8, 110, true);
g.edge(7, 8, 110, true);
GraphHopper tmp = new GraphHopperOSM().setCHEnabled(withCH).setEncodingManager(encodingManager);
tmp.getCHFactoryDecorator().setWeightingsAsStrings("fastest");
tmp.setGraphHopperStorage(g);
tmp.postProcessing();
return tmp;
}
use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.
the class CustomWeightingTest method testBoolean.
@Test
public void testBoolean() {
carFE = new CarFlagEncoder();
BooleanEncodedValue specialEnc = new SimpleBooleanEncodedValue("special", true);
encodingManager = new EncodingManager.Builder().add(carFE).add(specialEnc).build();
avSpeedEnc = carFE.getAverageSpeedEnc();
graph = new GraphBuilder(encodingManager).create();
BooleanEncodedValue accessEnc = carFE.getAccessEnc();
EdgeIteratorState edge = graph.edge(0, 1).set(accessEnc, true).setReverse(accessEnc, true).set(avSpeedEnc, 15).set(specialEnc, false).setReverse(specialEnc, true).setDistance(10);
CustomModel vehicleModel = new CustomModel();
assertEquals(3.1, createWeighting(vehicleModel).calcEdgeWeight(edge, false), 0.01);
vehicleModel.addToPriority(If("special == true", MULTIPLY, 0.8));
vehicleModel.addToPriority(If("special == false", MULTIPLY, 0.4));
Weighting weighting = createWeighting(vehicleModel);
assertEquals(6.7, weighting.calcEdgeWeight(edge, false), 0.01);
assertEquals(3.7, weighting.calcEdgeWeight(edge, true), 0.01);
}
use of com.graphhopper.routing.weighting.Weighting in project graphhopper by graphhopper.
the class Measurement method measureRouting.
private void measureRouting(final GraphHopper hopper, final QuerySettings querySettings) {
final Graph g = hopper.getGraphHopperStorage();
final AtomicLong maxDistance = new AtomicLong(0);
final AtomicLong minDistance = new AtomicLong(Long.MAX_VALUE);
final AtomicLong distSum = new AtomicLong(0);
final AtomicLong airDistSum = new AtomicLong(0);
final AtomicLong altCount = new AtomicLong(0);
final AtomicInteger failedCount = new AtomicInteger(0);
final DistanceCalc distCalc = new DistanceCalcEarth();
String profileName = querySettings.edgeBased ? "profile_tc" : "profile_no_tc";
Weighting weighting = hopper.createWeighting(hopper.getProfile(profileName), new PMap());
final EdgeFilter edgeFilter = new DefaultSnapFilter(weighting, hopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileName)));
final EdgeExplorer edgeExplorer = g.createEdgeExplorer(edgeFilter);
final AtomicLong visitedNodesSum = new AtomicLong(0);
final AtomicLong maxVisitedNodes = new AtomicLong(0);
final Random rand = new Random(seed);
final NodeAccess na = g.getNodeAccess();
MiniPerfTest miniPerf = new MiniPerfTest().setIterations(querySettings.count).start((warmup, run) -> {
GHRequest req = new GHRequest(querySettings.points);
IntArrayList nodes = new IntArrayList(querySettings.points);
// we try a few times to find points that do not lie within our blocked area
for (int i = 0; i < 5; i++) {
nodes.clear();
List<GHPoint> points = new ArrayList<>();
List<String> pointHints = new ArrayList<>();
int tries = 0;
while (nodes.size() < querySettings.points) {
int node = rand.nextInt(maxNode);
if (++tries > g.getNodes())
throw new RuntimeException("Could not find accessible points");
// probe location. it could be a pedestrian area or an edge removed in the subnetwork removal process
if (GHUtility.count(edgeExplorer.setBaseNode(node)) == 0)
continue;
nodes.add(node);
points.add(new GHPoint(na.getLat(node), na.getLon(node)));
if (querySettings.withPointHints) {
// we add some point hint to make sure the name similarity filter has to do some actual work
pointHints.add("probably_not_found");
}
}
req.setPoints(points);
req.setPointHints(pointHints);
if (querySettings.blockArea == null)
break;
try {
req.getHints().putObject(BLOCK_AREA, querySettings.blockArea);
// run this method to check if creating the blocked area is possible
GraphEdgeIdFinder.createBlockArea(hopper.getGraphHopperStorage(), hopper.getLocationIndex(), req.getPoints(), req.getHints(), edgeFilter);
break;
} catch (IllegalArgumentException ex) {
if (i >= 4)
throw new RuntimeException("Give up after 5 tries. Cannot find points outside of the block_area " + querySettings.blockArea + " - too big block_area or map too small? Request:" + req);
}
}
req.setProfile(profileName);
req.getHints().putObject(CH.DISABLE, !querySettings.ch).putObject("stall_on_demand", querySettings.sod).putObject(Landmark.DISABLE, !querySettings.lm).putObject(Landmark.ACTIVE_COUNT, querySettings.activeLandmarks).putObject("instructions", querySettings.withInstructions);
if (querySettings.alternative)
req.setAlgorithm(ALT_ROUTE);
if (querySettings.pathDetails)
req.setPathDetails(Arrays.asList(Parameters.Details.AVERAGE_SPEED, Parameters.Details.EDGE_ID, Parameters.Details.STREET_NAME));
if (!querySettings.simplify)
req.getHints().putObject(Parameters.Routing.WAY_POINT_MAX_DISTANCE, 0);
GHResponse rsp;
try {
rsp = hopper.route(req);
} catch (Exception ex) {
// 'not found' can happen if import creates more than one subnetwork
throw new RuntimeException("Error while calculating route! nodes: " + nodes + ", request:" + req, ex);
}
if (rsp.hasErrors()) {
if (!warmup)
failedCount.incrementAndGet();
if (rsp.getErrors().get(0).getMessage() == null)
rsp.getErrors().get(0).printStackTrace();
else if (!toLowerCase(rsp.getErrors().get(0).getMessage()).contains("not found")) {
if (stopOnError)
throw new RuntimeException("errors should NOT happen in Measurement! " + req + " => " + rsp.getErrors());
else
logger.error("errors should NOT happen in Measurement! " + req + " => " + rsp.getErrors());
}
return 0;
}
ResponsePath responsePath = rsp.getBest();
if (!warmup) {
long visitedNodes = rsp.getHints().getLong("visited_nodes.sum", 0);
visitedNodesSum.addAndGet(visitedNodes);
if (visitedNodes > maxVisitedNodes.get()) {
maxVisitedNodes.set(visitedNodes);
}
long dist = (long) responsePath.getDistance();
distSum.addAndGet(dist);
GHPoint prev = req.getPoints().get(0);
for (GHPoint point : req.getPoints()) {
airDistSum.addAndGet((long) distCalc.calcDist(prev.getLat(), prev.getLon(), point.getLat(), point.getLon()));
prev = point;
}
if (dist > maxDistance.get())
maxDistance.set(dist);
if (dist < minDistance.get())
minDistance.set(dist);
if (querySettings.alternative)
altCount.addAndGet(rsp.getAll().size());
}
return responsePath.getPoints().size();
});
int count = querySettings.count - failedCount.get();
if (count == 0)
throw new RuntimeException("All requests failed, something must be wrong: " + failedCount.get());
// if using non-bidirectional algorithm make sure you exclude CH routing
String algoStr = (querySettings.ch && !querySettings.edgeBased) ? Algorithms.DIJKSTRA_BI : Algorithms.ASTAR_BI;
if (querySettings.ch && !querySettings.sod) {
algoStr += "_no_sod";
}
String prefix = querySettings.prefix;
put(prefix + ".guessed_algorithm", algoStr);
put(prefix + ".failed_count", failedCount.get());
put(prefix + ".distance_min", minDistance.get());
put(prefix + ".distance_mean", (float) distSum.get() / count);
put(prefix + ".air_distance_mean", (float) airDistSum.get() / count);
put(prefix + ".distance_max", maxDistance.get());
put(prefix + ".visited_nodes_mean", (float) visitedNodesSum.get() / count);
put(prefix + ".visited_nodes_max", (float) maxVisitedNodes.get());
put(prefix + ".alternative_rate", (float) altCount.get() / count);
print(prefix, miniPerf);
}
Aggregations