proj_name
stringclasses
91 values
relative_path
stringclasses
558 values
class_name
stringclasses
959 values
func_name
stringlengths
1
70
masked_class
stringlengths
69
162k
func_body
stringlengths
0
30.5k
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
getWeighting
class MapMatching { private final BaseGraph graph; private final Router router; private final LocationIndexTree locationIndex; private double measurementErrorSigma = 10.0; private double transitionProbabilityBeta = 2.0; private final DistanceCalc distanceCalc = new DistancePlaneProjection(); private QueryGraph queryGraph; private Map<String, Object> statistics = new HashMap<>(); public static MapMatching fromGraphHopper(GraphHopper graphHopper, PMap hints) { Router router = routerFromGraphHopper(graphHopper, hints); return new MapMatching(graphHopper.getBaseGraph(), (LocationIndexTree) graphHopper.getLocationIndex(), router); } public static Router routerFromGraphHopper(GraphHopper graphHopper, PMap hints) { if (hints.has("vehicle")) throw new IllegalArgumentException("MapMatching hints may no longer contain a vehicle, use the profile parameter instead, see core/#1958"); if (hints.has("weighting")) throw new IllegalArgumentException("MapMatching hints may no longer contain a weighting, use the profile parameter instead, see core/#1958"); if (graphHopper.getProfiles().isEmpty()) { throw new IllegalArgumentException("No profiles found, you need to configure at least one profile to use map matching"); } if (!hints.has("profile")) { throw new IllegalArgumentException("You need to specify a profile to perform map matching"); } String profileStr = hints.getString("profile", ""); Profile profile = graphHopper.getProfile(profileStr); if (profile == null) { List<Profile> profiles = graphHopper.getProfiles(); List<String> profileNames = new ArrayList<>(profiles.size()); for (Profile p : profiles) { profileNames.add(p.getName()); } throw new IllegalArgumentException("Could not find profile '" + profileStr + "', choose one of: " + profileNames); } boolean disableLM = hints.getBool(Parameters.Landmark.DISABLE, false); boolean disableCH = hints.getBool(Parameters.CH.DISABLE, false); // see map-matching/#177: both ch.disable and lm.disable can be used to force Dijkstra which is the better // (=faster) choice when the observations are close to each other boolean useDijkstra = disableLM || disableCH; LandmarkStorage landmarks; if (!useDijkstra && graphHopper.getLandmarks().get(profile.getName()) != null) { // using LM because u-turn prevention does not work properly with (node-based) CH landmarks = graphHopper.getLandmarks().get(profile.getName()); } else { landmarks = null; } Weighting weighting = graphHopper.createWeighting(profile, hints); BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileStr)); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, inSubnetworkEnc); int maxVisitedNodes = hints.getInt(Parameters.Routing.MAX_VISITED_NODES, Integer.MAX_VALUE); Router router = new Router() { @Override public EdgeFilter getSnapFilter() { return snapFilter; } @Override public List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges) { assert (toNodes.length == toInEdges.length); List<Path> result = new ArrayList<>(); for (int i = 0; i < toNodes.length; i++) { result.add(calcOnePath(queryGraph, fromNode, toNodes[i], fromOutEdge, toInEdges[i])); } return result; } private Path calcOnePath(QueryGraph queryGraph, int fromNode, int toNode, int fromOutEdge, int toInEdge) { Weighting queryGraphWeighting = queryGraph.wrapWeighting(weighting); if (landmarks != null) { AStarBidirection aStarBidirection = new AStarBidirection(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; int activeLM = Math.min(8, landmarks.getLandmarkCount()); LMApproximator lmApproximator = LMApproximator.forLandmarks(queryGraph, queryGraphWeighting, landmarks, activeLM); aStarBidirection.setApproximation(lmApproximator); aStarBidirection.setMaxVisitedNodes(maxVisitedNodes); return aStarBidirection.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } else { DijkstraBidirectionRef dijkstraBidirectionRef = new DijkstraBidirectionRef(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; dijkstraBidirectionRef.setMaxVisitedNodes(maxVisitedNodes); return dijkstraBidirectionRef.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } } @Override public Weighting getWeighting() {<FILL_FUNCTION_BODY>} }; return router; } public MapMatching(BaseGraph graph, LocationIndexTree locationIndex, Router router) { this.graph = graph; this.locationIndex = locationIndex; this.router = router; } /** * Beta parameter of the exponential distribution for modeling transition * probabilities. */ public void setTransitionProbabilityBeta(double transitionProbabilityBeta) { this.transitionProbabilityBeta = transitionProbabilityBeta; } /** * Standard deviation of the normal distribution [m] used for modeling the * GPS error. */ public void setMeasurementErrorSigma(double measurementErrorSigma) { this.measurementErrorSigma = measurementErrorSigma; } public MatchResult match(List<Observation> observations) { List<Observation> filteredObservations = filterObservations(observations); statistics.put("filteredObservations", filteredObservations.size()); // Snap observations to links. Generates multiple candidate snaps per observation. List<List<Snap>> snapsPerObservation = filteredObservations.stream() .map(o -> findCandidateSnaps(o.getPoint().lat, o.getPoint().lon)) .collect(Collectors.toList()); statistics.put("snapsPerObservation", snapsPerObservation.stream().mapToInt(Collection::size).toArray()); // Create the query graph, containing split edges so that all the places where an observation might have happened // are a node. This modifies the Snap objects and puts the new node numbers into them. queryGraph = QueryGraph.create(graph, snapsPerObservation.stream().flatMap(Collection::stream).collect(Collectors.toList())); // Creates candidates from the Snaps of all observations (a candidate is basically a // Snap + direction). List<ObservationWithCandidateStates> timeSteps = createTimeSteps(filteredObservations, snapsPerObservation); // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps); statistics.put("transitionDistances", seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> Math.round(s.transitionDescriptor.getDistance())).toArray()); statistics.put("visitedNodes", router.getVisitedNodes()); statistics.put("snapDistanceRanks", IntStream.range(0, seq.size()).map(i -> snapsPerObservation.get(i).indexOf(seq.get(i).state.getSnap())).toArray()); statistics.put("snapDistances", seq.stream().mapToDouble(s -> s.state.getSnap().getQueryDistance()).toArray()); statistics.put("maxSnapDistances", IntStream.range(0, seq.size()).mapToDouble(i -> snapsPerObservation.get(i).stream().mapToDouble(Snap::getQueryDistance).max().orElse(-1.0)).toArray()); List<EdgeIteratorState> path = seq.stream().filter(s1 -> s1.transitionDescriptor != null).flatMap(s1 -> s1.transitionDescriptor.calcEdges().stream()).collect(Collectors.toList()); MatchResult result = new MatchResult(prepareEdgeMatches(seq)); Weighting queryGraphWeighting = queryGraph.wrapWeighting(router.getWeighting()); result.setMergedPath(new MapMatchedPath(queryGraph, queryGraphWeighting, path)); result.setMatchMillis(seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> s.transitionDescriptor.getTime()).sum()); result.setMatchLength(seq.stream().filter(s -> s.transitionDescriptor != null).mapToDouble(s -> s.transitionDescriptor.getDistance()).sum()); result.setGPXEntriesLength(gpxLength(observations)); result.setGraph(queryGraph); result.setWeighting(queryGraphWeighting); return result; } /** * Filters observations to only those which will be used for map matching (i.e. those which * are separated by at least 2 * measurementErrorSigman */ public List<Observation> filterObservations(List<Observation> observations) { List<Observation> filtered = new ArrayList<>(); Observation prevEntry = null; double acc = 0.0; int last = observations.size() - 1; for (int i = 0; i <= last; i++) { Observation observation = observations.get(i); if (i == 0 || i == last || distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()) > 2 * measurementErrorSigma) { if (i > 0) { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); acc -= distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } // Here we store the meters of distance that we are missing because of the filtering, // so that when we add these terms to the distances between the filtered points, // the original total distance between the unfiltered points is conserved. // (See test for kind of a specification.) observation.setAccumulatedLinearDistanceToPrevious(acc); filtered.add(observation); prevEntry = observation; acc = 0.0; } else { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } } return filtered; } public List<Snap> findCandidateSnaps(final double queryLat, final double queryLon) { double rLon = (measurementErrorSigma * 360.0 / DistanceCalcEarth.DIST_EARTH.calcCircumference(queryLat)); double rLat = measurementErrorSigma / DistanceCalcEarth.METERS_PER_DEGREE; Envelope envelope = new Envelope(queryLon, queryLon, queryLat, queryLat); for (int i = 0; i < 50; i++) { envelope.expandBy(rLon, rLat); List<Snap> snaps = findCandidateSnapsInBBox(queryLat, queryLon, BBox.fromEnvelope(envelope)); if (!snaps.isEmpty()) { return snaps; } } return Collections.emptyList(); } private List<Snap> findCandidateSnapsInBBox(double queryLat, double queryLon, BBox queryShape) { EdgeFilter edgeFilter = router.getSnapFilter(); List<Snap> snaps = new ArrayList<>(); IntHashSet seenEdges = new IntHashSet(); IntHashSet seenNodes = new IntHashSet(); locationIndex.query(queryShape, edgeId -> { EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2); if (seenEdges.add(edgeId) && edgeFilter.accept(edge)) { Snap snap = new Snap(queryLat, queryLon); locationIndex.traverseEdge(queryLat, queryLon, edge, (node, normedDist, wayIndex, pos) -> { if (normedDist < snap.getQueryDistance()) { snap.setQueryDistance(normedDist); snap.setClosestNode(node); snap.setWayIndex(wayIndex); snap.setSnappedPosition(pos); } }); double dist = DIST_PLANE.calcDenormalizedDist(snap.getQueryDistance()); snap.setClosestEdge(edge); snap.setQueryDistance(dist); if (snap.isValid() && (snap.getSnappedPosition() != Snap.Position.TOWER || seenNodes.add(snap.getClosestNode()))) { snap.calcSnappedPoint(DistanceCalcEarth.DIST_EARTH); if (queryShape.contains(snap.getSnappedPoint().lat, snap.getSnappedPoint().lon)) { snaps.add(snap); } } } }); snaps.sort(Comparator.comparingDouble(Snap::getQueryDistance)); return snaps; } /** * Creates TimeSteps with candidates for the GPX entries but does not create emission or * transition probabilities. Creates directed candidates for virtual nodes and undirected * candidates for real nodes. */ private List<ObservationWithCandidateStates> createTimeSteps(List<Observation> filteredObservations, List<List<Snap>> splitsPerObservation) { if (splitsPerObservation.size() != filteredObservations.size()) { throw new IllegalArgumentException( "filteredGPXEntries and queriesPerEntry must have same size."); } final List<ObservationWithCandidateStates> timeSteps = new ArrayList<>(); for (int i = 0; i < filteredObservations.size(); i++) { Observation observation = filteredObservations.get(i); Collection<Snap> splits = splitsPerObservation.get(i); List<State> candidates = new ArrayList<>(); for (Snap split : splits) { if (queryGraph.isVirtualNode(split.getClosestNode())) { List<VirtualEdgeIteratorState> virtualEdges = new ArrayList<>(); EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(split.getClosestNode()); while (iter.next()) { if (!queryGraph.isVirtualEdge(iter.getEdge())) { throw new RuntimeException("Virtual nodes must only have virtual edges " + "to adjacent nodes."); } virtualEdges.add((VirtualEdgeIteratorState) queryGraph.getEdgeIteratorState(iter.getEdge(), iter.getAdjNode())); } if (virtualEdges.size() != 2) { throw new RuntimeException("Each virtual node must have exactly 2 " + "virtual edges (reverse virtual edges are not returned by the " + "EdgeIterator"); } // Create a directed candidate for each of the two possible directions through // the virtual node. We need to add candidates for both directions because // we don't know yet which is the correct one. This will be figured // out by the Viterbi algorithm. candidates.add(new State(observation, split, virtualEdges.get(0), virtualEdges.get(1))); candidates.add(new State(observation, split, virtualEdges.get(1), virtualEdges.get(0))); } else { // Create an undirected candidate for the real node. candidates.add(new State(observation, split)); } } timeSteps.add(new ObservationWithCandidateStates(observation, candidates)); } return timeSteps; } static class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() { return statistics; } private static class MapMatchedPath extends Path { MapMatchedPath(Graph graph, Weighting weighting, List<EdgeIteratorState> edges) { super(graph); int prevEdge = EdgeIterator.NO_EDGE; for (EdgeIteratorState edge : edges) { addDistance(edge.getDistance()); addTime(GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdge)); addEdge(edge.getEdge()); prevEdge = edge.getEdge(); } if (edges.isEmpty()) { setFound(false); } else { setFromNode(edges.get(0).getBaseNode()); setFound(true); } } } public interface Router { EdgeFilter getSnapFilter(); List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges); Weighting getWeighting(); default long getVisitedNodes() { return 0L; } } }
return weighting;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
setTransitionProbabilityBeta
class MapMatching { private final BaseGraph graph; private final Router router; private final LocationIndexTree locationIndex; private double measurementErrorSigma = 10.0; private double transitionProbabilityBeta = 2.0; private final DistanceCalc distanceCalc = new DistancePlaneProjection(); private QueryGraph queryGraph; private Map<String, Object> statistics = new HashMap<>(); public static MapMatching fromGraphHopper(GraphHopper graphHopper, PMap hints) { Router router = routerFromGraphHopper(graphHopper, hints); return new MapMatching(graphHopper.getBaseGraph(), (LocationIndexTree) graphHopper.getLocationIndex(), router); } public static Router routerFromGraphHopper(GraphHopper graphHopper, PMap hints) { if (hints.has("vehicle")) throw new IllegalArgumentException("MapMatching hints may no longer contain a vehicle, use the profile parameter instead, see core/#1958"); if (hints.has("weighting")) throw new IllegalArgumentException("MapMatching hints may no longer contain a weighting, use the profile parameter instead, see core/#1958"); if (graphHopper.getProfiles().isEmpty()) { throw new IllegalArgumentException("No profiles found, you need to configure at least one profile to use map matching"); } if (!hints.has("profile")) { throw new IllegalArgumentException("You need to specify a profile to perform map matching"); } String profileStr = hints.getString("profile", ""); Profile profile = graphHopper.getProfile(profileStr); if (profile == null) { List<Profile> profiles = graphHopper.getProfiles(); List<String> profileNames = new ArrayList<>(profiles.size()); for (Profile p : profiles) { profileNames.add(p.getName()); } throw new IllegalArgumentException("Could not find profile '" + profileStr + "', choose one of: " + profileNames); } boolean disableLM = hints.getBool(Parameters.Landmark.DISABLE, false); boolean disableCH = hints.getBool(Parameters.CH.DISABLE, false); // see map-matching/#177: both ch.disable and lm.disable can be used to force Dijkstra which is the better // (=faster) choice when the observations are close to each other boolean useDijkstra = disableLM || disableCH; LandmarkStorage landmarks; if (!useDijkstra && graphHopper.getLandmarks().get(profile.getName()) != null) { // using LM because u-turn prevention does not work properly with (node-based) CH landmarks = graphHopper.getLandmarks().get(profile.getName()); } else { landmarks = null; } Weighting weighting = graphHopper.createWeighting(profile, hints); BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileStr)); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, inSubnetworkEnc); int maxVisitedNodes = hints.getInt(Parameters.Routing.MAX_VISITED_NODES, Integer.MAX_VALUE); Router router = new Router() { @Override public EdgeFilter getSnapFilter() { return snapFilter; } @Override public List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges) { assert (toNodes.length == toInEdges.length); List<Path> result = new ArrayList<>(); for (int i = 0; i < toNodes.length; i++) { result.add(calcOnePath(queryGraph, fromNode, toNodes[i], fromOutEdge, toInEdges[i])); } return result; } private Path calcOnePath(QueryGraph queryGraph, int fromNode, int toNode, int fromOutEdge, int toInEdge) { Weighting queryGraphWeighting = queryGraph.wrapWeighting(weighting); if (landmarks != null) { AStarBidirection aStarBidirection = new AStarBidirection(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; int activeLM = Math.min(8, landmarks.getLandmarkCount()); LMApproximator lmApproximator = LMApproximator.forLandmarks(queryGraph, queryGraphWeighting, landmarks, activeLM); aStarBidirection.setApproximation(lmApproximator); aStarBidirection.setMaxVisitedNodes(maxVisitedNodes); return aStarBidirection.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } else { DijkstraBidirectionRef dijkstraBidirectionRef = new DijkstraBidirectionRef(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; dijkstraBidirectionRef.setMaxVisitedNodes(maxVisitedNodes); return dijkstraBidirectionRef.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } } @Override public Weighting getWeighting() { return weighting; } }; return router; } public MapMatching(BaseGraph graph, LocationIndexTree locationIndex, Router router) { this.graph = graph; this.locationIndex = locationIndex; this.router = router; } /** * Beta parameter of the exponential distribution for modeling transition * probabilities. */ public void setTransitionProbabilityBeta(double transitionProbabilityBeta) {<FILL_FUNCTION_BODY>} /** * Standard deviation of the normal distribution [m] used for modeling the * GPS error. */ public void setMeasurementErrorSigma(double measurementErrorSigma) { this.measurementErrorSigma = measurementErrorSigma; } public MatchResult match(List<Observation> observations) { List<Observation> filteredObservations = filterObservations(observations); statistics.put("filteredObservations", filteredObservations.size()); // Snap observations to links. Generates multiple candidate snaps per observation. List<List<Snap>> snapsPerObservation = filteredObservations.stream() .map(o -> findCandidateSnaps(o.getPoint().lat, o.getPoint().lon)) .collect(Collectors.toList()); statistics.put("snapsPerObservation", snapsPerObservation.stream().mapToInt(Collection::size).toArray()); // Create the query graph, containing split edges so that all the places where an observation might have happened // are a node. This modifies the Snap objects and puts the new node numbers into them. queryGraph = QueryGraph.create(graph, snapsPerObservation.stream().flatMap(Collection::stream).collect(Collectors.toList())); // Creates candidates from the Snaps of all observations (a candidate is basically a // Snap + direction). List<ObservationWithCandidateStates> timeSteps = createTimeSteps(filteredObservations, snapsPerObservation); // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps); statistics.put("transitionDistances", seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> Math.round(s.transitionDescriptor.getDistance())).toArray()); statistics.put("visitedNodes", router.getVisitedNodes()); statistics.put("snapDistanceRanks", IntStream.range(0, seq.size()).map(i -> snapsPerObservation.get(i).indexOf(seq.get(i).state.getSnap())).toArray()); statistics.put("snapDistances", seq.stream().mapToDouble(s -> s.state.getSnap().getQueryDistance()).toArray()); statistics.put("maxSnapDistances", IntStream.range(0, seq.size()).mapToDouble(i -> snapsPerObservation.get(i).stream().mapToDouble(Snap::getQueryDistance).max().orElse(-1.0)).toArray()); List<EdgeIteratorState> path = seq.stream().filter(s1 -> s1.transitionDescriptor != null).flatMap(s1 -> s1.transitionDescriptor.calcEdges().stream()).collect(Collectors.toList()); MatchResult result = new MatchResult(prepareEdgeMatches(seq)); Weighting queryGraphWeighting = queryGraph.wrapWeighting(router.getWeighting()); result.setMergedPath(new MapMatchedPath(queryGraph, queryGraphWeighting, path)); result.setMatchMillis(seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> s.transitionDescriptor.getTime()).sum()); result.setMatchLength(seq.stream().filter(s -> s.transitionDescriptor != null).mapToDouble(s -> s.transitionDescriptor.getDistance()).sum()); result.setGPXEntriesLength(gpxLength(observations)); result.setGraph(queryGraph); result.setWeighting(queryGraphWeighting); return result; } /** * Filters observations to only those which will be used for map matching (i.e. those which * are separated by at least 2 * measurementErrorSigman */ public List<Observation> filterObservations(List<Observation> observations) { List<Observation> filtered = new ArrayList<>(); Observation prevEntry = null; double acc = 0.0; int last = observations.size() - 1; for (int i = 0; i <= last; i++) { Observation observation = observations.get(i); if (i == 0 || i == last || distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()) > 2 * measurementErrorSigma) { if (i > 0) { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); acc -= distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } // Here we store the meters of distance that we are missing because of the filtering, // so that when we add these terms to the distances between the filtered points, // the original total distance between the unfiltered points is conserved. // (See test for kind of a specification.) observation.setAccumulatedLinearDistanceToPrevious(acc); filtered.add(observation); prevEntry = observation; acc = 0.0; } else { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } } return filtered; } public List<Snap> findCandidateSnaps(final double queryLat, final double queryLon) { double rLon = (measurementErrorSigma * 360.0 / DistanceCalcEarth.DIST_EARTH.calcCircumference(queryLat)); double rLat = measurementErrorSigma / DistanceCalcEarth.METERS_PER_DEGREE; Envelope envelope = new Envelope(queryLon, queryLon, queryLat, queryLat); for (int i = 0; i < 50; i++) { envelope.expandBy(rLon, rLat); List<Snap> snaps = findCandidateSnapsInBBox(queryLat, queryLon, BBox.fromEnvelope(envelope)); if (!snaps.isEmpty()) { return snaps; } } return Collections.emptyList(); } private List<Snap> findCandidateSnapsInBBox(double queryLat, double queryLon, BBox queryShape) { EdgeFilter edgeFilter = router.getSnapFilter(); List<Snap> snaps = new ArrayList<>(); IntHashSet seenEdges = new IntHashSet(); IntHashSet seenNodes = new IntHashSet(); locationIndex.query(queryShape, edgeId -> { EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2); if (seenEdges.add(edgeId) && edgeFilter.accept(edge)) { Snap snap = new Snap(queryLat, queryLon); locationIndex.traverseEdge(queryLat, queryLon, edge, (node, normedDist, wayIndex, pos) -> { if (normedDist < snap.getQueryDistance()) { snap.setQueryDistance(normedDist); snap.setClosestNode(node); snap.setWayIndex(wayIndex); snap.setSnappedPosition(pos); } }); double dist = DIST_PLANE.calcDenormalizedDist(snap.getQueryDistance()); snap.setClosestEdge(edge); snap.setQueryDistance(dist); if (snap.isValid() && (snap.getSnappedPosition() != Snap.Position.TOWER || seenNodes.add(snap.getClosestNode()))) { snap.calcSnappedPoint(DistanceCalcEarth.DIST_EARTH); if (queryShape.contains(snap.getSnappedPoint().lat, snap.getSnappedPoint().lon)) { snaps.add(snap); } } } }); snaps.sort(Comparator.comparingDouble(Snap::getQueryDistance)); return snaps; } /** * Creates TimeSteps with candidates for the GPX entries but does not create emission or * transition probabilities. Creates directed candidates for virtual nodes and undirected * candidates for real nodes. */ private List<ObservationWithCandidateStates> createTimeSteps(List<Observation> filteredObservations, List<List<Snap>> splitsPerObservation) { if (splitsPerObservation.size() != filteredObservations.size()) { throw new IllegalArgumentException( "filteredGPXEntries and queriesPerEntry must have same size."); } final List<ObservationWithCandidateStates> timeSteps = new ArrayList<>(); for (int i = 0; i < filteredObservations.size(); i++) { Observation observation = filteredObservations.get(i); Collection<Snap> splits = splitsPerObservation.get(i); List<State> candidates = new ArrayList<>(); for (Snap split : splits) { if (queryGraph.isVirtualNode(split.getClosestNode())) { List<VirtualEdgeIteratorState> virtualEdges = new ArrayList<>(); EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(split.getClosestNode()); while (iter.next()) { if (!queryGraph.isVirtualEdge(iter.getEdge())) { throw new RuntimeException("Virtual nodes must only have virtual edges " + "to adjacent nodes."); } virtualEdges.add((VirtualEdgeIteratorState) queryGraph.getEdgeIteratorState(iter.getEdge(), iter.getAdjNode())); } if (virtualEdges.size() != 2) { throw new RuntimeException("Each virtual node must have exactly 2 " + "virtual edges (reverse virtual edges are not returned by the " + "EdgeIterator"); } // Create a directed candidate for each of the two possible directions through // the virtual node. We need to add candidates for both directions because // we don't know yet which is the correct one. This will be figured // out by the Viterbi algorithm. candidates.add(new State(observation, split, virtualEdges.get(0), virtualEdges.get(1))); candidates.add(new State(observation, split, virtualEdges.get(1), virtualEdges.get(0))); } else { // Create an undirected candidate for the real node. candidates.add(new State(observation, split)); } } timeSteps.add(new ObservationWithCandidateStates(observation, candidates)); } return timeSteps; } static class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() { return statistics; } private static class MapMatchedPath extends Path { MapMatchedPath(Graph graph, Weighting weighting, List<EdgeIteratorState> edges) { super(graph); int prevEdge = EdgeIterator.NO_EDGE; for (EdgeIteratorState edge : edges) { addDistance(edge.getDistance()); addTime(GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdge)); addEdge(edge.getEdge()); prevEdge = edge.getEdge(); } if (edges.isEmpty()) { setFound(false); } else { setFromNode(edges.get(0).getBaseNode()); setFound(true); } } } public interface Router { EdgeFilter getSnapFilter(); List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges); Weighting getWeighting(); default long getVisitedNodes() { return 0L; } } }
this.transitionProbabilityBeta = transitionProbabilityBeta;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
setMeasurementErrorSigma
class MapMatching { private final BaseGraph graph; private final Router router; private final LocationIndexTree locationIndex; private double measurementErrorSigma = 10.0; private double transitionProbabilityBeta = 2.0; private final DistanceCalc distanceCalc = new DistancePlaneProjection(); private QueryGraph queryGraph; private Map<String, Object> statistics = new HashMap<>(); public static MapMatching fromGraphHopper(GraphHopper graphHopper, PMap hints) { Router router = routerFromGraphHopper(graphHopper, hints); return new MapMatching(graphHopper.getBaseGraph(), (LocationIndexTree) graphHopper.getLocationIndex(), router); } public static Router routerFromGraphHopper(GraphHopper graphHopper, PMap hints) { if (hints.has("vehicle")) throw new IllegalArgumentException("MapMatching hints may no longer contain a vehicle, use the profile parameter instead, see core/#1958"); if (hints.has("weighting")) throw new IllegalArgumentException("MapMatching hints may no longer contain a weighting, use the profile parameter instead, see core/#1958"); if (graphHopper.getProfiles().isEmpty()) { throw new IllegalArgumentException("No profiles found, you need to configure at least one profile to use map matching"); } if (!hints.has("profile")) { throw new IllegalArgumentException("You need to specify a profile to perform map matching"); } String profileStr = hints.getString("profile", ""); Profile profile = graphHopper.getProfile(profileStr); if (profile == null) { List<Profile> profiles = graphHopper.getProfiles(); List<String> profileNames = new ArrayList<>(profiles.size()); for (Profile p : profiles) { profileNames.add(p.getName()); } throw new IllegalArgumentException("Could not find profile '" + profileStr + "', choose one of: " + profileNames); } boolean disableLM = hints.getBool(Parameters.Landmark.DISABLE, false); boolean disableCH = hints.getBool(Parameters.CH.DISABLE, false); // see map-matching/#177: both ch.disable and lm.disable can be used to force Dijkstra which is the better // (=faster) choice when the observations are close to each other boolean useDijkstra = disableLM || disableCH; LandmarkStorage landmarks; if (!useDijkstra && graphHopper.getLandmarks().get(profile.getName()) != null) { // using LM because u-turn prevention does not work properly with (node-based) CH landmarks = graphHopper.getLandmarks().get(profile.getName()); } else { landmarks = null; } Weighting weighting = graphHopper.createWeighting(profile, hints); BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileStr)); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, inSubnetworkEnc); int maxVisitedNodes = hints.getInt(Parameters.Routing.MAX_VISITED_NODES, Integer.MAX_VALUE); Router router = new Router() { @Override public EdgeFilter getSnapFilter() { return snapFilter; } @Override public List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges) { assert (toNodes.length == toInEdges.length); List<Path> result = new ArrayList<>(); for (int i = 0; i < toNodes.length; i++) { result.add(calcOnePath(queryGraph, fromNode, toNodes[i], fromOutEdge, toInEdges[i])); } return result; } private Path calcOnePath(QueryGraph queryGraph, int fromNode, int toNode, int fromOutEdge, int toInEdge) { Weighting queryGraphWeighting = queryGraph.wrapWeighting(weighting); if (landmarks != null) { AStarBidirection aStarBidirection = new AStarBidirection(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; int activeLM = Math.min(8, landmarks.getLandmarkCount()); LMApproximator lmApproximator = LMApproximator.forLandmarks(queryGraph, queryGraphWeighting, landmarks, activeLM); aStarBidirection.setApproximation(lmApproximator); aStarBidirection.setMaxVisitedNodes(maxVisitedNodes); return aStarBidirection.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } else { DijkstraBidirectionRef dijkstraBidirectionRef = new DijkstraBidirectionRef(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; dijkstraBidirectionRef.setMaxVisitedNodes(maxVisitedNodes); return dijkstraBidirectionRef.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } } @Override public Weighting getWeighting() { return weighting; } }; return router; } public MapMatching(BaseGraph graph, LocationIndexTree locationIndex, Router router) { this.graph = graph; this.locationIndex = locationIndex; this.router = router; } /** * Beta parameter of the exponential distribution for modeling transition * probabilities. */ public void setTransitionProbabilityBeta(double transitionProbabilityBeta) { this.transitionProbabilityBeta = transitionProbabilityBeta; } /** * Standard deviation of the normal distribution [m] used for modeling the * GPS error. */ public void setMeasurementErrorSigma(double measurementErrorSigma) {<FILL_FUNCTION_BODY>} public MatchResult match(List<Observation> observations) { List<Observation> filteredObservations = filterObservations(observations); statistics.put("filteredObservations", filteredObservations.size()); // Snap observations to links. Generates multiple candidate snaps per observation. List<List<Snap>> snapsPerObservation = filteredObservations.stream() .map(o -> findCandidateSnaps(o.getPoint().lat, o.getPoint().lon)) .collect(Collectors.toList()); statistics.put("snapsPerObservation", snapsPerObservation.stream().mapToInt(Collection::size).toArray()); // Create the query graph, containing split edges so that all the places where an observation might have happened // are a node. This modifies the Snap objects and puts the new node numbers into them. queryGraph = QueryGraph.create(graph, snapsPerObservation.stream().flatMap(Collection::stream).collect(Collectors.toList())); // Creates candidates from the Snaps of all observations (a candidate is basically a // Snap + direction). List<ObservationWithCandidateStates> timeSteps = createTimeSteps(filteredObservations, snapsPerObservation); // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps); statistics.put("transitionDistances", seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> Math.round(s.transitionDescriptor.getDistance())).toArray()); statistics.put("visitedNodes", router.getVisitedNodes()); statistics.put("snapDistanceRanks", IntStream.range(0, seq.size()).map(i -> snapsPerObservation.get(i).indexOf(seq.get(i).state.getSnap())).toArray()); statistics.put("snapDistances", seq.stream().mapToDouble(s -> s.state.getSnap().getQueryDistance()).toArray()); statistics.put("maxSnapDistances", IntStream.range(0, seq.size()).mapToDouble(i -> snapsPerObservation.get(i).stream().mapToDouble(Snap::getQueryDistance).max().orElse(-1.0)).toArray()); List<EdgeIteratorState> path = seq.stream().filter(s1 -> s1.transitionDescriptor != null).flatMap(s1 -> s1.transitionDescriptor.calcEdges().stream()).collect(Collectors.toList()); MatchResult result = new MatchResult(prepareEdgeMatches(seq)); Weighting queryGraphWeighting = queryGraph.wrapWeighting(router.getWeighting()); result.setMergedPath(new MapMatchedPath(queryGraph, queryGraphWeighting, path)); result.setMatchMillis(seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> s.transitionDescriptor.getTime()).sum()); result.setMatchLength(seq.stream().filter(s -> s.transitionDescriptor != null).mapToDouble(s -> s.transitionDescriptor.getDistance()).sum()); result.setGPXEntriesLength(gpxLength(observations)); result.setGraph(queryGraph); result.setWeighting(queryGraphWeighting); return result; } /** * Filters observations to only those which will be used for map matching (i.e. those which * are separated by at least 2 * measurementErrorSigman */ public List<Observation> filterObservations(List<Observation> observations) { List<Observation> filtered = new ArrayList<>(); Observation prevEntry = null; double acc = 0.0; int last = observations.size() - 1; for (int i = 0; i <= last; i++) { Observation observation = observations.get(i); if (i == 0 || i == last || distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()) > 2 * measurementErrorSigma) { if (i > 0) { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); acc -= distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } // Here we store the meters of distance that we are missing because of the filtering, // so that when we add these terms to the distances between the filtered points, // the original total distance between the unfiltered points is conserved. // (See test for kind of a specification.) observation.setAccumulatedLinearDistanceToPrevious(acc); filtered.add(observation); prevEntry = observation; acc = 0.0; } else { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } } return filtered; } public List<Snap> findCandidateSnaps(final double queryLat, final double queryLon) { double rLon = (measurementErrorSigma * 360.0 / DistanceCalcEarth.DIST_EARTH.calcCircumference(queryLat)); double rLat = measurementErrorSigma / DistanceCalcEarth.METERS_PER_DEGREE; Envelope envelope = new Envelope(queryLon, queryLon, queryLat, queryLat); for (int i = 0; i < 50; i++) { envelope.expandBy(rLon, rLat); List<Snap> snaps = findCandidateSnapsInBBox(queryLat, queryLon, BBox.fromEnvelope(envelope)); if (!snaps.isEmpty()) { return snaps; } } return Collections.emptyList(); } private List<Snap> findCandidateSnapsInBBox(double queryLat, double queryLon, BBox queryShape) { EdgeFilter edgeFilter = router.getSnapFilter(); List<Snap> snaps = new ArrayList<>(); IntHashSet seenEdges = new IntHashSet(); IntHashSet seenNodes = new IntHashSet(); locationIndex.query(queryShape, edgeId -> { EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2); if (seenEdges.add(edgeId) && edgeFilter.accept(edge)) { Snap snap = new Snap(queryLat, queryLon); locationIndex.traverseEdge(queryLat, queryLon, edge, (node, normedDist, wayIndex, pos) -> { if (normedDist < snap.getQueryDistance()) { snap.setQueryDistance(normedDist); snap.setClosestNode(node); snap.setWayIndex(wayIndex); snap.setSnappedPosition(pos); } }); double dist = DIST_PLANE.calcDenormalizedDist(snap.getQueryDistance()); snap.setClosestEdge(edge); snap.setQueryDistance(dist); if (snap.isValid() && (snap.getSnappedPosition() != Snap.Position.TOWER || seenNodes.add(snap.getClosestNode()))) { snap.calcSnappedPoint(DistanceCalcEarth.DIST_EARTH); if (queryShape.contains(snap.getSnappedPoint().lat, snap.getSnappedPoint().lon)) { snaps.add(snap); } } } }); snaps.sort(Comparator.comparingDouble(Snap::getQueryDistance)); return snaps; } /** * Creates TimeSteps with candidates for the GPX entries but does not create emission or * transition probabilities. Creates directed candidates for virtual nodes and undirected * candidates for real nodes. */ private List<ObservationWithCandidateStates> createTimeSteps(List<Observation> filteredObservations, List<List<Snap>> splitsPerObservation) { if (splitsPerObservation.size() != filteredObservations.size()) { throw new IllegalArgumentException( "filteredGPXEntries and queriesPerEntry must have same size."); } final List<ObservationWithCandidateStates> timeSteps = new ArrayList<>(); for (int i = 0; i < filteredObservations.size(); i++) { Observation observation = filteredObservations.get(i); Collection<Snap> splits = splitsPerObservation.get(i); List<State> candidates = new ArrayList<>(); for (Snap split : splits) { if (queryGraph.isVirtualNode(split.getClosestNode())) { List<VirtualEdgeIteratorState> virtualEdges = new ArrayList<>(); EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(split.getClosestNode()); while (iter.next()) { if (!queryGraph.isVirtualEdge(iter.getEdge())) { throw new RuntimeException("Virtual nodes must only have virtual edges " + "to adjacent nodes."); } virtualEdges.add((VirtualEdgeIteratorState) queryGraph.getEdgeIteratorState(iter.getEdge(), iter.getAdjNode())); } if (virtualEdges.size() != 2) { throw new RuntimeException("Each virtual node must have exactly 2 " + "virtual edges (reverse virtual edges are not returned by the " + "EdgeIterator"); } // Create a directed candidate for each of the two possible directions through // the virtual node. We need to add candidates for both directions because // we don't know yet which is the correct one. This will be figured // out by the Viterbi algorithm. candidates.add(new State(observation, split, virtualEdges.get(0), virtualEdges.get(1))); candidates.add(new State(observation, split, virtualEdges.get(1), virtualEdges.get(0))); } else { // Create an undirected candidate for the real node. candidates.add(new State(observation, split)); } } timeSteps.add(new ObservationWithCandidateStates(observation, candidates)); } return timeSteps; } static class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() { return statistics; } private static class MapMatchedPath extends Path { MapMatchedPath(Graph graph, Weighting weighting, List<EdgeIteratorState> edges) { super(graph); int prevEdge = EdgeIterator.NO_EDGE; for (EdgeIteratorState edge : edges) { addDistance(edge.getDistance()); addTime(GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdge)); addEdge(edge.getEdge()); prevEdge = edge.getEdge(); } if (edges.isEmpty()) { setFound(false); } else { setFromNode(edges.get(0).getBaseNode()); setFound(true); } } } public interface Router { EdgeFilter getSnapFilter(); List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges); Weighting getWeighting(); default long getVisitedNodes() { return 0L; } } }
this.measurementErrorSigma = measurementErrorSigma;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
match
class MapMatching { private final BaseGraph graph; private final Router router; private final LocationIndexTree locationIndex; private double measurementErrorSigma = 10.0; private double transitionProbabilityBeta = 2.0; private final DistanceCalc distanceCalc = new DistancePlaneProjection(); private QueryGraph queryGraph; private Map<String, Object> statistics = new HashMap<>(); public static MapMatching fromGraphHopper(GraphHopper graphHopper, PMap hints) { Router router = routerFromGraphHopper(graphHopper, hints); return new MapMatching(graphHopper.getBaseGraph(), (LocationIndexTree) graphHopper.getLocationIndex(), router); } public static Router routerFromGraphHopper(GraphHopper graphHopper, PMap hints) { if (hints.has("vehicle")) throw new IllegalArgumentException("MapMatching hints may no longer contain a vehicle, use the profile parameter instead, see core/#1958"); if (hints.has("weighting")) throw new IllegalArgumentException("MapMatching hints may no longer contain a weighting, use the profile parameter instead, see core/#1958"); if (graphHopper.getProfiles().isEmpty()) { throw new IllegalArgumentException("No profiles found, you need to configure at least one profile to use map matching"); } if (!hints.has("profile")) { throw new IllegalArgumentException("You need to specify a profile to perform map matching"); } String profileStr = hints.getString("profile", ""); Profile profile = graphHopper.getProfile(profileStr); if (profile == null) { List<Profile> profiles = graphHopper.getProfiles(); List<String> profileNames = new ArrayList<>(profiles.size()); for (Profile p : profiles) { profileNames.add(p.getName()); } throw new IllegalArgumentException("Could not find profile '" + profileStr + "', choose one of: " + profileNames); } boolean disableLM = hints.getBool(Parameters.Landmark.DISABLE, false); boolean disableCH = hints.getBool(Parameters.CH.DISABLE, false); // see map-matching/#177: both ch.disable and lm.disable can be used to force Dijkstra which is the better // (=faster) choice when the observations are close to each other boolean useDijkstra = disableLM || disableCH; LandmarkStorage landmarks; if (!useDijkstra && graphHopper.getLandmarks().get(profile.getName()) != null) { // using LM because u-turn prevention does not work properly with (node-based) CH landmarks = graphHopper.getLandmarks().get(profile.getName()); } else { landmarks = null; } Weighting weighting = graphHopper.createWeighting(profile, hints); BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileStr)); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, inSubnetworkEnc); int maxVisitedNodes = hints.getInt(Parameters.Routing.MAX_VISITED_NODES, Integer.MAX_VALUE); Router router = new Router() { @Override public EdgeFilter getSnapFilter() { return snapFilter; } @Override public List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges) { assert (toNodes.length == toInEdges.length); List<Path> result = new ArrayList<>(); for (int i = 0; i < toNodes.length; i++) { result.add(calcOnePath(queryGraph, fromNode, toNodes[i], fromOutEdge, toInEdges[i])); } return result; } private Path calcOnePath(QueryGraph queryGraph, int fromNode, int toNode, int fromOutEdge, int toInEdge) { Weighting queryGraphWeighting = queryGraph.wrapWeighting(weighting); if (landmarks != null) { AStarBidirection aStarBidirection = new AStarBidirection(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; int activeLM = Math.min(8, landmarks.getLandmarkCount()); LMApproximator lmApproximator = LMApproximator.forLandmarks(queryGraph, queryGraphWeighting, landmarks, activeLM); aStarBidirection.setApproximation(lmApproximator); aStarBidirection.setMaxVisitedNodes(maxVisitedNodes); return aStarBidirection.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } else { DijkstraBidirectionRef dijkstraBidirectionRef = new DijkstraBidirectionRef(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; dijkstraBidirectionRef.setMaxVisitedNodes(maxVisitedNodes); return dijkstraBidirectionRef.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } } @Override public Weighting getWeighting() { return weighting; } }; return router; } public MapMatching(BaseGraph graph, LocationIndexTree locationIndex, Router router) { this.graph = graph; this.locationIndex = locationIndex; this.router = router; } /** * Beta parameter of the exponential distribution for modeling transition * probabilities. */ public void setTransitionProbabilityBeta(double transitionProbabilityBeta) { this.transitionProbabilityBeta = transitionProbabilityBeta; } /** * Standard deviation of the normal distribution [m] used for modeling the * GPS error. */ public void setMeasurementErrorSigma(double measurementErrorSigma) { this.measurementErrorSigma = measurementErrorSigma; } public MatchResult match(List<Observation> observations) {<FILL_FUNCTION_BODY>} /** * Filters observations to only those which will be used for map matching (i.e. those which * are separated by at least 2 * measurementErrorSigman */ public List<Observation> filterObservations(List<Observation> observations) { List<Observation> filtered = new ArrayList<>(); Observation prevEntry = null; double acc = 0.0; int last = observations.size() - 1; for (int i = 0; i <= last; i++) { Observation observation = observations.get(i); if (i == 0 || i == last || distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()) > 2 * measurementErrorSigma) { if (i > 0) { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); acc -= distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } // Here we store the meters of distance that we are missing because of the filtering, // so that when we add these terms to the distances between the filtered points, // the original total distance between the unfiltered points is conserved. // (See test for kind of a specification.) observation.setAccumulatedLinearDistanceToPrevious(acc); filtered.add(observation); prevEntry = observation; acc = 0.0; } else { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } } return filtered; } public List<Snap> findCandidateSnaps(final double queryLat, final double queryLon) { double rLon = (measurementErrorSigma * 360.0 / DistanceCalcEarth.DIST_EARTH.calcCircumference(queryLat)); double rLat = measurementErrorSigma / DistanceCalcEarth.METERS_PER_DEGREE; Envelope envelope = new Envelope(queryLon, queryLon, queryLat, queryLat); for (int i = 0; i < 50; i++) { envelope.expandBy(rLon, rLat); List<Snap> snaps = findCandidateSnapsInBBox(queryLat, queryLon, BBox.fromEnvelope(envelope)); if (!snaps.isEmpty()) { return snaps; } } return Collections.emptyList(); } private List<Snap> findCandidateSnapsInBBox(double queryLat, double queryLon, BBox queryShape) { EdgeFilter edgeFilter = router.getSnapFilter(); List<Snap> snaps = new ArrayList<>(); IntHashSet seenEdges = new IntHashSet(); IntHashSet seenNodes = new IntHashSet(); locationIndex.query(queryShape, edgeId -> { EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2); if (seenEdges.add(edgeId) && edgeFilter.accept(edge)) { Snap snap = new Snap(queryLat, queryLon); locationIndex.traverseEdge(queryLat, queryLon, edge, (node, normedDist, wayIndex, pos) -> { if (normedDist < snap.getQueryDistance()) { snap.setQueryDistance(normedDist); snap.setClosestNode(node); snap.setWayIndex(wayIndex); snap.setSnappedPosition(pos); } }); double dist = DIST_PLANE.calcDenormalizedDist(snap.getQueryDistance()); snap.setClosestEdge(edge); snap.setQueryDistance(dist); if (snap.isValid() && (snap.getSnappedPosition() != Snap.Position.TOWER || seenNodes.add(snap.getClosestNode()))) { snap.calcSnappedPoint(DistanceCalcEarth.DIST_EARTH); if (queryShape.contains(snap.getSnappedPoint().lat, snap.getSnappedPoint().lon)) { snaps.add(snap); } } } }); snaps.sort(Comparator.comparingDouble(Snap::getQueryDistance)); return snaps; } /** * Creates TimeSteps with candidates for the GPX entries but does not create emission or * transition probabilities. Creates directed candidates for virtual nodes and undirected * candidates for real nodes. */ private List<ObservationWithCandidateStates> createTimeSteps(List<Observation> filteredObservations, List<List<Snap>> splitsPerObservation) { if (splitsPerObservation.size() != filteredObservations.size()) { throw new IllegalArgumentException( "filteredGPXEntries and queriesPerEntry must have same size."); } final List<ObservationWithCandidateStates> timeSteps = new ArrayList<>(); for (int i = 0; i < filteredObservations.size(); i++) { Observation observation = filteredObservations.get(i); Collection<Snap> splits = splitsPerObservation.get(i); List<State> candidates = new ArrayList<>(); for (Snap split : splits) { if (queryGraph.isVirtualNode(split.getClosestNode())) { List<VirtualEdgeIteratorState> virtualEdges = new ArrayList<>(); EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(split.getClosestNode()); while (iter.next()) { if (!queryGraph.isVirtualEdge(iter.getEdge())) { throw new RuntimeException("Virtual nodes must only have virtual edges " + "to adjacent nodes."); } virtualEdges.add((VirtualEdgeIteratorState) queryGraph.getEdgeIteratorState(iter.getEdge(), iter.getAdjNode())); } if (virtualEdges.size() != 2) { throw new RuntimeException("Each virtual node must have exactly 2 " + "virtual edges (reverse virtual edges are not returned by the " + "EdgeIterator"); } // Create a directed candidate for each of the two possible directions through // the virtual node. We need to add candidates for both directions because // we don't know yet which is the correct one. This will be figured // out by the Viterbi algorithm. candidates.add(new State(observation, split, virtualEdges.get(0), virtualEdges.get(1))); candidates.add(new State(observation, split, virtualEdges.get(1), virtualEdges.get(0))); } else { // Create an undirected candidate for the real node. candidates.add(new State(observation, split)); } } timeSteps.add(new ObservationWithCandidateStates(observation, candidates)); } return timeSteps; } static class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() { return statistics; } private static class MapMatchedPath extends Path { MapMatchedPath(Graph graph, Weighting weighting, List<EdgeIteratorState> edges) { super(graph); int prevEdge = EdgeIterator.NO_EDGE; for (EdgeIteratorState edge : edges) { addDistance(edge.getDistance()); addTime(GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdge)); addEdge(edge.getEdge()); prevEdge = edge.getEdge(); } if (edges.isEmpty()) { setFound(false); } else { setFromNode(edges.get(0).getBaseNode()); setFound(true); } } } public interface Router { EdgeFilter getSnapFilter(); List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges); Weighting getWeighting(); default long getVisitedNodes() { return 0L; } } }
List<Observation> filteredObservations = filterObservations(observations); statistics.put("filteredObservations", filteredObservations.size()); // Snap observations to links. Generates multiple candidate snaps per observation. List<List<Snap>> snapsPerObservation = filteredObservations.stream() .map(o -> findCandidateSnaps(o.getPoint().lat, o.getPoint().lon)) .collect(Collectors.toList()); statistics.put("snapsPerObservation", snapsPerObservation.stream().mapToInt(Collection::size).toArray()); // Create the query graph, containing split edges so that all the places where an observation might have happened // are a node. This modifies the Snap objects and puts the new node numbers into them. queryGraph = QueryGraph.create(graph, snapsPerObservation.stream().flatMap(Collection::stream).collect(Collectors.toList())); // Creates candidates from the Snaps of all observations (a candidate is basically a // Snap + direction). List<ObservationWithCandidateStates> timeSteps = createTimeSteps(filteredObservations, snapsPerObservation); // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps); statistics.put("transitionDistances", seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> Math.round(s.transitionDescriptor.getDistance())).toArray()); statistics.put("visitedNodes", router.getVisitedNodes()); statistics.put("snapDistanceRanks", IntStream.range(0, seq.size()).map(i -> snapsPerObservation.get(i).indexOf(seq.get(i).state.getSnap())).toArray()); statistics.put("snapDistances", seq.stream().mapToDouble(s -> s.state.getSnap().getQueryDistance()).toArray()); statistics.put("maxSnapDistances", IntStream.range(0, seq.size()).mapToDouble(i -> snapsPerObservation.get(i).stream().mapToDouble(Snap::getQueryDistance).max().orElse(-1.0)).toArray()); List<EdgeIteratorState> path = seq.stream().filter(s1 -> s1.transitionDescriptor != null).flatMap(s1 -> s1.transitionDescriptor.calcEdges().stream()).collect(Collectors.toList()); MatchResult result = new MatchResult(prepareEdgeMatches(seq)); Weighting queryGraphWeighting = queryGraph.wrapWeighting(router.getWeighting()); result.setMergedPath(new MapMatchedPath(queryGraph, queryGraphWeighting, path)); result.setMatchMillis(seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> s.transitionDescriptor.getTime()).sum()); result.setMatchLength(seq.stream().filter(s -> s.transitionDescriptor != null).mapToDouble(s -> s.transitionDescriptor.getDistance()).sum()); result.setGPXEntriesLength(gpxLength(observations)); result.setGraph(queryGraph); result.setWeighting(queryGraphWeighting); return result;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
filterObservations
class MapMatching { private final BaseGraph graph; private final Router router; private final LocationIndexTree locationIndex; private double measurementErrorSigma = 10.0; private double transitionProbabilityBeta = 2.0; private final DistanceCalc distanceCalc = new DistancePlaneProjection(); private QueryGraph queryGraph; private Map<String, Object> statistics = new HashMap<>(); public static MapMatching fromGraphHopper(GraphHopper graphHopper, PMap hints) { Router router = routerFromGraphHopper(graphHopper, hints); return new MapMatching(graphHopper.getBaseGraph(), (LocationIndexTree) graphHopper.getLocationIndex(), router); } public static Router routerFromGraphHopper(GraphHopper graphHopper, PMap hints) { if (hints.has("vehicle")) throw new IllegalArgumentException("MapMatching hints may no longer contain a vehicle, use the profile parameter instead, see core/#1958"); if (hints.has("weighting")) throw new IllegalArgumentException("MapMatching hints may no longer contain a weighting, use the profile parameter instead, see core/#1958"); if (graphHopper.getProfiles().isEmpty()) { throw new IllegalArgumentException("No profiles found, you need to configure at least one profile to use map matching"); } if (!hints.has("profile")) { throw new IllegalArgumentException("You need to specify a profile to perform map matching"); } String profileStr = hints.getString("profile", ""); Profile profile = graphHopper.getProfile(profileStr); if (profile == null) { List<Profile> profiles = graphHopper.getProfiles(); List<String> profileNames = new ArrayList<>(profiles.size()); for (Profile p : profiles) { profileNames.add(p.getName()); } throw new IllegalArgumentException("Could not find profile '" + profileStr + "', choose one of: " + profileNames); } boolean disableLM = hints.getBool(Parameters.Landmark.DISABLE, false); boolean disableCH = hints.getBool(Parameters.CH.DISABLE, false); // see map-matching/#177: both ch.disable and lm.disable can be used to force Dijkstra which is the better // (=faster) choice when the observations are close to each other boolean useDijkstra = disableLM || disableCH; LandmarkStorage landmarks; if (!useDijkstra && graphHopper.getLandmarks().get(profile.getName()) != null) { // using LM because u-turn prevention does not work properly with (node-based) CH landmarks = graphHopper.getLandmarks().get(profile.getName()); } else { landmarks = null; } Weighting weighting = graphHopper.createWeighting(profile, hints); BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileStr)); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, inSubnetworkEnc); int maxVisitedNodes = hints.getInt(Parameters.Routing.MAX_VISITED_NODES, Integer.MAX_VALUE); Router router = new Router() { @Override public EdgeFilter getSnapFilter() { return snapFilter; } @Override public List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges) { assert (toNodes.length == toInEdges.length); List<Path> result = new ArrayList<>(); for (int i = 0; i < toNodes.length; i++) { result.add(calcOnePath(queryGraph, fromNode, toNodes[i], fromOutEdge, toInEdges[i])); } return result; } private Path calcOnePath(QueryGraph queryGraph, int fromNode, int toNode, int fromOutEdge, int toInEdge) { Weighting queryGraphWeighting = queryGraph.wrapWeighting(weighting); if (landmarks != null) { AStarBidirection aStarBidirection = new AStarBidirection(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; int activeLM = Math.min(8, landmarks.getLandmarkCount()); LMApproximator lmApproximator = LMApproximator.forLandmarks(queryGraph, queryGraphWeighting, landmarks, activeLM); aStarBidirection.setApproximation(lmApproximator); aStarBidirection.setMaxVisitedNodes(maxVisitedNodes); return aStarBidirection.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } else { DijkstraBidirectionRef dijkstraBidirectionRef = new DijkstraBidirectionRef(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; dijkstraBidirectionRef.setMaxVisitedNodes(maxVisitedNodes); return dijkstraBidirectionRef.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } } @Override public Weighting getWeighting() { return weighting; } }; return router; } public MapMatching(BaseGraph graph, LocationIndexTree locationIndex, Router router) { this.graph = graph; this.locationIndex = locationIndex; this.router = router; } /** * Beta parameter of the exponential distribution for modeling transition * probabilities. */ public void setTransitionProbabilityBeta(double transitionProbabilityBeta) { this.transitionProbabilityBeta = transitionProbabilityBeta; } /** * Standard deviation of the normal distribution [m] used for modeling the * GPS error. */ public void setMeasurementErrorSigma(double measurementErrorSigma) { this.measurementErrorSigma = measurementErrorSigma; } public MatchResult match(List<Observation> observations) { List<Observation> filteredObservations = filterObservations(observations); statistics.put("filteredObservations", filteredObservations.size()); // Snap observations to links. Generates multiple candidate snaps per observation. List<List<Snap>> snapsPerObservation = filteredObservations.stream() .map(o -> findCandidateSnaps(o.getPoint().lat, o.getPoint().lon)) .collect(Collectors.toList()); statistics.put("snapsPerObservation", snapsPerObservation.stream().mapToInt(Collection::size).toArray()); // Create the query graph, containing split edges so that all the places where an observation might have happened // are a node. This modifies the Snap objects and puts the new node numbers into them. queryGraph = QueryGraph.create(graph, snapsPerObservation.stream().flatMap(Collection::stream).collect(Collectors.toList())); // Creates candidates from the Snaps of all observations (a candidate is basically a // Snap + direction). List<ObservationWithCandidateStates> timeSteps = createTimeSteps(filteredObservations, snapsPerObservation); // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps); statistics.put("transitionDistances", seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> Math.round(s.transitionDescriptor.getDistance())).toArray()); statistics.put("visitedNodes", router.getVisitedNodes()); statistics.put("snapDistanceRanks", IntStream.range(0, seq.size()).map(i -> snapsPerObservation.get(i).indexOf(seq.get(i).state.getSnap())).toArray()); statistics.put("snapDistances", seq.stream().mapToDouble(s -> s.state.getSnap().getQueryDistance()).toArray()); statistics.put("maxSnapDistances", IntStream.range(0, seq.size()).mapToDouble(i -> snapsPerObservation.get(i).stream().mapToDouble(Snap::getQueryDistance).max().orElse(-1.0)).toArray()); List<EdgeIteratorState> path = seq.stream().filter(s1 -> s1.transitionDescriptor != null).flatMap(s1 -> s1.transitionDescriptor.calcEdges().stream()).collect(Collectors.toList()); MatchResult result = new MatchResult(prepareEdgeMatches(seq)); Weighting queryGraphWeighting = queryGraph.wrapWeighting(router.getWeighting()); result.setMergedPath(new MapMatchedPath(queryGraph, queryGraphWeighting, path)); result.setMatchMillis(seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> s.transitionDescriptor.getTime()).sum()); result.setMatchLength(seq.stream().filter(s -> s.transitionDescriptor != null).mapToDouble(s -> s.transitionDescriptor.getDistance()).sum()); result.setGPXEntriesLength(gpxLength(observations)); result.setGraph(queryGraph); result.setWeighting(queryGraphWeighting); return result; } /** * Filters observations to only those which will be used for map matching (i.e. those which * are separated by at least 2 * measurementErrorSigman */ public List<Observation> filterObservations(List<Observation> observations) {<FILL_FUNCTION_BODY>} public List<Snap> findCandidateSnaps(final double queryLat, final double queryLon) { double rLon = (measurementErrorSigma * 360.0 / DistanceCalcEarth.DIST_EARTH.calcCircumference(queryLat)); double rLat = measurementErrorSigma / DistanceCalcEarth.METERS_PER_DEGREE; Envelope envelope = new Envelope(queryLon, queryLon, queryLat, queryLat); for (int i = 0; i < 50; i++) { envelope.expandBy(rLon, rLat); List<Snap> snaps = findCandidateSnapsInBBox(queryLat, queryLon, BBox.fromEnvelope(envelope)); if (!snaps.isEmpty()) { return snaps; } } return Collections.emptyList(); } private List<Snap> findCandidateSnapsInBBox(double queryLat, double queryLon, BBox queryShape) { EdgeFilter edgeFilter = router.getSnapFilter(); List<Snap> snaps = new ArrayList<>(); IntHashSet seenEdges = new IntHashSet(); IntHashSet seenNodes = new IntHashSet(); locationIndex.query(queryShape, edgeId -> { EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2); if (seenEdges.add(edgeId) && edgeFilter.accept(edge)) { Snap snap = new Snap(queryLat, queryLon); locationIndex.traverseEdge(queryLat, queryLon, edge, (node, normedDist, wayIndex, pos) -> { if (normedDist < snap.getQueryDistance()) { snap.setQueryDistance(normedDist); snap.setClosestNode(node); snap.setWayIndex(wayIndex); snap.setSnappedPosition(pos); } }); double dist = DIST_PLANE.calcDenormalizedDist(snap.getQueryDistance()); snap.setClosestEdge(edge); snap.setQueryDistance(dist); if (snap.isValid() && (snap.getSnappedPosition() != Snap.Position.TOWER || seenNodes.add(snap.getClosestNode()))) { snap.calcSnappedPoint(DistanceCalcEarth.DIST_EARTH); if (queryShape.contains(snap.getSnappedPoint().lat, snap.getSnappedPoint().lon)) { snaps.add(snap); } } } }); snaps.sort(Comparator.comparingDouble(Snap::getQueryDistance)); return snaps; } /** * Creates TimeSteps with candidates for the GPX entries but does not create emission or * transition probabilities. Creates directed candidates for virtual nodes and undirected * candidates for real nodes. */ private List<ObservationWithCandidateStates> createTimeSteps(List<Observation> filteredObservations, List<List<Snap>> splitsPerObservation) { if (splitsPerObservation.size() != filteredObservations.size()) { throw new IllegalArgumentException( "filteredGPXEntries and queriesPerEntry must have same size."); } final List<ObservationWithCandidateStates> timeSteps = new ArrayList<>(); for (int i = 0; i < filteredObservations.size(); i++) { Observation observation = filteredObservations.get(i); Collection<Snap> splits = splitsPerObservation.get(i); List<State> candidates = new ArrayList<>(); for (Snap split : splits) { if (queryGraph.isVirtualNode(split.getClosestNode())) { List<VirtualEdgeIteratorState> virtualEdges = new ArrayList<>(); EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(split.getClosestNode()); while (iter.next()) { if (!queryGraph.isVirtualEdge(iter.getEdge())) { throw new RuntimeException("Virtual nodes must only have virtual edges " + "to adjacent nodes."); } virtualEdges.add((VirtualEdgeIteratorState) queryGraph.getEdgeIteratorState(iter.getEdge(), iter.getAdjNode())); } if (virtualEdges.size() != 2) { throw new RuntimeException("Each virtual node must have exactly 2 " + "virtual edges (reverse virtual edges are not returned by the " + "EdgeIterator"); } // Create a directed candidate for each of the two possible directions through // the virtual node. We need to add candidates for both directions because // we don't know yet which is the correct one. This will be figured // out by the Viterbi algorithm. candidates.add(new State(observation, split, virtualEdges.get(0), virtualEdges.get(1))); candidates.add(new State(observation, split, virtualEdges.get(1), virtualEdges.get(0))); } else { // Create an undirected candidate for the real node. candidates.add(new State(observation, split)); } } timeSteps.add(new ObservationWithCandidateStates(observation, candidates)); } return timeSteps; } static class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() { return statistics; } private static class MapMatchedPath extends Path { MapMatchedPath(Graph graph, Weighting weighting, List<EdgeIteratorState> edges) { super(graph); int prevEdge = EdgeIterator.NO_EDGE; for (EdgeIteratorState edge : edges) { addDistance(edge.getDistance()); addTime(GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdge)); addEdge(edge.getEdge()); prevEdge = edge.getEdge(); } if (edges.isEmpty()) { setFound(false); } else { setFromNode(edges.get(0).getBaseNode()); setFound(true); } } } public interface Router { EdgeFilter getSnapFilter(); List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges); Weighting getWeighting(); default long getVisitedNodes() { return 0L; } } }
List<Observation> filtered = new ArrayList<>(); Observation prevEntry = null; double acc = 0.0; int last = observations.size() - 1; for (int i = 0; i <= last; i++) { Observation observation = observations.get(i); if (i == 0 || i == last || distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()) > 2 * measurementErrorSigma) { if (i > 0) { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); acc -= distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } // Here we store the meters of distance that we are missing because of the filtering, // so that when we add these terms to the distances between the filtered points, // the original total distance between the unfiltered points is conserved. // (See test for kind of a specification.) observation.setAccumulatedLinearDistanceToPrevious(acc); filtered.add(observation); prevEntry = observation; acc = 0.0; } else { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } } return filtered;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
findCandidateSnaps
class MapMatching { private final BaseGraph graph; private final Router router; private final LocationIndexTree locationIndex; private double measurementErrorSigma = 10.0; private double transitionProbabilityBeta = 2.0; private final DistanceCalc distanceCalc = new DistancePlaneProjection(); private QueryGraph queryGraph; private Map<String, Object> statistics = new HashMap<>(); public static MapMatching fromGraphHopper(GraphHopper graphHopper, PMap hints) { Router router = routerFromGraphHopper(graphHopper, hints); return new MapMatching(graphHopper.getBaseGraph(), (LocationIndexTree) graphHopper.getLocationIndex(), router); } public static Router routerFromGraphHopper(GraphHopper graphHopper, PMap hints) { if (hints.has("vehicle")) throw new IllegalArgumentException("MapMatching hints may no longer contain a vehicle, use the profile parameter instead, see core/#1958"); if (hints.has("weighting")) throw new IllegalArgumentException("MapMatching hints may no longer contain a weighting, use the profile parameter instead, see core/#1958"); if (graphHopper.getProfiles().isEmpty()) { throw new IllegalArgumentException("No profiles found, you need to configure at least one profile to use map matching"); } if (!hints.has("profile")) { throw new IllegalArgumentException("You need to specify a profile to perform map matching"); } String profileStr = hints.getString("profile", ""); Profile profile = graphHopper.getProfile(profileStr); if (profile == null) { List<Profile> profiles = graphHopper.getProfiles(); List<String> profileNames = new ArrayList<>(profiles.size()); for (Profile p : profiles) { profileNames.add(p.getName()); } throw new IllegalArgumentException("Could not find profile '" + profileStr + "', choose one of: " + profileNames); } boolean disableLM = hints.getBool(Parameters.Landmark.DISABLE, false); boolean disableCH = hints.getBool(Parameters.CH.DISABLE, false); // see map-matching/#177: both ch.disable and lm.disable can be used to force Dijkstra which is the better // (=faster) choice when the observations are close to each other boolean useDijkstra = disableLM || disableCH; LandmarkStorage landmarks; if (!useDijkstra && graphHopper.getLandmarks().get(profile.getName()) != null) { // using LM because u-turn prevention does not work properly with (node-based) CH landmarks = graphHopper.getLandmarks().get(profile.getName()); } else { landmarks = null; } Weighting weighting = graphHopper.createWeighting(profile, hints); BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileStr)); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, inSubnetworkEnc); int maxVisitedNodes = hints.getInt(Parameters.Routing.MAX_VISITED_NODES, Integer.MAX_VALUE); Router router = new Router() { @Override public EdgeFilter getSnapFilter() { return snapFilter; } @Override public List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges) { assert (toNodes.length == toInEdges.length); List<Path> result = new ArrayList<>(); for (int i = 0; i < toNodes.length; i++) { result.add(calcOnePath(queryGraph, fromNode, toNodes[i], fromOutEdge, toInEdges[i])); } return result; } private Path calcOnePath(QueryGraph queryGraph, int fromNode, int toNode, int fromOutEdge, int toInEdge) { Weighting queryGraphWeighting = queryGraph.wrapWeighting(weighting); if (landmarks != null) { AStarBidirection aStarBidirection = new AStarBidirection(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; int activeLM = Math.min(8, landmarks.getLandmarkCount()); LMApproximator lmApproximator = LMApproximator.forLandmarks(queryGraph, queryGraphWeighting, landmarks, activeLM); aStarBidirection.setApproximation(lmApproximator); aStarBidirection.setMaxVisitedNodes(maxVisitedNodes); return aStarBidirection.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } else { DijkstraBidirectionRef dijkstraBidirectionRef = new DijkstraBidirectionRef(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; dijkstraBidirectionRef.setMaxVisitedNodes(maxVisitedNodes); return dijkstraBidirectionRef.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } } @Override public Weighting getWeighting() { return weighting; } }; return router; } public MapMatching(BaseGraph graph, LocationIndexTree locationIndex, Router router) { this.graph = graph; this.locationIndex = locationIndex; this.router = router; } /** * Beta parameter of the exponential distribution for modeling transition * probabilities. */ public void setTransitionProbabilityBeta(double transitionProbabilityBeta) { this.transitionProbabilityBeta = transitionProbabilityBeta; } /** * Standard deviation of the normal distribution [m] used for modeling the * GPS error. */ public void setMeasurementErrorSigma(double measurementErrorSigma) { this.measurementErrorSigma = measurementErrorSigma; } public MatchResult match(List<Observation> observations) { List<Observation> filteredObservations = filterObservations(observations); statistics.put("filteredObservations", filteredObservations.size()); // Snap observations to links. Generates multiple candidate snaps per observation. List<List<Snap>> snapsPerObservation = filteredObservations.stream() .map(o -> findCandidateSnaps(o.getPoint().lat, o.getPoint().lon)) .collect(Collectors.toList()); statistics.put("snapsPerObservation", snapsPerObservation.stream().mapToInt(Collection::size).toArray()); // Create the query graph, containing split edges so that all the places where an observation might have happened // are a node. This modifies the Snap objects and puts the new node numbers into them. queryGraph = QueryGraph.create(graph, snapsPerObservation.stream().flatMap(Collection::stream).collect(Collectors.toList())); // Creates candidates from the Snaps of all observations (a candidate is basically a // Snap + direction). List<ObservationWithCandidateStates> timeSteps = createTimeSteps(filteredObservations, snapsPerObservation); // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps); statistics.put("transitionDistances", seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> Math.round(s.transitionDescriptor.getDistance())).toArray()); statistics.put("visitedNodes", router.getVisitedNodes()); statistics.put("snapDistanceRanks", IntStream.range(0, seq.size()).map(i -> snapsPerObservation.get(i).indexOf(seq.get(i).state.getSnap())).toArray()); statistics.put("snapDistances", seq.stream().mapToDouble(s -> s.state.getSnap().getQueryDistance()).toArray()); statistics.put("maxSnapDistances", IntStream.range(0, seq.size()).mapToDouble(i -> snapsPerObservation.get(i).stream().mapToDouble(Snap::getQueryDistance).max().orElse(-1.0)).toArray()); List<EdgeIteratorState> path = seq.stream().filter(s1 -> s1.transitionDescriptor != null).flatMap(s1 -> s1.transitionDescriptor.calcEdges().stream()).collect(Collectors.toList()); MatchResult result = new MatchResult(prepareEdgeMatches(seq)); Weighting queryGraphWeighting = queryGraph.wrapWeighting(router.getWeighting()); result.setMergedPath(new MapMatchedPath(queryGraph, queryGraphWeighting, path)); result.setMatchMillis(seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> s.transitionDescriptor.getTime()).sum()); result.setMatchLength(seq.stream().filter(s -> s.transitionDescriptor != null).mapToDouble(s -> s.transitionDescriptor.getDistance()).sum()); result.setGPXEntriesLength(gpxLength(observations)); result.setGraph(queryGraph); result.setWeighting(queryGraphWeighting); return result; } /** * Filters observations to only those which will be used for map matching (i.e. those which * are separated by at least 2 * measurementErrorSigman */ public List<Observation> filterObservations(List<Observation> observations) { List<Observation> filtered = new ArrayList<>(); Observation prevEntry = null; double acc = 0.0; int last = observations.size() - 1; for (int i = 0; i <= last; i++) { Observation observation = observations.get(i); if (i == 0 || i == last || distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()) > 2 * measurementErrorSigma) { if (i > 0) { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); acc -= distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } // Here we store the meters of distance that we are missing because of the filtering, // so that when we add these terms to the distances between the filtered points, // the original total distance between the unfiltered points is conserved. // (See test for kind of a specification.) observation.setAccumulatedLinearDistanceToPrevious(acc); filtered.add(observation); prevEntry = observation; acc = 0.0; } else { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } } return filtered; } public List<Snap> findCandidateSnaps(final double queryLat, final double queryLon) {<FILL_FUNCTION_BODY>} private List<Snap> findCandidateSnapsInBBox(double queryLat, double queryLon, BBox queryShape) { EdgeFilter edgeFilter = router.getSnapFilter(); List<Snap> snaps = new ArrayList<>(); IntHashSet seenEdges = new IntHashSet(); IntHashSet seenNodes = new IntHashSet(); locationIndex.query(queryShape, edgeId -> { EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2); if (seenEdges.add(edgeId) && edgeFilter.accept(edge)) { Snap snap = new Snap(queryLat, queryLon); locationIndex.traverseEdge(queryLat, queryLon, edge, (node, normedDist, wayIndex, pos) -> { if (normedDist < snap.getQueryDistance()) { snap.setQueryDistance(normedDist); snap.setClosestNode(node); snap.setWayIndex(wayIndex); snap.setSnappedPosition(pos); } }); double dist = DIST_PLANE.calcDenormalizedDist(snap.getQueryDistance()); snap.setClosestEdge(edge); snap.setQueryDistance(dist); if (snap.isValid() && (snap.getSnappedPosition() != Snap.Position.TOWER || seenNodes.add(snap.getClosestNode()))) { snap.calcSnappedPoint(DistanceCalcEarth.DIST_EARTH); if (queryShape.contains(snap.getSnappedPoint().lat, snap.getSnappedPoint().lon)) { snaps.add(snap); } } } }); snaps.sort(Comparator.comparingDouble(Snap::getQueryDistance)); return snaps; } /** * Creates TimeSteps with candidates for the GPX entries but does not create emission or * transition probabilities. Creates directed candidates for virtual nodes and undirected * candidates for real nodes. */ private List<ObservationWithCandidateStates> createTimeSteps(List<Observation> filteredObservations, List<List<Snap>> splitsPerObservation) { if (splitsPerObservation.size() != filteredObservations.size()) { throw new IllegalArgumentException( "filteredGPXEntries and queriesPerEntry must have same size."); } final List<ObservationWithCandidateStates> timeSteps = new ArrayList<>(); for (int i = 0; i < filteredObservations.size(); i++) { Observation observation = filteredObservations.get(i); Collection<Snap> splits = splitsPerObservation.get(i); List<State> candidates = new ArrayList<>(); for (Snap split : splits) { if (queryGraph.isVirtualNode(split.getClosestNode())) { List<VirtualEdgeIteratorState> virtualEdges = new ArrayList<>(); EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(split.getClosestNode()); while (iter.next()) { if (!queryGraph.isVirtualEdge(iter.getEdge())) { throw new RuntimeException("Virtual nodes must only have virtual edges " + "to adjacent nodes."); } virtualEdges.add((VirtualEdgeIteratorState) queryGraph.getEdgeIteratorState(iter.getEdge(), iter.getAdjNode())); } if (virtualEdges.size() != 2) { throw new RuntimeException("Each virtual node must have exactly 2 " + "virtual edges (reverse virtual edges are not returned by the " + "EdgeIterator"); } // Create a directed candidate for each of the two possible directions through // the virtual node. We need to add candidates for both directions because // we don't know yet which is the correct one. This will be figured // out by the Viterbi algorithm. candidates.add(new State(observation, split, virtualEdges.get(0), virtualEdges.get(1))); candidates.add(new State(observation, split, virtualEdges.get(1), virtualEdges.get(0))); } else { // Create an undirected candidate for the real node. candidates.add(new State(observation, split)); } } timeSteps.add(new ObservationWithCandidateStates(observation, candidates)); } return timeSteps; } static class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() { return statistics; } private static class MapMatchedPath extends Path { MapMatchedPath(Graph graph, Weighting weighting, List<EdgeIteratorState> edges) { super(graph); int prevEdge = EdgeIterator.NO_EDGE; for (EdgeIteratorState edge : edges) { addDistance(edge.getDistance()); addTime(GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdge)); addEdge(edge.getEdge()); prevEdge = edge.getEdge(); } if (edges.isEmpty()) { setFound(false); } else { setFromNode(edges.get(0).getBaseNode()); setFound(true); } } } public interface Router { EdgeFilter getSnapFilter(); List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges); Weighting getWeighting(); default long getVisitedNodes() { return 0L; } } }
double rLon = (measurementErrorSigma * 360.0 / DistanceCalcEarth.DIST_EARTH.calcCircumference(queryLat)); double rLat = measurementErrorSigma / DistanceCalcEarth.METERS_PER_DEGREE; Envelope envelope = new Envelope(queryLon, queryLon, queryLat, queryLat); for (int i = 0; i < 50; i++) { envelope.expandBy(rLon, rLat); List<Snap> snaps = findCandidateSnapsInBBox(queryLat, queryLon, BBox.fromEnvelope(envelope)); if (!snaps.isEmpty()) { return snaps; } } return Collections.emptyList();
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
findCandidateSnapsInBBox
class MapMatching { private final BaseGraph graph; private final Router router; private final LocationIndexTree locationIndex; private double measurementErrorSigma = 10.0; private double transitionProbabilityBeta = 2.0; private final DistanceCalc distanceCalc = new DistancePlaneProjection(); private QueryGraph queryGraph; private Map<String, Object> statistics = new HashMap<>(); public static MapMatching fromGraphHopper(GraphHopper graphHopper, PMap hints) { Router router = routerFromGraphHopper(graphHopper, hints); return new MapMatching(graphHopper.getBaseGraph(), (LocationIndexTree) graphHopper.getLocationIndex(), router); } public static Router routerFromGraphHopper(GraphHopper graphHopper, PMap hints) { if (hints.has("vehicle")) throw new IllegalArgumentException("MapMatching hints may no longer contain a vehicle, use the profile parameter instead, see core/#1958"); if (hints.has("weighting")) throw new IllegalArgumentException("MapMatching hints may no longer contain a weighting, use the profile parameter instead, see core/#1958"); if (graphHopper.getProfiles().isEmpty()) { throw new IllegalArgumentException("No profiles found, you need to configure at least one profile to use map matching"); } if (!hints.has("profile")) { throw new IllegalArgumentException("You need to specify a profile to perform map matching"); } String profileStr = hints.getString("profile", ""); Profile profile = graphHopper.getProfile(profileStr); if (profile == null) { List<Profile> profiles = graphHopper.getProfiles(); List<String> profileNames = new ArrayList<>(profiles.size()); for (Profile p : profiles) { profileNames.add(p.getName()); } throw new IllegalArgumentException("Could not find profile '" + profileStr + "', choose one of: " + profileNames); } boolean disableLM = hints.getBool(Parameters.Landmark.DISABLE, false); boolean disableCH = hints.getBool(Parameters.CH.DISABLE, false); // see map-matching/#177: both ch.disable and lm.disable can be used to force Dijkstra which is the better // (=faster) choice when the observations are close to each other boolean useDijkstra = disableLM || disableCH; LandmarkStorage landmarks; if (!useDijkstra && graphHopper.getLandmarks().get(profile.getName()) != null) { // using LM because u-turn prevention does not work properly with (node-based) CH landmarks = graphHopper.getLandmarks().get(profile.getName()); } else { landmarks = null; } Weighting weighting = graphHopper.createWeighting(profile, hints); BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileStr)); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, inSubnetworkEnc); int maxVisitedNodes = hints.getInt(Parameters.Routing.MAX_VISITED_NODES, Integer.MAX_VALUE); Router router = new Router() { @Override public EdgeFilter getSnapFilter() { return snapFilter; } @Override public List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges) { assert (toNodes.length == toInEdges.length); List<Path> result = new ArrayList<>(); for (int i = 0; i < toNodes.length; i++) { result.add(calcOnePath(queryGraph, fromNode, toNodes[i], fromOutEdge, toInEdges[i])); } return result; } private Path calcOnePath(QueryGraph queryGraph, int fromNode, int toNode, int fromOutEdge, int toInEdge) { Weighting queryGraphWeighting = queryGraph.wrapWeighting(weighting); if (landmarks != null) { AStarBidirection aStarBidirection = new AStarBidirection(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; int activeLM = Math.min(8, landmarks.getLandmarkCount()); LMApproximator lmApproximator = LMApproximator.forLandmarks(queryGraph, queryGraphWeighting, landmarks, activeLM); aStarBidirection.setApproximation(lmApproximator); aStarBidirection.setMaxVisitedNodes(maxVisitedNodes); return aStarBidirection.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } else { DijkstraBidirectionRef dijkstraBidirectionRef = new DijkstraBidirectionRef(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; dijkstraBidirectionRef.setMaxVisitedNodes(maxVisitedNodes); return dijkstraBidirectionRef.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } } @Override public Weighting getWeighting() { return weighting; } }; return router; } public MapMatching(BaseGraph graph, LocationIndexTree locationIndex, Router router) { this.graph = graph; this.locationIndex = locationIndex; this.router = router; } /** * Beta parameter of the exponential distribution for modeling transition * probabilities. */ public void setTransitionProbabilityBeta(double transitionProbabilityBeta) { this.transitionProbabilityBeta = transitionProbabilityBeta; } /** * Standard deviation of the normal distribution [m] used for modeling the * GPS error. */ public void setMeasurementErrorSigma(double measurementErrorSigma) { this.measurementErrorSigma = measurementErrorSigma; } public MatchResult match(List<Observation> observations) { List<Observation> filteredObservations = filterObservations(observations); statistics.put("filteredObservations", filteredObservations.size()); // Snap observations to links. Generates multiple candidate snaps per observation. List<List<Snap>> snapsPerObservation = filteredObservations.stream() .map(o -> findCandidateSnaps(o.getPoint().lat, o.getPoint().lon)) .collect(Collectors.toList()); statistics.put("snapsPerObservation", snapsPerObservation.stream().mapToInt(Collection::size).toArray()); // Create the query graph, containing split edges so that all the places where an observation might have happened // are a node. This modifies the Snap objects and puts the new node numbers into them. queryGraph = QueryGraph.create(graph, snapsPerObservation.stream().flatMap(Collection::stream).collect(Collectors.toList())); // Creates candidates from the Snaps of all observations (a candidate is basically a // Snap + direction). List<ObservationWithCandidateStates> timeSteps = createTimeSteps(filteredObservations, snapsPerObservation); // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps); statistics.put("transitionDistances", seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> Math.round(s.transitionDescriptor.getDistance())).toArray()); statistics.put("visitedNodes", router.getVisitedNodes()); statistics.put("snapDistanceRanks", IntStream.range(0, seq.size()).map(i -> snapsPerObservation.get(i).indexOf(seq.get(i).state.getSnap())).toArray()); statistics.put("snapDistances", seq.stream().mapToDouble(s -> s.state.getSnap().getQueryDistance()).toArray()); statistics.put("maxSnapDistances", IntStream.range(0, seq.size()).mapToDouble(i -> snapsPerObservation.get(i).stream().mapToDouble(Snap::getQueryDistance).max().orElse(-1.0)).toArray()); List<EdgeIteratorState> path = seq.stream().filter(s1 -> s1.transitionDescriptor != null).flatMap(s1 -> s1.transitionDescriptor.calcEdges().stream()).collect(Collectors.toList()); MatchResult result = new MatchResult(prepareEdgeMatches(seq)); Weighting queryGraphWeighting = queryGraph.wrapWeighting(router.getWeighting()); result.setMergedPath(new MapMatchedPath(queryGraph, queryGraphWeighting, path)); result.setMatchMillis(seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> s.transitionDescriptor.getTime()).sum()); result.setMatchLength(seq.stream().filter(s -> s.transitionDescriptor != null).mapToDouble(s -> s.transitionDescriptor.getDistance()).sum()); result.setGPXEntriesLength(gpxLength(observations)); result.setGraph(queryGraph); result.setWeighting(queryGraphWeighting); return result; } /** * Filters observations to only those which will be used for map matching (i.e. those which * are separated by at least 2 * measurementErrorSigman */ public List<Observation> filterObservations(List<Observation> observations) { List<Observation> filtered = new ArrayList<>(); Observation prevEntry = null; double acc = 0.0; int last = observations.size() - 1; for (int i = 0; i <= last; i++) { Observation observation = observations.get(i); if (i == 0 || i == last || distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()) > 2 * measurementErrorSigma) { if (i > 0) { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); acc -= distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } // Here we store the meters of distance that we are missing because of the filtering, // so that when we add these terms to the distances between the filtered points, // the original total distance between the unfiltered points is conserved. // (See test for kind of a specification.) observation.setAccumulatedLinearDistanceToPrevious(acc); filtered.add(observation); prevEntry = observation; acc = 0.0; } else { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } } return filtered; } public List<Snap> findCandidateSnaps(final double queryLat, final double queryLon) { double rLon = (measurementErrorSigma * 360.0 / DistanceCalcEarth.DIST_EARTH.calcCircumference(queryLat)); double rLat = measurementErrorSigma / DistanceCalcEarth.METERS_PER_DEGREE; Envelope envelope = new Envelope(queryLon, queryLon, queryLat, queryLat); for (int i = 0; i < 50; i++) { envelope.expandBy(rLon, rLat); List<Snap> snaps = findCandidateSnapsInBBox(queryLat, queryLon, BBox.fromEnvelope(envelope)); if (!snaps.isEmpty()) { return snaps; } } return Collections.emptyList(); } private List<Snap> findCandidateSnapsInBBox(double queryLat, double queryLon, BBox queryShape) {<FILL_FUNCTION_BODY>} /** * Creates TimeSteps with candidates for the GPX entries but does not create emission or * transition probabilities. Creates directed candidates for virtual nodes and undirected * candidates for real nodes. */ private List<ObservationWithCandidateStates> createTimeSteps(List<Observation> filteredObservations, List<List<Snap>> splitsPerObservation) { if (splitsPerObservation.size() != filteredObservations.size()) { throw new IllegalArgumentException( "filteredGPXEntries and queriesPerEntry must have same size."); } final List<ObservationWithCandidateStates> timeSteps = new ArrayList<>(); for (int i = 0; i < filteredObservations.size(); i++) { Observation observation = filteredObservations.get(i); Collection<Snap> splits = splitsPerObservation.get(i); List<State> candidates = new ArrayList<>(); for (Snap split : splits) { if (queryGraph.isVirtualNode(split.getClosestNode())) { List<VirtualEdgeIteratorState> virtualEdges = new ArrayList<>(); EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(split.getClosestNode()); while (iter.next()) { if (!queryGraph.isVirtualEdge(iter.getEdge())) { throw new RuntimeException("Virtual nodes must only have virtual edges " + "to adjacent nodes."); } virtualEdges.add((VirtualEdgeIteratorState) queryGraph.getEdgeIteratorState(iter.getEdge(), iter.getAdjNode())); } if (virtualEdges.size() != 2) { throw new RuntimeException("Each virtual node must have exactly 2 " + "virtual edges (reverse virtual edges are not returned by the " + "EdgeIterator"); } // Create a directed candidate for each of the two possible directions through // the virtual node. We need to add candidates for both directions because // we don't know yet which is the correct one. This will be figured // out by the Viterbi algorithm. candidates.add(new State(observation, split, virtualEdges.get(0), virtualEdges.get(1))); candidates.add(new State(observation, split, virtualEdges.get(1), virtualEdges.get(0))); } else { // Create an undirected candidate for the real node. candidates.add(new State(observation, split)); } } timeSteps.add(new ObservationWithCandidateStates(observation, candidates)); } return timeSteps; } static class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() { return statistics; } private static class MapMatchedPath extends Path { MapMatchedPath(Graph graph, Weighting weighting, List<EdgeIteratorState> edges) { super(graph); int prevEdge = EdgeIterator.NO_EDGE; for (EdgeIteratorState edge : edges) { addDistance(edge.getDistance()); addTime(GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdge)); addEdge(edge.getEdge()); prevEdge = edge.getEdge(); } if (edges.isEmpty()) { setFound(false); } else { setFromNode(edges.get(0).getBaseNode()); setFound(true); } } } public interface Router { EdgeFilter getSnapFilter(); List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges); Weighting getWeighting(); default long getVisitedNodes() { return 0L; } } }
EdgeFilter edgeFilter = router.getSnapFilter(); List<Snap> snaps = new ArrayList<>(); IntHashSet seenEdges = new IntHashSet(); IntHashSet seenNodes = new IntHashSet(); locationIndex.query(queryShape, edgeId -> { EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2); if (seenEdges.add(edgeId) && edgeFilter.accept(edge)) { Snap snap = new Snap(queryLat, queryLon); locationIndex.traverseEdge(queryLat, queryLon, edge, (node, normedDist, wayIndex, pos) -> { if (normedDist < snap.getQueryDistance()) { snap.setQueryDistance(normedDist); snap.setClosestNode(node); snap.setWayIndex(wayIndex); snap.setSnappedPosition(pos); } }); double dist = DIST_PLANE.calcDenormalizedDist(snap.getQueryDistance()); snap.setClosestEdge(edge); snap.setQueryDistance(dist); if (snap.isValid() && (snap.getSnappedPosition() != Snap.Position.TOWER || seenNodes.add(snap.getClosestNode()))) { snap.calcSnappedPoint(DistanceCalcEarth.DIST_EARTH); if (queryShape.contains(snap.getSnappedPoint().lat, snap.getSnappedPoint().lon)) { snaps.add(snap); } } } }); snaps.sort(Comparator.comparingDouble(Snap::getQueryDistance)); return snaps;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
createTimeSteps
class MapMatching { private final BaseGraph graph; private final Router router; private final LocationIndexTree locationIndex; private double measurementErrorSigma = 10.0; private double transitionProbabilityBeta = 2.0; private final DistanceCalc distanceCalc = new DistancePlaneProjection(); private QueryGraph queryGraph; private Map<String, Object> statistics = new HashMap<>(); public static MapMatching fromGraphHopper(GraphHopper graphHopper, PMap hints) { Router router = routerFromGraphHopper(graphHopper, hints); return new MapMatching(graphHopper.getBaseGraph(), (LocationIndexTree) graphHopper.getLocationIndex(), router); } public static Router routerFromGraphHopper(GraphHopper graphHopper, PMap hints) { if (hints.has("vehicle")) throw new IllegalArgumentException("MapMatching hints may no longer contain a vehicle, use the profile parameter instead, see core/#1958"); if (hints.has("weighting")) throw new IllegalArgumentException("MapMatching hints may no longer contain a weighting, use the profile parameter instead, see core/#1958"); if (graphHopper.getProfiles().isEmpty()) { throw new IllegalArgumentException("No profiles found, you need to configure at least one profile to use map matching"); } if (!hints.has("profile")) { throw new IllegalArgumentException("You need to specify a profile to perform map matching"); } String profileStr = hints.getString("profile", ""); Profile profile = graphHopper.getProfile(profileStr); if (profile == null) { List<Profile> profiles = graphHopper.getProfiles(); List<String> profileNames = new ArrayList<>(profiles.size()); for (Profile p : profiles) { profileNames.add(p.getName()); } throw new IllegalArgumentException("Could not find profile '" + profileStr + "', choose one of: " + profileNames); } boolean disableLM = hints.getBool(Parameters.Landmark.DISABLE, false); boolean disableCH = hints.getBool(Parameters.CH.DISABLE, false); // see map-matching/#177: both ch.disable and lm.disable can be used to force Dijkstra which is the better // (=faster) choice when the observations are close to each other boolean useDijkstra = disableLM || disableCH; LandmarkStorage landmarks; if (!useDijkstra && graphHopper.getLandmarks().get(profile.getName()) != null) { // using LM because u-turn prevention does not work properly with (node-based) CH landmarks = graphHopper.getLandmarks().get(profile.getName()); } else { landmarks = null; } Weighting weighting = graphHopper.createWeighting(profile, hints); BooleanEncodedValue inSubnetworkEnc = graphHopper.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileStr)); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, inSubnetworkEnc); int maxVisitedNodes = hints.getInt(Parameters.Routing.MAX_VISITED_NODES, Integer.MAX_VALUE); Router router = new Router() { @Override public EdgeFilter getSnapFilter() { return snapFilter; } @Override public List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges) { assert (toNodes.length == toInEdges.length); List<Path> result = new ArrayList<>(); for (int i = 0; i < toNodes.length; i++) { result.add(calcOnePath(queryGraph, fromNode, toNodes[i], fromOutEdge, toInEdges[i])); } return result; } private Path calcOnePath(QueryGraph queryGraph, int fromNode, int toNode, int fromOutEdge, int toInEdge) { Weighting queryGraphWeighting = queryGraph.wrapWeighting(weighting); if (landmarks != null) { AStarBidirection aStarBidirection = new AStarBidirection(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; int activeLM = Math.min(8, landmarks.getLandmarkCount()); LMApproximator lmApproximator = LMApproximator.forLandmarks(queryGraph, queryGraphWeighting, landmarks, activeLM); aStarBidirection.setApproximation(lmApproximator); aStarBidirection.setMaxVisitedNodes(maxVisitedNodes); return aStarBidirection.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } else { DijkstraBidirectionRef dijkstraBidirectionRef = new DijkstraBidirectionRef(queryGraph, queryGraphWeighting, TraversalMode.EDGE_BASED) { @Override protected void initCollections(int size) { super.initCollections(50); } }; dijkstraBidirectionRef.setMaxVisitedNodes(maxVisitedNodes); return dijkstraBidirectionRef.calcPath(fromNode, toNode, fromOutEdge, toInEdge); } } @Override public Weighting getWeighting() { return weighting; } }; return router; } public MapMatching(BaseGraph graph, LocationIndexTree locationIndex, Router router) { this.graph = graph; this.locationIndex = locationIndex; this.router = router; } /** * Beta parameter of the exponential distribution for modeling transition * probabilities. */ public void setTransitionProbabilityBeta(double transitionProbabilityBeta) { this.transitionProbabilityBeta = transitionProbabilityBeta; } /** * Standard deviation of the normal distribution [m] used for modeling the * GPS error. */ public void setMeasurementErrorSigma(double measurementErrorSigma) { this.measurementErrorSigma = measurementErrorSigma; } public MatchResult match(List<Observation> observations) { List<Observation> filteredObservations = filterObservations(observations); statistics.put("filteredObservations", filteredObservations.size()); // Snap observations to links. Generates multiple candidate snaps per observation. List<List<Snap>> snapsPerObservation = filteredObservations.stream() .map(o -> findCandidateSnaps(o.getPoint().lat, o.getPoint().lon)) .collect(Collectors.toList()); statistics.put("snapsPerObservation", snapsPerObservation.stream().mapToInt(Collection::size).toArray()); // Create the query graph, containing split edges so that all the places where an observation might have happened // are a node. This modifies the Snap objects and puts the new node numbers into them. queryGraph = QueryGraph.create(graph, snapsPerObservation.stream().flatMap(Collection::stream).collect(Collectors.toList())); // Creates candidates from the Snaps of all observations (a candidate is basically a // Snap + direction). List<ObservationWithCandidateStates> timeSteps = createTimeSteps(filteredObservations, snapsPerObservation); // Compute the most likely sequence of map matching candidates: List<SequenceState<State, Observation, Path>> seq = computeViterbiSequence(timeSteps); statistics.put("transitionDistances", seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> Math.round(s.transitionDescriptor.getDistance())).toArray()); statistics.put("visitedNodes", router.getVisitedNodes()); statistics.put("snapDistanceRanks", IntStream.range(0, seq.size()).map(i -> snapsPerObservation.get(i).indexOf(seq.get(i).state.getSnap())).toArray()); statistics.put("snapDistances", seq.stream().mapToDouble(s -> s.state.getSnap().getQueryDistance()).toArray()); statistics.put("maxSnapDistances", IntStream.range(0, seq.size()).mapToDouble(i -> snapsPerObservation.get(i).stream().mapToDouble(Snap::getQueryDistance).max().orElse(-1.0)).toArray()); List<EdgeIteratorState> path = seq.stream().filter(s1 -> s1.transitionDescriptor != null).flatMap(s1 -> s1.transitionDescriptor.calcEdges().stream()).collect(Collectors.toList()); MatchResult result = new MatchResult(prepareEdgeMatches(seq)); Weighting queryGraphWeighting = queryGraph.wrapWeighting(router.getWeighting()); result.setMergedPath(new MapMatchedPath(queryGraph, queryGraphWeighting, path)); result.setMatchMillis(seq.stream().filter(s -> s.transitionDescriptor != null).mapToLong(s -> s.transitionDescriptor.getTime()).sum()); result.setMatchLength(seq.stream().filter(s -> s.transitionDescriptor != null).mapToDouble(s -> s.transitionDescriptor.getDistance()).sum()); result.setGPXEntriesLength(gpxLength(observations)); result.setGraph(queryGraph); result.setWeighting(queryGraphWeighting); return result; } /** * Filters observations to only those which will be used for map matching (i.e. those which * are separated by at least 2 * measurementErrorSigman */ public List<Observation> filterObservations(List<Observation> observations) { List<Observation> filtered = new ArrayList<>(); Observation prevEntry = null; double acc = 0.0; int last = observations.size() - 1; for (int i = 0; i <= last; i++) { Observation observation = observations.get(i); if (i == 0 || i == last || distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()) > 2 * measurementErrorSigma) { if (i > 0) { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); acc -= distanceCalc.calcDist( prevEntry.getPoint().getLat(), prevEntry.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } // Here we store the meters of distance that we are missing because of the filtering, // so that when we add these terms to the distances between the filtered points, // the original total distance between the unfiltered points is conserved. // (See test for kind of a specification.) observation.setAccumulatedLinearDistanceToPrevious(acc); filtered.add(observation); prevEntry = observation; acc = 0.0; } else { Observation prevObservation = observations.get(i - 1); acc += distanceCalc.calcDist( prevObservation.getPoint().getLat(), prevObservation.getPoint().getLon(), observation.getPoint().getLat(), observation.getPoint().getLon()); } } return filtered; } public List<Snap> findCandidateSnaps(final double queryLat, final double queryLon) { double rLon = (measurementErrorSigma * 360.0 / DistanceCalcEarth.DIST_EARTH.calcCircumference(queryLat)); double rLat = measurementErrorSigma / DistanceCalcEarth.METERS_PER_DEGREE; Envelope envelope = new Envelope(queryLon, queryLon, queryLat, queryLat); for (int i = 0; i < 50; i++) { envelope.expandBy(rLon, rLat); List<Snap> snaps = findCandidateSnapsInBBox(queryLat, queryLon, BBox.fromEnvelope(envelope)); if (!snaps.isEmpty()) { return snaps; } } return Collections.emptyList(); } private List<Snap> findCandidateSnapsInBBox(double queryLat, double queryLon, BBox queryShape) { EdgeFilter edgeFilter = router.getSnapFilter(); List<Snap> snaps = new ArrayList<>(); IntHashSet seenEdges = new IntHashSet(); IntHashSet seenNodes = new IntHashSet(); locationIndex.query(queryShape, edgeId -> { EdgeIteratorState edge = graph.getEdgeIteratorStateForKey(edgeId * 2); if (seenEdges.add(edgeId) && edgeFilter.accept(edge)) { Snap snap = new Snap(queryLat, queryLon); locationIndex.traverseEdge(queryLat, queryLon, edge, (node, normedDist, wayIndex, pos) -> { if (normedDist < snap.getQueryDistance()) { snap.setQueryDistance(normedDist); snap.setClosestNode(node); snap.setWayIndex(wayIndex); snap.setSnappedPosition(pos); } }); double dist = DIST_PLANE.calcDenormalizedDist(snap.getQueryDistance()); snap.setClosestEdge(edge); snap.setQueryDistance(dist); if (snap.isValid() && (snap.getSnappedPosition() != Snap.Position.TOWER || seenNodes.add(snap.getClosestNode()))) { snap.calcSnappedPoint(DistanceCalcEarth.DIST_EARTH); if (queryShape.contains(snap.getSnappedPoint().lat, snap.getSnappedPoint().lon)) { snaps.add(snap); } } } }); snaps.sort(Comparator.comparingDouble(Snap::getQueryDistance)); return snaps; } /** * Creates TimeSteps with candidates for the GPX entries but does not create emission or * transition probabilities. Creates directed candidates for virtual nodes and undirected * candidates for real nodes. */ private List<ObservationWithCandidateStates> createTimeSteps(List<Observation> filteredObservations, List<List<Snap>> splitsPerObservation) {<FILL_FUNCTION_BODY>} static class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() { return statistics; } private static class MapMatchedPath extends Path { MapMatchedPath(Graph graph, Weighting weighting, List<EdgeIteratorState> edges) { super(graph); int prevEdge = EdgeIterator.NO_EDGE; for (EdgeIteratorState edge : edges) { addDistance(edge.getDistance()); addTime(GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdge)); addEdge(edge.getEdge()); prevEdge = edge.getEdge(); } if (edges.isEmpty()) { setFound(false); } else { setFromNode(edges.get(0).getBaseNode()); setFound(true); } } } public interface Router { EdgeFilter getSnapFilter(); List<Path> calcPaths(QueryGraph queryGraph, int fromNode, int fromOutEdge, int[] toNodes, int[] toInEdges); Weighting getWeighting(); default long getVisitedNodes() { return 0L; } } }
if (splitsPerObservation.size() != filteredObservations.size()) { throw new IllegalArgumentException( "filteredGPXEntries and queriesPerEntry must have same size."); } final List<ObservationWithCandidateStates> timeSteps = new ArrayList<>(); for (int i = 0; i < filteredObservations.size(); i++) { Observation observation = filteredObservations.get(i); Collection<Snap> splits = splitsPerObservation.get(i); List<State> candidates = new ArrayList<>(); for (Snap split : splits) { if (queryGraph.isVirtualNode(split.getClosestNode())) { List<VirtualEdgeIteratorState> virtualEdges = new ArrayList<>(); EdgeIterator iter = queryGraph.createEdgeExplorer().setBaseNode(split.getClosestNode()); while (iter.next()) { if (!queryGraph.isVirtualEdge(iter.getEdge())) { throw new RuntimeException("Virtual nodes must only have virtual edges " + "to adjacent nodes."); } virtualEdges.add((VirtualEdgeIteratorState) queryGraph.getEdgeIteratorState(iter.getEdge(), iter.getAdjNode())); } if (virtualEdges.size() != 2) { throw new RuntimeException("Each virtual node must have exactly 2 " + "virtual edges (reverse virtual edges are not returned by the " + "EdgeIterator"); } // Create a directed candidate for each of the two possible directions through // the virtual node. We need to add candidates for both directions because // we don't know yet which is the correct one. This will be figured // out by the Viterbi algorithm. candidates.add(new State(observation, split, virtualEdges.get(0), virtualEdges.get(1))); candidates.add(new State(observation, split, virtualEdges.get(1), virtualEdges.get(0))); } else { // Create an undirected candidate for the real node. candidates.add(new State(observation, split)); } } timeSteps.add(new ObservationWithCandidateStates(observation, candidates)); } return timeSteps;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
Label
computeViterbiSequence
class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) {<FILL_FUNCTION_BODY>
if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
Label
prepareEdgeMatches
class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) {<FILL_FUNCTION_BODY>
// This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
Label
gpxLength
class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) {<FILL_FUNCTION_BODY>
if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; }
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
Label
equalEdges
class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) {<FILL_FUNCTION_BODY>
return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode();
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
Label
resolveToRealEdge
class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) {<FILL_FUNCTION_BODY>
if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; }
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
Label
getStatistics
class Label { int timeStep; State state; Label back; boolean isDeleted; double minusLogProbability; } private List<SequenceState<State, Observation, Path>> computeViterbiSequence(List<ObservationWithCandidateStates> timeSteps) { if (timeSteps.isEmpty()) { return Collections.emptyList(); } final HmmProbabilities probabilities = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta); final Map<State, Label> labels = new HashMap<>(); Map<Transition<State>, Path> roadPaths = new HashMap<>(); PriorityQueue<Label> q = new PriorityQueue<>(Comparator.comparing(qe -> qe.minusLogProbability)); for (State candidate : timeSteps.get(0).candidates) { // distance from observation to road in meters final double distance = candidate.getSnap().getQueryDistance(); Label label = new Label(); label.state = candidate; label.minusLogProbability = probabilities.emissionLogProbability(distance) * -1.0; q.add(label); labels.put(candidate, label); } Label qe = null; while (!q.isEmpty()) { qe = q.poll(); if (qe.isDeleted) continue; if (qe.timeStep == timeSteps.size() - 1) break; State from = qe.state; ObservationWithCandidateStates timeStep = timeSteps.get(qe.timeStep); ObservationWithCandidateStates nextTimeStep = timeSteps.get(qe.timeStep + 1); final double linearDistance = distanceCalc.calcDist(timeStep.observation.getPoint().lat, timeStep.observation.getPoint().lon, nextTimeStep.observation.getPoint().lat, nextTimeStep.observation.getPoint().lon) + nextTimeStep.observation.getAccumulatedLinearDistanceToPrevious(); int fromNode = from.getSnap().getClosestNode(); int fromOutEdge = from.isOnDirectedEdge() ? from.getOutgoingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE; int[] toNodes = nextTimeStep.candidates.stream().mapToInt(c -> c.getSnap().getClosestNode()).toArray(); int[] toInEdges = nextTimeStep.candidates.stream().mapToInt(to -> to.isOnDirectedEdge() ? to.getIncomingVirtualEdge().getEdge() : EdgeIterator.ANY_EDGE).toArray(); List<Path> paths = router.calcPaths(queryGraph, fromNode, fromOutEdge, toNodes, toInEdges); for (int i = 0; i < nextTimeStep.candidates.size(); i++) { State to = nextTimeStep.candidates.get(i); Path path = paths.get(i); if (path.isFound()) { double transitionLogProbability = probabilities.transitionLogProbability(path.getDistance(), linearDistance); Transition<State> transition = new Transition<>(from, to); roadPaths.put(transition, path); double minusLogProbability = qe.minusLogProbability - probabilities.emissionLogProbability(to.getSnap().getQueryDistance()) - transitionLogProbability; Label label1 = labels.get(to); if (label1 == null || minusLogProbability < label1.minusLogProbability) { q.stream().filter(oldQe -> !oldQe.isDeleted && oldQe.state == to).findFirst().ifPresent(oldQe -> oldQe.isDeleted = true); Label label = new Label(); label.state = to; label.timeStep = qe.timeStep + 1; label.back = qe; label.minusLogProbability = minusLogProbability; q.add(label); labels.put(to, label); } } } } if (qe == null) { throw new IllegalArgumentException("Sequence is broken for submitted track at initial time step."); } if (qe.timeStep != timeSteps.size() - 1) { throw new IllegalArgumentException("Sequence is broken for submitted track at time step " + qe.timeStep + ". observation:" + qe.state.getEntry()); } ArrayList<SequenceState<State, Observation, Path>> result = new ArrayList<>(); while (qe != null) { final SequenceState<State, Observation, Path> ss = new SequenceState<>(qe.state, qe.state.getEntry(), qe.back == null ? null : roadPaths.get(new Transition<>(qe.back.state, qe.state))); result.add(ss); qe = qe.back; } Collections.reverse(result); return result; } private List<EdgeMatch> prepareEdgeMatches(List<SequenceState<State, Observation, Path>> seq) { // This creates a list of directed edges (EdgeIteratorState instances turned the right way), // each associated with 0 or more of the observations. // These directed edges are edges of the real street graph, where nodes are intersections. // So in _this_ representation, the path that you get when you just look at the edges goes from // an intersection to an intersection. // Implementation note: We have to look at both states _and_ transitions, since we can have e.g. just one state, // or two states with a transition that is an empty path (observations snapped to the same node in the query graph), // but these states still happen on an edge, and for this representation, we want to have that edge. // (Whereas in the ResponsePath representation, we would just see an empty path.) // Note that the result can be empty, even when the input is not. Observations can be on nodes as well as on // edges, and when all observations are on the same node, we get no edge at all. // But apart from that corner case, all observations that go in here are also in the result. // (Consider totally forbidding candidate states to be snapped to a point, and make them all be on directed // edges, then that corner case goes away.) List<EdgeMatch> edgeMatches = new ArrayList<>(); List<State> states = new ArrayList<>(); EdgeIteratorState currentDirectedRealEdge = null; for (SequenceState<State, Observation, Path> transitionAndState : seq) { // transition (except before the first state) if (transitionAndState.transitionDescriptor != null) { for (EdgeIteratorState edge : transitionAndState.transitionDescriptor.calcEdges()) { EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(edge); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } } // state if (transitionAndState.state.isOnDirectedEdge()) { // as opposed to on a node EdgeIteratorState newDirectedRealEdge = resolveToRealEdge(transitionAndState.state.getOutgoingVirtualEdge()); if (currentDirectedRealEdge != null) { if (!equalEdges(currentDirectedRealEdge, newDirectedRealEdge)) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); states = new ArrayList<>(); } } currentDirectedRealEdge = newDirectedRealEdge; } states.add(transitionAndState.state); } if (currentDirectedRealEdge != null) { EdgeMatch edgeMatch = new EdgeMatch(currentDirectedRealEdge, states); edgeMatches.add(edgeMatch); } return edgeMatches; } private double gpxLength(List<Observation> gpxList) { if (gpxList.isEmpty()) { return 0; } else { double gpxLength = 0; Observation prevEntry = gpxList.get(0); for (int i = 1; i < gpxList.size(); i++) { Observation entry = gpxList.get(i); gpxLength += distanceCalc.calcDist(prevEntry.getPoint().lat, prevEntry.getPoint().lon, entry.getPoint().lat, entry.getPoint().lon); prevEntry = entry; } return gpxLength; } } private boolean equalEdges(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.getEdge() == edge2.getEdge() && edge1.getBaseNode() == edge2.getBaseNode() && edge1.getAdjNode() == edge2.getAdjNode(); } private EdgeIteratorState resolveToRealEdge(EdgeIteratorState edgeIteratorState) { if (queryGraph.isVirtualNode(edgeIteratorState.getBaseNode()) || queryGraph.isVirtualNode(edgeIteratorState.getAdjNode())) { return graph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) edgeIteratorState).getOriginalEdgeKey()); } else { return edgeIteratorState; } } public Map<String, Object> getStatistics() {<FILL_FUNCTION_BODY>
return statistics;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Stop.java
Loader
isRequired
class Loader extends Entity.Loader<Stop> { public Loader(GTFSFeed feed) { super(feed, "stops"); } @Override protected boolean isRequired() {<FILL_FUNCTION_BODY>} @Override public void loadOneRow() throws IOException { Stop s = new Stop(); s.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index s.stop_id = getStringField("stop_id", true); s.stop_code = getStringField("stop_code", false); s.stop_name = getStringField("stop_name", true); s.stop_desc = getStringField("stop_desc", false); s.stop_lat = getDoubleField("stop_lat", true, -90D, 90D); s.stop_lon = getDoubleField("stop_lon", true, -180D, 180D); s.zone_id = getStringField("zone_id", false); s.stop_url = getUrlField("stop_url", false); s.location_type = getIntField("location_type", false, 0, 4); s.parent_station = getStringField("parent_station", false); s.stop_timezone = getStringField("stop_timezone", false); s.wheelchair_boarding = getStringField("wheelchair_boarding", false); s.feed = feed; s.feed_id = feed.feedId; /* TODO check ref integrity later, this table self-references via parent_station */ feed.stops.put(s.stop_id, s); } }
return true;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Stop.java
Loader
loadOneRow
class Loader extends Entity.Loader<Stop> { public Loader(GTFSFeed feed) { super(feed, "stops"); } @Override protected boolean isRequired() { return true; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} }
Stop s = new Stop(); s.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index s.stop_id = getStringField("stop_id", true); s.stop_code = getStringField("stop_code", false); s.stop_name = getStringField("stop_name", true); s.stop_desc = getStringField("stop_desc", false); s.stop_lat = getDoubleField("stop_lat", true, -90D, 90D); s.stop_lon = getDoubleField("stop_lon", true, -180D, 180D); s.zone_id = getStringField("zone_id", false); s.stop_url = getUrlField("stop_url", false); s.location_type = getIntField("location_type", false, 0, 4); s.parent_station = getStringField("parent_station", false); s.stop_timezone = getStringField("stop_timezone", false); s.wheelchair_boarding = getStringField("wheelchair_boarding", false); s.feed = feed; s.feed_id = feed.feedId; /* TODO check ref integrity later, this table self-references via parent_station */ feed.stops.put(s.stop_id, s);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Stop.java
Loader
toString
class Loader extends Entity.Loader<Stop> { public Loader(GTFSFeed feed) { super(feed, "stops"); } @Override protected boolean isRequired() { return true; } @Override public void loadOneRow() throws IOException { Stop s = new Stop(); s.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index s.stop_id = getStringField("stop_id", true); s.stop_code = getStringField("stop_code", false); s.stop_name = getStringField("stop_name", true); s.stop_desc = getStringField("stop_desc", false); s.stop_lat = getDoubleField("stop_lat", true, -90D, 90D); s.stop_lon = getDoubleField("stop_lon", true, -180D, 180D); s.zone_id = getStringField("zone_id", false); s.stop_url = getUrlField("stop_url", false); s.location_type = getIntField("location_type", false, 0, 4); s.parent_station = getStringField("parent_station", false); s.stop_timezone = getStringField("stop_timezone", false); s.wheelchair_boarding = getStringField("wheelchair_boarding", false); s.feed = feed; s.feed_id = feed.feedId; /* TODO check ref integrity later, this table self-references via parent_station */ feed.stops.put(s.stop_id, s); } } @Override public String toString() {<FILL_FUNCTION_BODY>
return "Stop{" + "stop_id='" + stop_id + '\'' + '}';
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/Label.java
Transition
toString
class Transition { final Label label; final GraphExplorer.MultiModalEdge edge; Transition(Label label, GraphExplorer.MultiModalEdge edge) { this.label = label; this.edge = edge; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return (edge != null ? edge.toString() + " -> " : "") + label.node;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/Label.java
Transition
toString
class Transition { final Label label; final GraphExplorer.MultiModalEdge edge; Transition(Label label, GraphExplorer.MultiModalEdge edge) { this.label = label; this.edge = edge; } @Override public String toString() { return (edge != null ? edge.toString() + " -> " : "") + label.node; } } public boolean deleted = false; public final long currentTime; public final GraphExplorer.MultiModalEdge edge; public final NodeId node; public final int nTransfers; public final Long departureTime; public final long streetTime; public final long extraWeight; final long residualDelay; final boolean impossible; public final Label parent; Label(long currentTime, GraphExplorer.MultiModalEdge edge, NodeId node, int nTransfers, Long departureTime, long streetTime, long extraWeight, long residualDelay, boolean impossible, Label parent) { this.currentTime = currentTime; this.edge = edge; this.node = node; this.nTransfers = nTransfers; this.departureTime = departureTime; this.streetTime = streetTime; this.extraWeight = extraWeight; this.residualDelay = residualDelay; this.impossible = impossible; this.parent = parent; } @Override public String toString() {<FILL_FUNCTION_BODY>
return node + " " + (departureTime != null ? Instant.ofEpochMilli(departureTime) : "---") + "\t" + nTransfers + "\t" + Instant.ofEpochMilli(currentTime);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/Label.java
Transition
getTransitions
class Transition { final Label label; final GraphExplorer.MultiModalEdge edge; Transition(Label label, GraphExplorer.MultiModalEdge edge) { this.label = label; this.edge = edge; } @Override public String toString() { return (edge != null ? edge.toString() + " -> " : "") + label.node; } } public boolean deleted = false; public final long currentTime; public final GraphExplorer.MultiModalEdge edge; public final NodeId node; public final int nTransfers; public final Long departureTime; public final long streetTime; public final long extraWeight; final long residualDelay; final boolean impossible; public final Label parent; Label(long currentTime, GraphExplorer.MultiModalEdge edge, NodeId node, int nTransfers, Long departureTime, long streetTime, long extraWeight, long residualDelay, boolean impossible, Label parent) { this.currentTime = currentTime; this.edge = edge; this.node = node; this.nTransfers = nTransfers; this.departureTime = departureTime; this.streetTime = streetTime; this.extraWeight = extraWeight; this.residualDelay = residualDelay; this.impossible = impossible; this.parent = parent; } @Override public String toString() { return node + " " + (departureTime != null ? Instant.ofEpochMilli(departureTime) : "---") + "\t" + nTransfers + "\t" + Instant.ofEpochMilli(currentTime); } static List<Label.Transition> getTransitions(Label _label, boolean arriveBy) {<FILL_FUNCTION_BODY>
Label label = _label; boolean reverseEdgeFlags = !arriveBy; List<Label.Transition> result = new ArrayList<>(); if (!reverseEdgeFlags) { result.add(new Label.Transition(label, null)); } while (label.parent != null) { Label.Transition transition; if (reverseEdgeFlags) { transition = new Label.Transition(label, label.edge); } else { transition = new Label.Transition(label.parent, label.edge); } label = label.parent; result.add(transition); } if (reverseEdgeFlags) { result.add(new Label.Transition(label, null)); Collections.reverse(result); } return result;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/Label.java
NodeId
equals
class NodeId { public NodeId(int streetNode, int ptNode) { this.streetNode = streetNode; this.ptNode = ptNode; } public int streetNode; public int ptNode; @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = 1; result = 31 * result + streetNode; result = 31 * result + ptNode; return result; } @Override public String toString() { return "NodeId{" + "streetNode=" + streetNode + ", ptNode=" + ptNode + '}'; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeId nodeId = (NodeId) o; return streetNode == nodeId.streetNode && ptNode == nodeId.ptNode;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/Label.java
NodeId
hashCode
class NodeId { public NodeId(int streetNode, int ptNode) { this.streetNode = streetNode; this.ptNode = ptNode; } public int streetNode; public int ptNode; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeId nodeId = (NodeId) o; return streetNode == nodeId.streetNode && ptNode == nodeId.ptNode; } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { return "NodeId{" + "streetNode=" + streetNode + ", ptNode=" + ptNode + '}'; } }
int result = 1; result = 31 * result + streetNode; result = 31 * result + ptNode; return result;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/Label.java
NodeId
toString
class NodeId { public NodeId(int streetNode, int ptNode) { this.streetNode = streetNode; this.ptNode = ptNode; } public int streetNode; public int ptNode; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeId nodeId = (NodeId) o; return streetNode == nodeId.streetNode && ptNode == nodeId.ptNode; } @Override public int hashCode() { int result = 1; result = 31 * result + streetNode; result = 31 * result + ptNode; return result; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "NodeId{" + "streetNode=" + streetNode + ", ptNode=" + ptNode + '}';
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/PtLocationSnapper.java
Result
snapAll
class Result { public final QueryGraph queryGraph; public final List<Label.NodeId> nodes; public final PointList points; public Result(QueryGraph queryGraph, List<Label.NodeId> nodes, PointList points) { this.queryGraph = queryGraph; this.nodes = nodes; this.points = points; } } BaseGraph baseGraph; LocationIndex locationIndex; GtfsStorage gtfsStorage; public PtLocationSnapper(BaseGraph baseGraph, LocationIndex locationIndex, GtfsStorage gtfsStorage) { this.baseGraph = baseGraph; this.locationIndex = locationIndex; this.gtfsStorage = gtfsStorage; } public Result snapAll(List<GHLocation> locations, List<EdgeFilter> snapFilters) {<FILL_FUNCTION_BODY>
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(gtfsStorage.getPtToStreet().getOrDefault(stopSnap.getClosestNode(), -1), stopSnap.getClosestNode())); points.add(stopSnap.getQueryPoint().lat, stopSnap.getQueryPoint().lon); } } } else { pointSnaps.add(closest); allSnaps.add(() -> new Label.NodeId(closest.getClosestNode(), gtfsStorage.getStreetToPt().getOrDefault(closest.getClosestNode(), -1))); points.add(closest.getSnappedPoint()); } } else if (location instanceof GHStationLocation) { final Snap stopSnap = findByStopId((GHStationLocation) location, i); allSnaps.add(() -> new Label.NodeId(gtfsStorage.getPtToStreet().getOrDefault(stopSnap.getClosestNode(), -1), stopSnap.getClosestNode())); points.add(stopSnap.getQueryPoint().lat, stopSnap.getQueryPoint().lon); } } QueryGraph queryGraph = QueryGraph.create(baseGraph.getBaseGraph(), pointSnaps); // modifies pointSnaps! List<Label.NodeId> nodes = new ArrayList<>(); for (Supplier<Label.NodeId> supplier : allSnaps) { nodes.add(supplier.get()); } return new Result(queryGraph, nodes, points);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/PtLocationSnapper.java
Result
findByStopId
class Result { public final QueryGraph queryGraph; public final List<Label.NodeId> nodes; public final PointList points; public Result(QueryGraph queryGraph, List<Label.NodeId> nodes, PointList points) { this.queryGraph = queryGraph; this.nodes = nodes; this.points = points; } } BaseGraph baseGraph; LocationIndex locationIndex; GtfsStorage gtfsStorage; public PtLocationSnapper(BaseGraph baseGraph, LocationIndex locationIndex, GtfsStorage gtfsStorage) { this.baseGraph = baseGraph; this.locationIndex = locationIndex; this.gtfsStorage = gtfsStorage; } 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(gtfsStorage.getPtToStreet().getOrDefault(stopSnap.getClosestNode(), -1), stopSnap.getClosestNode())); points.add(stopSnap.getQueryPoint().lat, stopSnap.getQueryPoint().lon); } } } else { pointSnaps.add(closest); allSnaps.add(() -> new Label.NodeId(closest.getClosestNode(), gtfsStorage.getStreetToPt().getOrDefault(closest.getClosestNode(), -1))); points.add(closest.getSnappedPoint()); } } else if (location instanceof GHStationLocation) { final Snap stopSnap = findByStopId((GHStationLocation) location, i); allSnaps.add(() -> new Label.NodeId(gtfsStorage.getPtToStreet().getOrDefault(stopSnap.getClosestNode(), -1), stopSnap.getClosestNode())); points.add(stopSnap.getQueryPoint().lat, stopSnap.getQueryPoint().lon); } } QueryGraph queryGraph = QueryGraph.create(baseGraph.getBaseGraph(), pointSnaps); // modifies pointSnaps! List<Label.NodeId> nodes = new ArrayList<>(); for (Supplier<Label.NodeId> supplier : allSnaps) { nodes.add(supplier.get()); } return new Result(queryGraph, nodes, points); } private Snap findByStopId(GHStationLocation station, int indexForErrorMessage) {<FILL_FUNCTION_BODY>
for (Map.Entry<String, GTFSFeed> entry : gtfsStorage.getGtfsFeeds().entrySet()) { final Integer node = gtfsStorage.getStationNodes().get(new GtfsStorage.FeedIdWithStopId(entry.getKey(), station.stop_id)); if (node != null) { Stop stop = gtfsStorage.getGtfsFeeds().get(entry.getKey()).stops.get(station.stop_id); final Snap stationSnap = new Snap(stop.stop_lat, stop.stop_lon); stationSnap.setClosestNode(node); return stationSnap; } } throw new PointNotFoundException("Cannot find station: " + station.stop_id, indexForErrorMessage);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/fare/TicketPurchaseScoreCalculator.java
TempTicket
calculateScore
class TempTicket { String feed_id; Fare fare; int totalNumber = 0; long validUntil; int nMoreTransfers = 0; } double calculateScore(TicketPurchase ticketPurchase) {<FILL_FUNCTION_BODY>
double cost = 0; for (Ticket ticket : ticketPurchase.getTickets()) { cost -= ticket.getFare().fare_attribute.price; } return cost - ticketPurchase.getNSchwarzfahrTrips() * 60.0;
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
main
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) {<FILL_FUNCTION_BODY>} public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60); } }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) { clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() { return true; } @Override public void onTile(BBox bbox, int depth) { int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width); } @Override public void onEdge(int edgeId) { // mg.plotNode(g2, node, Color.BLUE); } }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK); } }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) { if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3); } }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) { Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); } } private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize();
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
paintComponent
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) { PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize(); } public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) {<FILL_FUNCTION_BODY>} }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) { clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() { return true; } @Override public void onTile(BBox bbox, int depth) { int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width); } @Override public void onEdge(int edgeId) { // mg.plotNode(g2, node, Color.BLUE); } }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK); } }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) { if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3); } }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) { Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); } } private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
paintComponent
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) { PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize(); } public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60); } }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) {<FILL_FUNCTION_BODY>} }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) { if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3); } }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) { Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); } } private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() { return true; } @Override public void onTile(BBox bbox, int depth) { int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width); } @Override public void onEdge(int edgeId) { // mg.plotNode(g2, node, Color.BLUE); } }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
isTileInfo
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) { PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize(); } public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60); } }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) { clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() {<FILL_FUNCTION_BODY>} @Override public void onTile(BBox bbox, int depth) { int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width); } @Override public void onEdge(int edgeId) { // mg.plotNode(g2, node, Color.BLUE); } }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK); } }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) { if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3); } }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) { Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); } } private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
return true;
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
onTile
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) { PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize(); } public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60); } }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) { clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() { return true; } @Override public void onTile(BBox bbox, int depth) {<FILL_FUNCTION_BODY>} @Override public void onEdge(int edgeId) { // mg.plotNode(g2, node, Color.BLUE); } }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK); } }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) { if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3); } }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) { Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); } } private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
onEdge
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) { PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize(); } public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60); } }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) { clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() { return true; } @Override public void onTile(BBox bbox, int depth) { int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width); } @Override public void onEdge(int edgeId) {<FILL_FUNCTION_BODY>} }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK); } }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) { if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3); } }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) { Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); } } private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
// mg.plotNode(g2, node, Color.BLUE);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
paintComponent
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) { PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize(); } public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60); } }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) { clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() { return true; } @Override public void onTile(BBox bbox, int depth) { int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width); } @Override public void onEdge(int edgeId) { // mg.plotNode(g2, node, Color.BLUE); } }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK); } }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) {<FILL_FUNCTION_BODY>} }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) { Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); } } private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
createAlgo
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) { PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize(); } public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60); } }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) { clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() { return true; } @Override public void onTile(BBox bbox, int depth) { int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width); } @Override public void onEdge(int edgeId) { // mg.plotNode(g2, node, Color.BLUE); } }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK); } }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) { if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3); } }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) {<FILL_FUNCTION_BODY>} private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); }
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
setGraphics2D
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) {<FILL_FUNCTION_BODY>} @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } }
this.g2 = g2;
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
updateBestPath
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) {<FILL_FUNCTION_BODY>} }
if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
generateColors
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) {<FILL_FUNCTION_BODY>
Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols;
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
plotNodeName
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) {<FILL_FUNCTION_BODY>
double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
plotPath
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) {<FILL_FUNCTION_BODY>
if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath;
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
visualize
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() {<FILL_FUNCTION_BODY>
try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); }
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
run
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() {<FILL_FUNCTION_BODY>
int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
mouseWheelMoved
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) {<FILL_FUNCTION_BODY>
mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads();
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
mouseClicked
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) {<FILL_FUNCTION_BODY>
if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone;
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
mouseDragged
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) {<FILL_FUNCTION_BODY>
dragging = true; fastPaint = true; update(e); updateLatLon(e);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
mouseReleased
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) {<FILL_FUNCTION_BODY>
if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); }
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
update
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) {<FILL_FUNCTION_BODY>
mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads();
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
mouseMoved
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) {<FILL_FUNCTION_BODY>
updateLatLon(e);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
mousePressed
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) {<FILL_FUNCTION_BODY>
updateLatLon(e);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
updateLatLon
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) {<FILL_FUNCTION_BODY>
latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY();
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
repaintPaths
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() {<FILL_FUNCTION_BODY>
pathLayer.repaint(); mainPanel.repaint();
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
CHDebugAlgo
repaintRoads
class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() {<FILL_FUNCTION_BODY>
// avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec");
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
TranslationMapFactory
provide
class TranslationMapFactory implements Factory<TranslationMap> { @Inject GraphHopper graphHopper; @Override public TranslationMap provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(TranslationMap instance) { } }
return graphHopper.getTranslationMap();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
TranslationMapFactory
dispose
class TranslationMapFactory implements Factory<TranslationMap> { @Inject GraphHopper graphHopper; @Override public TranslationMap provide() { return graphHopper.getTranslationMap(); } @Override public void dispose(TranslationMap instance) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
BaseGraphFactory
provide
class BaseGraphFactory implements Factory<BaseGraph> { @Inject GraphHopper graphHopper; @Override public BaseGraph provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(BaseGraph instance) { } }
return graphHopper.getBaseGraph();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
BaseGraphFactory
dispose
class BaseGraphFactory implements Factory<BaseGraph> { @Inject GraphHopper graphHopper; @Override public BaseGraph provide() { return graphHopper.getBaseGraph(); } @Override public void dispose(BaseGraph instance) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
GtfsStorageFactory
provide
class GtfsStorageFactory implements Factory<GtfsStorage> { @Inject GraphHopperGtfs graphHopper; @Override public GtfsStorage provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(GtfsStorage instance) { } }
return graphHopper.getGtfsStorage();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
GtfsStorageFactory
dispose
class GtfsStorageFactory implements Factory<GtfsStorage> { @Inject GraphHopperGtfs graphHopper; @Override public GtfsStorage provide() { return graphHopper.getGtfsStorage(); } @Override public void dispose(GtfsStorage instance) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
EncodingManagerFactory
provide
class EncodingManagerFactory implements Factory<EncodingManager> { @Inject GraphHopper graphHopper; @Override public EncodingManager provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(EncodingManager instance) { } }
return graphHopper.getEncodingManager();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
EncodingManagerFactory
dispose
class EncodingManagerFactory implements Factory<EncodingManager> { @Inject GraphHopper graphHopper; @Override public EncodingManager provide() { return graphHopper.getEncodingManager(); } @Override public void dispose(EncodingManager instance) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
LocationIndexFactory
provide
class LocationIndexFactory implements Factory<LocationIndex> { @Inject GraphHopper graphHopper; @Override public LocationIndex provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(LocationIndex instance) { } }
return graphHopper.getLocationIndex();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
LocationIndexFactory
dispose
class LocationIndexFactory implements Factory<LocationIndex> { @Inject GraphHopper graphHopper; @Override public LocationIndex provide() { return graphHopper.getLocationIndex(); } @Override public void dispose(LocationIndex instance) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
ProfileResolverFactory
provide
class ProfileResolverFactory implements Factory<ProfileResolver> { @Inject GraphHopper graphHopper; @Override public ProfileResolver provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(ProfileResolver instance) { } }
return new ProfileResolver(graphHopper.getProfiles());
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
ProfileResolverFactory
dispose
class ProfileResolverFactory implements Factory<ProfileResolver> { @Inject GraphHopper graphHopper; @Override public ProfileResolver provide() { return new ProfileResolver(graphHopper.getProfiles()); } @Override public void dispose(ProfileResolver instance) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
GHRequestTransformerFactory
provide
class GHRequestTransformerFactory implements Factory<GHRequestTransformer> { @Override public GHRequestTransformer provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(GHRequestTransformer instance) { } }
return req -> req;
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
GHRequestTransformerFactory
dispose
class GHRequestTransformerFactory implements Factory<GHRequestTransformer> { @Override public GHRequestTransformer provide() { return req -> req; } @Override public void dispose(GHRequestTransformer instance) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
PathDetailsBuilderFactoryFactory
provide
class PathDetailsBuilderFactoryFactory implements Factory<PathDetailsBuilderFactory> { @Inject GraphHopper graphHopper; @Override public PathDetailsBuilderFactory provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(PathDetailsBuilderFactory profileResolver) { } }
return graphHopper.getPathDetailsBuilderFactory();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
PathDetailsBuilderFactoryFactory
dispose
class PathDetailsBuilderFactoryFactory implements Factory<PathDetailsBuilderFactory> { @Inject GraphHopper graphHopper; @Override public PathDetailsBuilderFactory provide() { return graphHopper.getPathDetailsBuilderFactory(); } @Override public void dispose(PathDetailsBuilderFactory profileResolver) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
MapMatchingRouterFactoryFactory
provide
class MapMatchingRouterFactoryFactory implements Factory<MapMatchingResource.MapMatchingRouterFactory> { @Inject GraphHopper graphHopper; @Override public MapMatchingResource.MapMatchingRouterFactory provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(MapMatchingResource.MapMatchingRouterFactory mapMatchingRouterFactory) { } }
return new MapMatchingResource.MapMatchingRouterFactory() { @Override public MapMatching.Router createMapMatchingRouter(PMap hints) { return MapMatching.routerFromGraphHopper(graphHopper, hints); } };
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
MapMatchingRouterFactoryFactory
createMapMatchingRouter
class MapMatchingRouterFactoryFactory implements Factory<MapMatchingResource.MapMatchingRouterFactory> { @Inject GraphHopper graphHopper; @Override public MapMatchingResource.MapMatchingRouterFactory provide() { return new MapMatchingResource.MapMatchingRouterFactory() { @Override public MapMatching.Router createMapMatchingRouter(PMap hints) {<FILL_FUNCTION_BODY>} }; } @Override public void dispose(MapMatchingResource.MapMatchingRouterFactory mapMatchingRouterFactory) { } }
return MapMatching.routerFromGraphHopper(graphHopper, hints);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
MapMatchingRouterFactoryFactory
dispose
class MapMatchingRouterFactoryFactory implements Factory<MapMatchingResource.MapMatchingRouterFactory> { @Inject GraphHopper graphHopper; @Override public MapMatchingResource.MapMatchingRouterFactory provide() { return new MapMatchingResource.MapMatchingRouterFactory() { @Override public MapMatching.Router createMapMatchingRouter(PMap hints) { return MapMatching.routerFromGraphHopper(graphHopper, hints); } }; } @Override public void dispose(MapMatchingResource.MapMatchingRouterFactory mapMatchingRouterFactory) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
HasElevation
provide
class HasElevation implements Factory<Boolean> { @Inject GraphHopper graphHopper; @Override public Boolean provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(Boolean instance) { } }
return graphHopper.hasElevation();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
HasElevation
dispose
class HasElevation implements Factory<Boolean> { @Inject GraphHopper graphHopper; @Override public Boolean provide() { return graphHopper.hasElevation(); } @Override public void dispose(Boolean instance) {<FILL_FUNCTION_BODY>} }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
HasElevation
initialize
class HasElevation implements Factory<Boolean> { @Inject GraphHopper graphHopper; @Override public Boolean provide() { return graphHopper.hasElevation(); } @Override public void dispose(Boolean instance) { } } @Override public void initialize(Bootstrap<?> bootstrap) {<FILL_FUNCTION_BODY>
// See #1440: avoids warning regarding com.fasterxml.jackson.module.afterburner.util.MyClassLoader bootstrap.setObjectMapper(io.dropwizard.jackson.Jackson.newMinimalObjectMapper()); // avoids warning regarding com.fasterxml.jackson.databind.util.ClassUtil bootstrap.getObjectMapper().registerModule(new Jdk8Module()); Jackson.initObjectMapper(bootstrap.getObjectMapper()); bootstrap.getObjectMapper().setDateFormat(new StdDateFormat()); // See https://github.com/dropwizard/dropwizard/issues/1558 bootstrap.getObjectMapper().enable(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
HasElevation
run
class HasElevation implements Factory<Boolean> { @Inject GraphHopper graphHopper; @Override public Boolean provide() { return graphHopper.hasElevation(); } @Override public void dispose(Boolean instance) { } } @Override public void initialize(Bootstrap<?> bootstrap) { // See #1440: avoids warning regarding com.fasterxml.jackson.module.afterburner.util.MyClassLoader bootstrap.setObjectMapper(io.dropwizard.jackson.Jackson.newMinimalObjectMapper()); // avoids warning regarding com.fasterxml.jackson.databind.util.ClassUtil bootstrap.getObjectMapper().registerModule(new Jdk8Module()); Jackson.initObjectMapper(bootstrap.getObjectMapper()); bootstrap.getObjectMapper().setDateFormat(new StdDateFormat()); // See https://github.com/dropwizard/dropwizard/issues/1558 bootstrap.getObjectMapper().enable(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING); } @Override public void run(GraphHopperBundleConfiguration configuration, Environment environment) {<FILL_FUNCTION_BODY>
for (Object k : System.getProperties().keySet()) { if (k instanceof String && ((String) k).startsWith("graphhopper.")) throw new IllegalArgumentException("You need to prefix system parameters with '-Ddw.graphhopper.' instead of '-Dgraphhopper.' see #1879 and #1897"); } // When Dropwizard's Hibernate Validation misvalidates a query parameter, // a JerseyViolationException is thrown. // With this mapper, we use our custom format for that (backwards compatibility), // and also coerce the media type of the response to JSON, so we can return JSON error // messages from methods that normally have a different return type. // That's questionable, but on the other hand, Dropwizard itself does the same thing, // not here, but in a different place (the custom parameter parsers). // So for the moment we have to assume that both mechanisms // a) always return JSON error messages, and // b) there's no need to annotate the method with media type JSON for that. // // However, for places that throw IllegalArgumentException or MultiException, // we DO need to use the media type JSON annotation, because // those are agnostic to the media type (could be GPX!), so the server needs to know // that a JSON error response is supported. (See below.) environment.jersey().register(new GHJerseyViolationExceptionMapper()); // If the "?type=gpx" parameter is present, sets a corresponding media type header environment.jersey().register(new TypeGPXFilter()); // Together, these two take care that MultiExceptions thrown from RouteResource // come out as JSON or GPX, depending on the media type environment.jersey().register(new MultiExceptionMapper()); environment.jersey().register(new MultiExceptionGPXMessageBodyWriter()); // This makes an IllegalArgumentException come out as a MultiException with // a single entry. environment.jersey().register(new IllegalArgumentExceptionMapper()); final GraphHopperManaged graphHopperManaged = new GraphHopperManaged(configuration.getGraphHopperConfiguration()); environment.lifecycle().manage(graphHopperManaged); final GraphHopper graphHopper = graphHopperManaged.getGraphHopper(); environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(configuration.getGraphHopperConfiguration()).to(GraphHopperConfig.class); bind(graphHopper).to(GraphHopper.class); bind(new JTSTriangulator(graphHopper.getRouterConfig())).to(Triangulator.class); bindFactory(MapMatchingRouterFactoryFactory.class).to(MapMatchingResource.MapMatchingRouterFactory.class); bindFactory(PathDetailsBuilderFactoryFactory.class).to(PathDetailsBuilderFactory.class); bindFactory(ProfileResolverFactory.class).to(ProfileResolver.class); bindFactory(GHRequestTransformerFactory.class).to(GHRequestTransformer.class); bindFactory(HasElevation.class).to(Boolean.class).named("hasElevation"); bindFactory(LocationIndexFactory.class).to(LocationIndex.class); bindFactory(TranslationMapFactory.class).to(TranslationMap.class); bindFactory(EncodingManagerFactory.class).to(EncodingManager.class); bindFactory(BaseGraphFactory.class).to(BaseGraph.class); bindFactory(GtfsStorageFactory.class).to(GtfsStorage.class); } }); environment.jersey().register(MVTResource.class); environment.jersey().register(NearestResource.class); environment.jersey().register(RouteResource.class); environment.jersey().register(IsochroneResource.class); environment.jersey().register(MapMatchingResource.class); if (configuration.getGraphHopperConfiguration().has("gtfs.file")) { // These are pt-specific implementations of /route and /isochrone, but the same API. // We serve them under different paths (/route-pt and /isochrone-pt), and forward // requests for ?vehicle=pt there. environment.jersey().register(new AbstractBinder() { @Override protected void configure() { if (configuration.getGraphHopperConfiguration().getBool("gtfs.free_walk", false)) { bind(PtRouterFreeWalkImpl.class).to(PtRouter.class); } else { bind(PtRouterImpl.class).to(PtRouter.class); } } }); environment.jersey().register(PtRouteResource.class); environment.jersey().register(PtIsochroneResource.class); environment.jersey().register(PtMVTResource.class); environment.jersey().register(PtRedirectFilter.class); } environment.jersey().register(SPTResource.class); environment.jersey().register(I18NResource.class); environment.jersey().register(InfoResource.class); environment.healthChecks().register("graphhopper", new GraphHopperHealthCheck(graphHopper)); environment.jersey().register(environment.healthChecks()); environment.jersey().register(HealthCheckResource.class);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
HasElevation
configure
class HasElevation implements Factory<Boolean> { @Inject GraphHopper graphHopper; @Override public Boolean provide() { return graphHopper.hasElevation(); } @Override public void dispose(Boolean instance) { } } @Override public void initialize(Bootstrap<?> bootstrap) { // See #1440: avoids warning regarding com.fasterxml.jackson.module.afterburner.util.MyClassLoader bootstrap.setObjectMapper(io.dropwizard.jackson.Jackson.newMinimalObjectMapper()); // avoids warning regarding com.fasterxml.jackson.databind.util.ClassUtil bootstrap.getObjectMapper().registerModule(new Jdk8Module()); Jackson.initObjectMapper(bootstrap.getObjectMapper()); bootstrap.getObjectMapper().setDateFormat(new StdDateFormat()); // See https://github.com/dropwizard/dropwizard/issues/1558 bootstrap.getObjectMapper().enable(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING); } @Override public void run(GraphHopperBundleConfiguration configuration, Environment environment) { for (Object k : System.getProperties().keySet()) { if (k instanceof String && ((String) k).startsWith("graphhopper.")) throw new IllegalArgumentException("You need to prefix system parameters with '-Ddw.graphhopper.' instead of '-Dgraphhopper.' see #1879 and #1897"); } // When Dropwizard's Hibernate Validation misvalidates a query parameter, // a JerseyViolationException is thrown. // With this mapper, we use our custom format for that (backwards compatibility), // and also coerce the media type of the response to JSON, so we can return JSON error // messages from methods that normally have a different return type. // That's questionable, but on the other hand, Dropwizard itself does the same thing, // not here, but in a different place (the custom parameter parsers). // So for the moment we have to assume that both mechanisms // a) always return JSON error messages, and // b) there's no need to annotate the method with media type JSON for that. // // However, for places that throw IllegalArgumentException or MultiException, // we DO need to use the media type JSON annotation, because // those are agnostic to the media type (could be GPX!), so the server needs to know // that a JSON error response is supported. (See below.) environment.jersey().register(new GHJerseyViolationExceptionMapper()); // If the "?type=gpx" parameter is present, sets a corresponding media type header environment.jersey().register(new TypeGPXFilter()); // Together, these two take care that MultiExceptions thrown from RouteResource // come out as JSON or GPX, depending on the media type environment.jersey().register(new MultiExceptionMapper()); environment.jersey().register(new MultiExceptionGPXMessageBodyWriter()); // This makes an IllegalArgumentException come out as a MultiException with // a single entry. environment.jersey().register(new IllegalArgumentExceptionMapper()); final GraphHopperManaged graphHopperManaged = new GraphHopperManaged(configuration.getGraphHopperConfiguration()); environment.lifecycle().manage(graphHopperManaged); final GraphHopper graphHopper = graphHopperManaged.getGraphHopper(); environment.jersey().register(new AbstractBinder() { @Override protected void configure() {<FILL_FUNCTION_BODY>
bind(configuration.getGraphHopperConfiguration()).to(GraphHopperConfig.class); bind(graphHopper).to(GraphHopper.class); bind(new JTSTriangulator(graphHopper.getRouterConfig())).to(Triangulator.class); bindFactory(MapMatchingRouterFactoryFactory.class).to(MapMatchingResource.MapMatchingRouterFactory.class); bindFactory(PathDetailsBuilderFactoryFactory.class).to(PathDetailsBuilderFactory.class); bindFactory(ProfileResolverFactory.class).to(ProfileResolver.class); bindFactory(GHRequestTransformerFactory.class).to(GHRequestTransformer.class); bindFactory(HasElevation.class).to(Boolean.class).named("hasElevation"); bindFactory(LocationIndexFactory.class).to(LocationIndex.class); bindFactory(TranslationMapFactory.class).to(TranslationMap.class); bindFactory(EncodingManagerFactory.class).to(EncodingManager.class); bindFactory(BaseGraphFactory.class).to(BaseGraph.class); bindFactory(GtfsStorageFactory.class).to(GtfsStorage.class);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
HasElevation
configure
class HasElevation implements Factory<Boolean> { @Inject GraphHopper graphHopper; @Override public Boolean provide() { return graphHopper.hasElevation(); } @Override public void dispose(Boolean instance) { } } @Override public void initialize(Bootstrap<?> bootstrap) { // See #1440: avoids warning regarding com.fasterxml.jackson.module.afterburner.util.MyClassLoader bootstrap.setObjectMapper(io.dropwizard.jackson.Jackson.newMinimalObjectMapper()); // avoids warning regarding com.fasterxml.jackson.databind.util.ClassUtil bootstrap.getObjectMapper().registerModule(new Jdk8Module()); Jackson.initObjectMapper(bootstrap.getObjectMapper()); bootstrap.getObjectMapper().setDateFormat(new StdDateFormat()); // See https://github.com/dropwizard/dropwizard/issues/1558 bootstrap.getObjectMapper().enable(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING); } @Override public void run(GraphHopperBundleConfiguration configuration, Environment environment) { for (Object k : System.getProperties().keySet()) { if (k instanceof String && ((String) k).startsWith("graphhopper.")) throw new IllegalArgumentException("You need to prefix system parameters with '-Ddw.graphhopper.' instead of '-Dgraphhopper.' see #1879 and #1897"); } // When Dropwizard's Hibernate Validation misvalidates a query parameter, // a JerseyViolationException is thrown. // With this mapper, we use our custom format for that (backwards compatibility), // and also coerce the media type of the response to JSON, so we can return JSON error // messages from methods that normally have a different return type. // That's questionable, but on the other hand, Dropwizard itself does the same thing, // not here, but in a different place (the custom parameter parsers). // So for the moment we have to assume that both mechanisms // a) always return JSON error messages, and // b) there's no need to annotate the method with media type JSON for that. // // However, for places that throw IllegalArgumentException or MultiException, // we DO need to use the media type JSON annotation, because // those are agnostic to the media type (could be GPX!), so the server needs to know // that a JSON error response is supported. (See below.) environment.jersey().register(new GHJerseyViolationExceptionMapper()); // If the "?type=gpx" parameter is present, sets a corresponding media type header environment.jersey().register(new TypeGPXFilter()); // Together, these two take care that MultiExceptions thrown from RouteResource // come out as JSON or GPX, depending on the media type environment.jersey().register(new MultiExceptionMapper()); environment.jersey().register(new MultiExceptionGPXMessageBodyWriter()); // This makes an IllegalArgumentException come out as a MultiException with // a single entry. environment.jersey().register(new IllegalArgumentExceptionMapper()); final GraphHopperManaged graphHopperManaged = new GraphHopperManaged(configuration.getGraphHopperConfiguration()); environment.lifecycle().manage(graphHopperManaged); final GraphHopper graphHopper = graphHopperManaged.getGraphHopper(); environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(configuration.getGraphHopperConfiguration()).to(GraphHopperConfig.class); bind(graphHopper).to(GraphHopper.class); bind(new JTSTriangulator(graphHopper.getRouterConfig())).to(Triangulator.class); bindFactory(MapMatchingRouterFactoryFactory.class).to(MapMatchingResource.MapMatchingRouterFactory.class); bindFactory(PathDetailsBuilderFactoryFactory.class).to(PathDetailsBuilderFactory.class); bindFactory(ProfileResolverFactory.class).to(ProfileResolver.class); bindFactory(GHRequestTransformerFactory.class).to(GHRequestTransformer.class); bindFactory(HasElevation.class).to(Boolean.class).named("hasElevation"); bindFactory(LocationIndexFactory.class).to(LocationIndex.class); bindFactory(TranslationMapFactory.class).to(TranslationMap.class); bindFactory(EncodingManagerFactory.class).to(EncodingManager.class); bindFactory(BaseGraphFactory.class).to(BaseGraph.class); bindFactory(GtfsStorageFactory.class).to(GtfsStorage.class); } }); environment.jersey().register(MVTResource.class); environment.jersey().register(NearestResource.class); environment.jersey().register(RouteResource.class); environment.jersey().register(IsochroneResource.class); environment.jersey().register(MapMatchingResource.class); if (configuration.getGraphHopperConfiguration().has("gtfs.file")) { // These are pt-specific implementations of /route and /isochrone, but the same API. // We serve them under different paths (/route-pt and /isochrone-pt), and forward // requests for ?vehicle=pt there. environment.jersey().register(new AbstractBinder() { @Override protected void configure() {<FILL_FUNCTION_BODY>
if (configuration.getGraphHopperConfiguration().getBool("gtfs.free_walk", false)) { bind(PtRouterFreeWalkImpl.class).to(PtRouter.class); } else { bind(PtRouterImpl.class).to(PtRouter.class); }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/I18NResource.java
Response
getFromHeader
class Response { public String locale; public Map<String, String> en; @JsonProperty("default") public Map<String, String> defaultTr; } @GET public Response getFromHeader(@HeaderParam("Accept-Language") String acceptLang) {<FILL_FUNCTION_BODY>
if (acceptLang == null) return get(""); return get(acceptLang.split(",")[0]);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/I18NResource.java
Response
get
class Response { public String locale; public Map<String, String> en; @JsonProperty("default") public Map<String, String> defaultTr; } @GET public Response getFromHeader(@HeaderParam("Accept-Language") String acceptLang) { if (acceptLang == null) return get(""); return get(acceptLang.split(",")[0]); } @GET @Path("/{locale}") public Response get(@PathParam("locale") String locale) {<FILL_FUNCTION_BODY>
Translation tr = map.get(locale); Response json = new Response(); if (tr != null && !Locale.US.equals(tr.getLocale())) { json.defaultTr = tr.asMap(); } json.locale = locale; json.en = map.get("en").asMap(); return json;
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/InfoResource.java
ProfileData
getInfo
class ProfileData { // for deserialization in e.g. tests public ProfileData() { } public ProfileData(String name) { this.name = name; } public String name; } public Envelope bbox; public final List<ProfileData> profiles = new ArrayList<>(); public String version = Constants.VERSION; public boolean elevation; public Map<String, List<Object>> encoded_values; public String import_date; public String data_date; } @GET public Info getInfo() {<FILL_FUNCTION_BODY>
final Info info = new Info(); info.bbox = new Envelope(baseGraph.getBounds().minLon, baseGraph.getBounds().maxLon, baseGraph.getBounds().minLat, baseGraph.getBounds().maxLat); for (Profile p : config.getProfiles()) { Info.ProfileData profileData = new Info.ProfileData(p.getName()); info.profiles.add(profileData); } if (config.has("gtfs.file")) info.profiles.add(new Info.ProfileData("pt")); info.elevation = hasElevation; info.import_date = properties.get("datareader.import.date"); info.data_date = properties.get("datareader.data.date"); List<EncodedValue> evList = encodingManager.getEncodedValues(); info.encoded_values = new LinkedHashMap<>(); for (EncodedValue encodedValue : evList) { List<Object> possibleValueList = new ArrayList<>(); String name = encodedValue.getName(); if (privateEV.contains(name)) { continue; } else if (encodedValue instanceof EnumEncodedValue) { for (Enum o : ((EnumEncodedValue) encodedValue).getValues()) { possibleValueList.add(o.name()); } } else if (encodedValue instanceof BooleanEncodedValue) { possibleValueList.add("true"); possibleValueList.add("false"); } else if (encodedValue instanceof DecimalEncodedValue || encodedValue instanceof IntEncodedValue) { possibleValueList.add(">number"); possibleValueList.add("<number"); } else { // we only add enum, boolean and numeric encoded values to the list continue; } info.encoded_values.put(name, possibleValueList); } return info;
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/NearestResource.java
Response
doGet
class Response { public final String type = "Point"; public final double[] coordinates; public final double distance; // Distance from input to snapped point in meters @JsonCreator Response(@JsonProperty("coordinates") double[] coordinates, @JsonProperty("distance") double distance) { this.coordinates = coordinates; this.distance = distance; } } @GET public Response doGet(@QueryParam("point") GHPoint point, @QueryParam("elevation") @DefaultValue("false") boolean elevation) {<FILL_FUNCTION_BODY>
Snap snap = index.findClosest(point.lat, point.lon, EdgeFilter.ALL_EDGES); if (snap.isValid()) { GHPoint3D snappedPoint = snap.getSnappedPoint(); double[] coordinates = hasElevation && elevation ? new double[]{snappedPoint.lon, snappedPoint.lat, snappedPoint.ele} : new double[]{snappedPoint.lon, snappedPoint.lat}; return new Response(coordinates, calc.calcDist(point.lat, point.lon, snappedPoint.lat, snappedPoint.lon)); } else { throw new WebApplicationException("Nearest point cannot be found!"); }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/PtIsochroneResource.java
Info
doGet
class Info { public List<String> copyrights = new ArrayList<>(); } public List<JsonFeature> polygons = new ArrayList<>(); public Info info = new Info(); } @GET @Produces({MediaType.APPLICATION_JSON}) public Response doGet( @QueryParam("point") GHLocationParam sourceParam, @QueryParam("time_limit") @DefaultValue("600") long seconds, @QueryParam("reverse_flow") @DefaultValue("false") boolean reverseFlow, @QueryParam("pt.earliest_departure_time") @NotNull OffsetDateTimeParam departureTimeParam, @QueryParam("pt.blocked_route_types") @DefaultValue("0") int blockedRouteTypes, @QueryParam("result") @DefaultValue("multipolygon") String format) {<FILL_FUNCTION_BODY>
Instant initialTime = departureTimeParam.get().toInstant(); GHLocation location = sourceParam.get(); double targetZ = seconds * 1000; GeometryFactory geometryFactory = new GeometryFactory(); CustomModel customModel = new CustomModel() .addToPriority(Statement.If("!" + VehicleAccess.key("foot"), Statement.Op.MULTIPLY, "0")) .addToSpeed(Statement.If("true", Statement.Op.LIMIT, VehicleSpeed.key("foot"))); final Weighting weighting = CustomModelParser.createWeighting(encodingManager, TurnCostProvider.NO_TURN_COST_PROVIDER, customModel); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, encodingManager.getBooleanEncodedValue(Subnetwork.key("foot"))); PtLocationSnapper.Result snapResult = new PtLocationSnapper(baseGraph, locationIndex, gtfsStorage).snapAll(Arrays.asList(location), Arrays.asList(snapFilter)); GraphExplorer graphExplorer = new GraphExplorer(snapResult.queryGraph, gtfsStorage.getPtGraph(), weighting, gtfsStorage, RealtimeFeed.empty(), reverseFlow, false, false, 5.0, reverseFlow, blockedRouteTypes); MultiCriteriaLabelSetting router = new MultiCriteriaLabelSetting(graphExplorer, reverseFlow, false, false, 0, Collections.emptyList()); Map<Coordinate, Double> z1 = new HashMap<>(); NodeAccess nodeAccess = snapResult.queryGraph.getNodeAccess(); for (Label label : router.calcLabels(snapResult.nodes.get(0), initialTime)) { if (!((label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1) <= targetZ)) { break; } if (label.node.streetNode != -1) { Coordinate nodeCoordinate = new Coordinate(nodeAccess.getLon(label.node.streetNode), nodeAccess.getLat(label.node.streetNode)); z1.merge(nodeCoordinate, (double) (label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1), Math::min); } else if (label.edge != null && (label.edge.getType() == GtfsStorage.EdgeType.EXIT_PT || label.edge.getType() == GtfsStorage.EdgeType.ENTER_PT)) { GtfsStorage.PlatformDescriptor platformDescriptor = label.edge.getPlatformDescriptor(); Stop stop = gtfsStorage.getGtfsFeeds().get(platformDescriptor.feed_id).stops.get(platformDescriptor.stop_id); Coordinate nodeCoordinate = new Coordinate(stop.stop_lon, stop.stop_lat); z1.merge(nodeCoordinate, (double) (label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1), Math::min); } } if (format.equals("multipoint")) { MultiPoint exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); return wrap(exploredPoints); } else { MultiPoint exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); // Get at least all nodes within our bounding box (I think convex hull would be enough.) // I think then we should have all possible encroaching points. (Proof needed.) locationIndex.query(BBox.fromEnvelope(exploredPoints.getEnvelopeInternal()), edgeId -> { EdgeIteratorState edge = snapResult.queryGraph.getEdgeIteratorStateForKey(edgeId * 2); z1.merge(new Coordinate(nodeAccess.getLon(edge.getBaseNode()), nodeAccess.getLat(edge.getBaseNode())), Double.MAX_VALUE, Math::min); z1.merge(new Coordinate(nodeAccess.getLon(edge.getAdjNode()), nodeAccess.getLat(edge.getAdjNode())), Double.MAX_VALUE, Math::min); }); exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); CoordinateList siteCoords = DelaunayTriangulationBuilder.extractUniqueCoordinates(exploredPoints); List<ConstraintVertex> constraintVertices = new ArrayList<>(); for (Object siteCoord : siteCoords) { Coordinate coord = (Coordinate) siteCoord; constraintVertices.add(new ConstraintVertex(coord)); } ConformingDelaunayTriangulator cdt = new ConformingDelaunayTriangulator(constraintVertices, JTS_TOLERANCE); cdt.setConstraints(new ArrayList(), new ArrayList()); cdt.formInitialDelaunay(); QuadEdgeSubdivision tin = cdt.getSubdivision(); for (Vertex vertex : (Collection<Vertex>) tin.getVertices(true)) { if (tin.isFrameVertex(vertex)) { vertex.setZ(Double.MAX_VALUE); } else { Double aDouble = z1.get(vertex.getCoordinate()); if (aDouble != null) { vertex.setZ(aDouble); } else { vertex.setZ(Double.MAX_VALUE); } } } ReadableTriangulation triangulation = ReadableTriangulation.wrap(tin); ContourBuilder contourBuilder = new ContourBuilder(triangulation); MultiPolygon isoline = contourBuilder.computeIsoline(targetZ, triangulation.getEdges()); // debugging tool if (format.equals("triangulation")) { Response response = new Response(); for (Vertex vertex : (Collection<Vertex>) tin.getVertices(true)) { JsonFeature feature = new JsonFeature(); feature.setGeometry(geometryFactory.createPoint(vertex.getCoordinate())); HashMap<String, Object> properties = new HashMap<>(); properties.put("z", vertex.getZ()); feature.setProperties(properties); response.polygons.add(feature); } for (QuadEdge edge : (Collection<QuadEdge>) tin.getPrimaryEdges(false)) { JsonFeature feature = new JsonFeature(); feature.setGeometry(edge.toLineSegment().toGeometry(geometryFactory)); HashMap<String, Object> properties = new HashMap<>(); feature.setProperties(properties); response.polygons.add(feature); } JsonFeature feature = new JsonFeature(); feature.setGeometry(isoline); HashMap<String, Object> properties = new HashMap<>(); properties.put("z", targetZ); feature.setProperties(properties); response.polygons.add(feature); response.info.copyrights.addAll(config.getCopyrights()); return response; } else { return wrap(isoline); } }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/PtIsochroneResource.java
Info
wrap
class Info { public List<String> copyrights = new ArrayList<>(); } public List<JsonFeature> polygons = new ArrayList<>(); public Info info = new Info(); } @GET @Produces({MediaType.APPLICATION_JSON}) public Response doGet( @QueryParam("point") GHLocationParam sourceParam, @QueryParam("time_limit") @DefaultValue("600") long seconds, @QueryParam("reverse_flow") @DefaultValue("false") boolean reverseFlow, @QueryParam("pt.earliest_departure_time") @NotNull OffsetDateTimeParam departureTimeParam, @QueryParam("pt.blocked_route_types") @DefaultValue("0") int blockedRouteTypes, @QueryParam("result") @DefaultValue("multipolygon") String format) { Instant initialTime = departureTimeParam.get().toInstant(); GHLocation location = sourceParam.get(); double targetZ = seconds * 1000; GeometryFactory geometryFactory = new GeometryFactory(); CustomModel customModel = new CustomModel() .addToPriority(Statement.If("!" + VehicleAccess.key("foot"), Statement.Op.MULTIPLY, "0")) .addToSpeed(Statement.If("true", Statement.Op.LIMIT, VehicleSpeed.key("foot"))); final Weighting weighting = CustomModelParser.createWeighting(encodingManager, TurnCostProvider.NO_TURN_COST_PROVIDER, customModel); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, encodingManager.getBooleanEncodedValue(Subnetwork.key("foot"))); PtLocationSnapper.Result snapResult = new PtLocationSnapper(baseGraph, locationIndex, gtfsStorage).snapAll(Arrays.asList(location), Arrays.asList(snapFilter)); GraphExplorer graphExplorer = new GraphExplorer(snapResult.queryGraph, gtfsStorage.getPtGraph(), weighting, gtfsStorage, RealtimeFeed.empty(), reverseFlow, false, false, 5.0, reverseFlow, blockedRouteTypes); MultiCriteriaLabelSetting router = new MultiCriteriaLabelSetting(graphExplorer, reverseFlow, false, false, 0, Collections.emptyList()); Map<Coordinate, Double> z1 = new HashMap<>(); NodeAccess nodeAccess = snapResult.queryGraph.getNodeAccess(); for (Label label : router.calcLabels(snapResult.nodes.get(0), initialTime)) { if (!((label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1) <= targetZ)) { break; } if (label.node.streetNode != -1) { Coordinate nodeCoordinate = new Coordinate(nodeAccess.getLon(label.node.streetNode), nodeAccess.getLat(label.node.streetNode)); z1.merge(nodeCoordinate, (double) (label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1), Math::min); } else if (label.edge != null && (label.edge.getType() == GtfsStorage.EdgeType.EXIT_PT || label.edge.getType() == GtfsStorage.EdgeType.ENTER_PT)) { GtfsStorage.PlatformDescriptor platformDescriptor = label.edge.getPlatformDescriptor(); Stop stop = gtfsStorage.getGtfsFeeds().get(platformDescriptor.feed_id).stops.get(platformDescriptor.stop_id); Coordinate nodeCoordinate = new Coordinate(stop.stop_lon, stop.stop_lat); z1.merge(nodeCoordinate, (double) (label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1), Math::min); } } if (format.equals("multipoint")) { MultiPoint exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); return wrap(exploredPoints); } else { MultiPoint exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); // Get at least all nodes within our bounding box (I think convex hull would be enough.) // I think then we should have all possible encroaching points. (Proof needed.) locationIndex.query(BBox.fromEnvelope(exploredPoints.getEnvelopeInternal()), edgeId -> { EdgeIteratorState edge = snapResult.queryGraph.getEdgeIteratorStateForKey(edgeId * 2); z1.merge(new Coordinate(nodeAccess.getLon(edge.getBaseNode()), nodeAccess.getLat(edge.getBaseNode())), Double.MAX_VALUE, Math::min); z1.merge(new Coordinate(nodeAccess.getLon(edge.getAdjNode()), nodeAccess.getLat(edge.getAdjNode())), Double.MAX_VALUE, Math::min); }); exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); CoordinateList siteCoords = DelaunayTriangulationBuilder.extractUniqueCoordinates(exploredPoints); List<ConstraintVertex> constraintVertices = new ArrayList<>(); for (Object siteCoord : siteCoords) { Coordinate coord = (Coordinate) siteCoord; constraintVertices.add(new ConstraintVertex(coord)); } ConformingDelaunayTriangulator cdt = new ConformingDelaunayTriangulator(constraintVertices, JTS_TOLERANCE); cdt.setConstraints(new ArrayList(), new ArrayList()); cdt.formInitialDelaunay(); QuadEdgeSubdivision tin = cdt.getSubdivision(); for (Vertex vertex : (Collection<Vertex>) tin.getVertices(true)) { if (tin.isFrameVertex(vertex)) { vertex.setZ(Double.MAX_VALUE); } else { Double aDouble = z1.get(vertex.getCoordinate()); if (aDouble != null) { vertex.setZ(aDouble); } else { vertex.setZ(Double.MAX_VALUE); } } } ReadableTriangulation triangulation = ReadableTriangulation.wrap(tin); ContourBuilder contourBuilder = new ContourBuilder(triangulation); MultiPolygon isoline = contourBuilder.computeIsoline(targetZ, triangulation.getEdges()); // debugging tool if (format.equals("triangulation")) { Response response = new Response(); for (Vertex vertex : (Collection<Vertex>) tin.getVertices(true)) { JsonFeature feature = new JsonFeature(); feature.setGeometry(geometryFactory.createPoint(vertex.getCoordinate())); HashMap<String, Object> properties = new HashMap<>(); properties.put("z", vertex.getZ()); feature.setProperties(properties); response.polygons.add(feature); } for (QuadEdge edge : (Collection<QuadEdge>) tin.getPrimaryEdges(false)) { JsonFeature feature = new JsonFeature(); feature.setGeometry(edge.toLineSegment().toGeometry(geometryFactory)); HashMap<String, Object> properties = new HashMap<>(); feature.setProperties(properties); response.polygons.add(feature); } JsonFeature feature = new JsonFeature(); feature.setGeometry(isoline); HashMap<String, Object> properties = new HashMap<>(); properties.put("z", targetZ); feature.setProperties(properties); response.polygons.add(feature); response.info.copyrights.addAll(config.getCopyrights()); return response; } else { return wrap(isoline); } } } private Response wrap(Geometry isoline) {<FILL_FUNCTION_BODY>
JsonFeature feature = new JsonFeature(); feature.setGeometry(isoline); HashMap<String, Object> properties = new HashMap<>(); properties.put("bucket", 0); feature.setProperties(properties); Response response = new Response(); response.polygons.add(feature); response.info.copyrights.addAll(config.getCopyrights()); return response;