name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
graphhopper_GHRequest_setHeadings_rdh
/** * Sets the headings, i.e. the direction the route should leave the starting point and the directions the route * should arrive from at the via-points and the end point. Each heading is given as north based azimuth (clockwise) * in [0, 360) or NaN if no direction shall be specified. * <p> * The number of headings must be zero (default), one (for the start point) or equal to the number of points * when sending the request. */ public GHRequest setHeadings(List<Double> headings) { this.headings = headings; return this; }
3.26
graphhopper_Unzipper_getVerifiedFile_rdh
// see #1628 File getVerifiedFile(File destinationDir, ZipEntry ze) throws IOException { File destinationFile = new File(destinationDir, ze.getName()); if (!destinationFile.getCanonicalPath().startsWith(destinationDir.getCanonicalPath() + File.separator)) throw new SecurityException("Zip Entry is outside of the target dir: " + ze.getName()); return destinationFile; }
3.26
graphhopper_Unzipper_unzip_rdh
/** * * @param progressListener * updates not in percentage but the number of bytes already read. */ public void unzip(InputStream fromIs, File toFolder, LongConsumer progressListener) throws IOException { if (!toFolder.exists()) toFolder.mkdirs(); long sumBytes = 0; ZipInputStream zis = new ZipInputStream(fromIs); try { ZipEntry ze = zis.getNextEntry(); byte[] buffer = new byte[8 * 1024]; while (ze != null) { if (ze.isDirectory()) { getVerifiedFile(toFolder, ze).mkdir(); } else { double factor = 1; if ((ze.getCompressedSize() > 0) && (ze.getSize() > 0)) factor = ((double) (ze.getCompressedSize())) / ze.getSize(); File v7 = getVerifiedFile(toFolder, ze); FileOutputStream fos = new FileOutputStream(v7); try { int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); sumBytes += len * factor; if (progressListener != null) progressListener.accept(sumBytes); } } finally { fos.close(); } } ze = zis.getNextEntry(); } zis.closeEntry(); } finally { zis.close(); } }
3.26
graphhopper_AStarBidirectionCH_setApproximation_rdh
/** * * @param approx * if true it enables approximate distance calculation from lat,lon values */ public AStarBidirectionCH setApproximation(WeightApproximator approx) { weightApprox = new BalancedWeightApproximator(approx); return this; }
3.26
graphhopper_RoutingExampleTC_createGraphHopperInstance_rdh
// see RoutingExample for more details static GraphHopper createGraphHopperInstance(String ghLoc) { GraphHopper hopper = new GraphHopper(); hopper.setOSMFile(ghLoc); hopper.setGraphHopperLocation("target/routing-tc-graph-cache"); Profile profile = // we can also set u_turn_costs (in seconds). by default no u-turns are allowed, but with this setting // we will consider u-turns at all junctions with a 40s time penalty // enabling turn costs means OSM turn restriction constraints like 'no_left_turn' will be taken into account new Profile("car").setVehicle("car").setTurnCosts(true).putHint("u_turn_costs", 40); hopper.setProfiles(profile); // enable CH for our profile. since turn costs are enabled this will take more time and memory to prepare than // without turn costs. hopper.getCHPreparationHandler().setCHProfiles(new CHProfile(profile.getName())); hopper.importOrLoad(); return hopper;}
3.26
graphhopper_ShortestPathTree_setDistanceLimit_rdh
/** * Distance limit in meter */ public void setDistanceLimit(double limit) { exploreType = DISTANCE; this.limit = limit; this.queueByZ = new PriorityQueue<>(1000, comparingDouble(l -> l.distance)); }
3.26
graphhopper_ShortestPathTree_setTimeLimit_rdh
/** * Time limit in milliseconds */ public void setTimeLimit(double limit) { exploreType = f0; this.limit = limit; this.queueByZ = new PriorityQueue<>(1000, comparingLong(l -> l.time)); }
3.26
graphhopper_NodeBasedWitnessPathSearcher_getMemoryUsageAsString_rdh
/** * * @return currently used memory in MB (approximately) */ public String getMemoryUsageAsString() { return ((((8L * weights.length) + (changedNodes.buffer.length * 4L)) + heap.getMemoryUsage()) / Helper.MB) + "MB"; }
3.26
graphhopper_NodeBasedWitnessPathSearcher_findUpperBound_rdh
/** * Runs or continues a Dijkstra search starting at the startNode and ignoring the ignoreNode given in init(). * If the shortest path is found we return its weight. However, this method also returns early if any path was * found for which the weight is below or equal to the given acceptedWeight, or the given maximum number of settled * nodes is exceeded. In these cases the returned weight can be larger than the actual weight of the shortest path. * In any case we get an upper bound for the real shortest path weight. * * @param targetNode * the target of the search. if this node is settled we return the weight of the shortest path * @param acceptedWeight * once we find a path with weight smaller than or equal to this we return the weight. the * returned weight might be larger than the weight of the real shortest path. if there is * no path with weight smaller than or equal to this we stop the search and return the best * path we found. * @param maxSettledNodes * once the number of settled nodes exceeds this number we return the currently found best * weight path. in this case we might not have found a path at all. * @return the weight of the found path or {@link Double#POSITIVE_INFINITY} if no path was found */ public double findUpperBound(int targetNode, double acceptedWeight, int maxSettledNodes) {// todo: for historic reasons we count the number of settled nodes for each call of this method // *not* the total number of settled nodes since starting the search (which corresponds // to the size of the settled part of the shortest path tree). it's probably worthwhile // to change this in the future. while (((!heap.isEmpty()) && (settledNodes < maxSettledNodes)) && (heap.peekKey() <= acceptedWeight)) { // we found *a* path to the target node (not necessarily the shortest), and the weight is acceptable, so we stop if (weights[targetNode] <= acceptedWeight)return weights[targetNode]; int node = heap.poll(); PrepareGraphEdgeIterator iter = outEdgeExplorer.setBaseNode(node); while (iter.next()) { int adjNode = iter.getAdjNode(); if (adjNode == ignoreNode) continue; double weight = weights[node] + iter.getWeight();if (Double.isInfinite(weight)) continue; double adjWeight = weights[adjNode]; if (adjWeight == Double.POSITIVE_INFINITY) { weights[adjNode] = weight; heap.insert(weight, adjNode); changedNodes.add(adjNode); } else if (weight < adjWeight) { weights[adjNode] = weight; heap.update(weight, adjNode); } } settledNodes++; // we have settled the target node, we now know the exact weight of the shortest path and return if (node == targetNode) return weights[node]; } return weights[targetNode]; }
3.26
graphhopper_OSMMaxSpeedParser_isValidSpeed_rdh
/** * * @return <i>true</i> if the given speed is not {@link Double#NaN} */ private boolean isValidSpeed(double speed) { return !Double.isNaN(speed); }
3.26
graphhopper_GraphHopperGeocoding_geocode_rdh
/** * Perform a geocoding request. Both forward and revers are possible, just configure the <code>request</code> * accordingly. * * @param request * the request to send to the API * @return found results for your request */ public GHGeocodingResponse geocode(GHGeocodingRequest request) { String url = buildUrl(request); try { Request okRequest = new Request.Builder().url(url).header(X_GH_CLIENT_VERSION, GH_VERSION_FROM_MAVEN).build(); Response rsp = getClientForRequest(request).newCall(okRequest).execute();ResponseBody rspBody = rsp.body(); if (!rsp.isSuccessful()) throw new RuntimeException(rspBody.string()); GHGeocodingResponse geoRsp = objectMapper.readValue(rspBody.bytes(), GHGeocodingResponse.class); return geoRsp; } catch (IOException ex) { throw new RuntimeException((("IO problem for geocoding URL " + url) + ": ") + ex.getMessage(), ex); } }
3.26
graphhopper_AbstractSRTMElevationProvider_calcIntKey_rdh
// use int key instead of string for lower memory usage int calcIntKey(double lat, double lon) { // we could use LinearKeyAlgo but this is simpler as we only need integer precision: return (((down(lat) + 90) * 1000) + down(lon)) + 180; }
3.26
graphhopper_AbstractSRTMElevationProvider_toShort_rdh
// we need big endianess to read the SRTM files final short toShort(byte[] b, int offset) { return ((short) (((b[offset] & 0xff) << 8) | (b[offset + 1] & 0xff))); }
3.26
graphhopper_VectorTileDecoder_setAutoScale_rdh
/** * Set the autoScale setting. * * @param autoScale * when true, the encoder automatically scale and return all coordinates in the 0..255 range. * when false, the encoder returns all coordinates in the 0..extent-1 range as they are encoded. */ public void setAutoScale(boolean autoScale) { this.autoScale = autoScale; }
3.26
graphhopper_VectorTileDecoder_isAutoScale_rdh
/** * Get the autoScale setting. * * @return autoScale */ public boolean isAutoScale() { return autoScale; }
3.26
graphhopper_GHPoint_toGeoJson_rdh
/** * Attention: geoJson is LON,LAT */ public Double[] toGeoJson() { return new Double[]{ lon, lat }; }
3.26
graphhopper_JaroWinkler_distance_rdh
/** * Return 1 - similarity. */ public final double distance(final String s1, final String s2) { return 1.0 - m0(s1, s2); }
3.26
graphhopper_JaroWinkler_getThreshold_rdh
/** * Returns the current value of the threshold used for adding the Winkler * bonus. The default value is 0.7. * * @return the current value of the threshold */ public final double getThreshold() { return f0; }
3.26
graphhopper_JaroWinkler_m0_rdh
/** * Compute JW similarity. */ public final double m0(final String s1, final String s2) { int[] mtp = matches(s1, s2); float m = mtp[0]; if (m == 0) { return 0.0F; } double j = (((m / s1.length()) + (m / s2.length())) + ((m - mtp[1]) / m)) / THREE; double jw = j; if (j > getThreshold()) { jw = j + ((Math.min(JW_COEF, 1.0 / mtp[THREE]) * mtp[2]) * (1 - j)); } return jw; }
3.26
graphhopper_TileBasedElevationProvider_setInterpolate_rdh
/** * Configuration option to use bilinear interpolation to find the elevation at a point from the * surrounding elevation points. Has only an effect if called before the first getEle call. * Turned off by default. */ public TileBasedElevationProvider setInterpolate(boolean interpolate) { this.interpolate = interpolate; return this; }
3.26
graphhopper_TileBasedElevationProvider_setBaseURL_rdh
/** * Specifies the service URL where to download the elevation data. An empty string should set it * to the default URL. Default is a provider-dependent URL which should work out of the box. */ public TileBasedElevationProvider setBaseURL(String baseUrl) { if ((baseUrl == null) || baseUrl.isEmpty()) throw new IllegalArgumentException("baseUrl cannot be empty"); this.baseUrl = baseUrl; return this;}
3.26
graphhopper_PbfDecoder_waitForUpdate_rdh
/** * Any thread can call this method when they wish to wait until an update has been performed by * another thread. */ private void waitForUpdate() { try { dataWaitCondition.await(); } catch (InterruptedException e) { throw new RuntimeException("Thread was interrupted.", e); } }
3.26
graphhopper_PbfDecoder_m0_rdh
/** * Any thread can call this method when they wish to signal another thread that an update has * occurred. */ private void m0() { dataWaitCondition.signal(); }
3.26
graphhopper_NodeBasedNodeContractor_insertShortcuts_rdh
/** * Calls the shortcut handler for all edges and shortcuts adjacent to the given node. After this method is called * these edges and shortcuts will be removed from the prepare graph, so this method offers the last chance to deal * with them. */ private void insertShortcuts(int node) { shortcuts.clear(); insertOutShortcuts(node); insertInShortcuts(node); int origEdges = prepareGraph.getOriginalEdges(); for (Shortcut sc : shortcuts) { int shortcut = chBuilder.addShortcutNodeBased(sc.from, sc.to, sc.flags, sc.weight, sc.skippedEdge1, sc.skippedEdge2); if (sc.flags == PrepareEncoder.getScFwdDir()) { prepareGraph.setShortcutForPrepareEdge(sc.prepareEdgeFwd, origEdges + shortcut); } else if (sc.flags == PrepareEncoder.getScBwdDir()) { prepareGraph.setShortcutForPrepareEdge(sc.prepareEdgeBwd, origEdges + shortcut); } else { prepareGraph.setShortcutForPrepareEdge(sc.prepareEdgeFwd, origEdges + shortcut); prepareGraph.setShortcutForPrepareEdge(sc.prepareEdgeBwd, origEdges + shortcut); } } addedShortcutsCount += shortcuts.size(); }
3.26
graphhopper_NodeBasedNodeContractor_findAndHandleShortcuts_rdh
/** * Searches for shortcuts and calls the given handler on each shortcut that is found. The graph is not directly * changed by this method. * Returns the 'degree' of the given node (disregarding edges from/to already contracted nodes). * Note that here the degree is not the total number of adjacent edges, but only the number of incoming edges */ private long findAndHandleShortcuts(int node, PrepareShortcutHandler handler, int maxVisitedNodes) { long degree = 0; PrepareGraphEdgeIterator incomingEdges = inEdgeExplorer.setBaseNode(node); // collect outgoing nodes (goal-nodes) only once while (incomingEdges.next()) { int fromNode = incomingEdges.getAdjNode(); if (fromNode == node) throw new IllegalStateException("Unexpected loop-edge at node: " + node); final double incomingEdgeWeight = incomingEdges.getWeight();// this check is important to prevent calling calcMillis on inaccessible edges and also allows early exit if (Double.isInfinite(incomingEdgeWeight)) { continue; } // collect outgoing nodes (goal-nodes) only once PrepareGraphEdgeIterator outgoingEdges = outEdgeExplorer.setBaseNode(node); witnessPathSearcher.init(fromNode, node);degree++; while (outgoingEdges.next()) {int toNode = outgoingEdges.getAdjNode(); // no need to search for witnesses going from a node back to itself if (fromNode == toNode) continue; // Limit weight as ferries or forbidden edges can increase local search too much. // If we decrease the correct weight we only explore less and introduce more shortcuts. // I.e. no change to accuracy is made. double existingDirectWeight = incomingEdgeWeight + outgoingEdges.getWeight(); if (Double.isInfinite(existingDirectWeight)) continue; dijkstraSW.start(); dijkstraCount++; double maxWeight = witnessPathSearcher.findUpperBound(toNode, existingDirectWeight, maxVisitedNodes); dijkstraSW.stop(); // FOUND witness path, so do not add shortcut if (maxWeight <= existingDirectWeight) continue; handler.handleShortcut(fromNode, toNode, existingDirectWeight, outgoingEdges.getPrepareEdge(), outgoingEdges.getOrigEdgeCount(), incomingEdges.getPrepareEdge(), incomingEdges.getOrigEdgeCount()); } } return degree; }
3.26
graphhopper_NodeBasedNodeContractor_calculatePriority_rdh
/** * Warning: the calculated priority must NOT depend on priority(v) and therefore findAndHandleShortcuts should also not * depend on the priority(v). Otherwise updating the priority before contracting in contractNodes() could lead to * a slowish or even endless loop. */ @Override public float calculatePriority(int node) { // # huge influence: the bigger the less shortcuts gets created and the faster is the preparation // // every adjNode has an 'original edge' number associated. initially it is r=1 // when a new shortcut is introduced then r of the associated edges is summed up: // r(u,w)=r(u,v)+r(v,w) now we can define // originalEdgesCount = σ(v) := sum_{ (u,w) ∈ shortcuts(v) } of r(u, w) shortcutsCount = 0; originalEdgesCount = 0; findAndHandleShortcuts(node, this::countShortcuts, ((int) (meanDegree * params.maxPollFactorHeuristic))); // from shortcuts we can compute the edgeDifference // # low influence: with it the shortcut creation is slightly faster // // |shortcuts(v)| − |{(u, v) | v uncontracted}| − |{(v, w) | v uncontracted}| // meanDegree is used instead of outDegree+inDegree as if one adjNode is in both directions // only one bucket memory is used. Additionally one shortcut could also stand for two directions. int edgeDifference = shortcutsCount - prepareGraph.getDegree(node); // according to the paper do a simple linear combination of the properties to get the priority. return (params.edgeDifferenceWeight * edgeDifference) + (params.originalEdgesCountWeight * originalEdgesCount);// todo: maybe use contracted-neighbors heuristic (contract nodes with lots of contracted neighbors later) as in GH 1.0 again? // maybe use hierarchy-depths heuristic as in edge-based? }
3.26
graphhopper_StringEncodedValue_roundUp_rdh
/** * * @param value * the value to be rounded * @return the value rounded to the highest integer with the same number of leading zeros */ private static int roundUp(int value) { return (-1) >>> Integer.numberOfLeadingZeros(value); }
3.26
graphhopper_StringEncodedValue_getValues_rdh
/** * * @return an unmodifiable List of the current values */ public List<String> getValues() { return Collections.unmodifiableList(values); }
3.26
graphhopper_FootPriorityParser_collect_rdh
/** * * @param weightToPrioMap * associate a weight with every priority. This sorted map allows * subclasses to 'insert' more important priorities as well as overwrite determined priorities. */ void collect(ReaderWay way, TreeMap<Double, Integer> weightToPrioMap) { String highway = way.getTag("highway"); if (way.hasTag("foot", "designated")) weightToPrioMap.put(100.0, PREFER.getValue()); double maxSpeed = Math.max(getMaxSpeed(way, false), getMaxSpeed(way, true)); if (safeHighwayTags.contains(highway) || (isValidSpeed(maxSpeed) && (maxSpeed <= 20))) { weightToPrioMap.put(40.0, PREFER.getValue()); if (way.hasTag("tunnel", intendedValues)) { if (way.hasTag("sidewalk", sidewalksNoValues)) weightToPrioMap.put(40.0, AVOID.getValue()); else weightToPrioMap.put(40.0, UNCHANGED.getValue()); } } else if ((isValidSpeed(maxSpeed) && (maxSpeed > 50)) || avoidHighwayTags.contains(highway)) { if (way.hasTag("sidewalk", sidewalksNoValues)) weightToPrioMap.put(40.0, VERY_BAD.getValue()); else if (!way.hasTag("sidewalk", sidewalkValues)) weightToPrioMap.put(40.0, AVOID.getValue()); else weightToPrioMap.put(40.0, SLIGHT_AVOID.getValue()); } else if (way.hasTag("sidewalk", sidewalksNoValues)) weightToPrioMap.put(40.0, AVOID.getValue()); if (way.hasTag("bicycle", "official") || way.hasTag("bicycle", "designated")) weightToPrioMap.put(44.0, SLIGHT_AVOID.getValue()); }
3.26
graphhopper_SpatialKeyAlgo_getBits_rdh
/** * * @return the number of involved bits */ public int getBits() { return allBits; }
3.26
graphhopper_GtfsStorage_postInit_rdh
// TODO: Refactor initialization public void postInit() { LocalDate latestStartDate = LocalDate.ofEpochDay(this.gtfsFeeds.values().stream().mapToLong(f -> f.getStartDate().toEpochDay()).max().getAsLong()); LocalDate earliestEndDate = LocalDate.ofEpochDay(this.gtfsFeeds.values().stream().mapToLong(f -> f.getEndDate().toEpochDay()).min().getAsLong()); LOGGER.info("Calendar range covered by all feeds: {} till {}", latestStartDate, earliestEndDate); faresByFeed = new HashMap<>(); this.gtfsFeeds.forEach((feed_id, feed) -> faresByFeed.put(feed_id, feed.fares)); }
3.26
graphhopper_OSMValueExtractor_stringToKmh_rdh
/** * * @return the speed in km/h */ public static double stringToKmh(String str) { if (Helper.isEmpty(str)) return Double.NaN; if ("walk".equals(str)) return 6; // on some German autobahns and a very few other places if ("none".equals(str)) return MaxSpeed.UNLIMITED_SIGN_SPEED; int mpInteger = str.indexOf("mp"); int knotInteger = str.indexOf("knots"); int kmInteger = str.indexOf("km"); int kphInteger = str.indexOf("kph"); double factor; if (mpInteger > 0) { str = str.substring(0, mpInteger).trim(); factor = DistanceCalcEarth.KM_MILE; } else if (knotInteger > 0) { str = str.substring(0, knotInteger).trim(); factor = 1.852;// see https://en.wikipedia.org/wiki/Knot_%28unit%29#Definitions } else { if (kmInteger > 0) { str = str.substring(0, kmInteger).trim(); } else if (kphInteger > 0) { str = str.substring(0, kphInteger).trim(); } factor = 1; } double value; try { value = Integer.parseInt(str) * factor; } catch (Exception ex) { return Double.NaN; } if (value <= 0) { return Double.NaN; } return value; }
3.26
graphhopper_OSMValueExtractor_conditionalWeightToTons_rdh
/** * This parses the weight for a conditional value like "delivery @ (weight > 7.5)" */ public static double conditionalWeightToTons(String value) { try { int index = value.indexOf("weight>");// maxweight or weight if (index < 0) { index = value.indexOf("weight >"); if (index > 0)index += "weight >".length(); } else { index += "weight>".length(); } if (index > 0) { int lastIndex = value.indexOf(')', index);// (value) or value if (lastIndex < 0) lastIndex = value.length() - 1; if (lastIndex > index) return OSMValueExtractor.stringToTons(value.substring(index, lastIndex)); } return Double.NaN; } catch (Exception ex) { throw new RuntimeException("value " + value, ex); } }
3.26
graphhopper_QueryOverlayBuilder_buildVirtualEdges_rdh
/** * For all specified snaps calculate the snapped point and if necessary set the closest node * to a virtual one and reverse the closest edge. Additionally the wayIndex can change if an edge is * swapped. */private void buildVirtualEdges(List<Snap> snaps) { GHIntObjectHashMap<List<Snap>> edge2res = new GHIntObjectHashMap<>(snaps.size()); // Phase 1 // calculate snapped point and swap direction of closest edge if necessary for (Snap snap : snaps) { // Do not create virtual node for a snap if it is directly on a tower node or not found if (snap.getSnappedPosition() == Position.TOWER) continue; EdgeIteratorState closestEdge = snap.getClosestEdge(); if (closestEdge == null) throw new IllegalStateException("Do not call QueryGraph.create with invalid Snap " + snap); int v3 = closestEdge.getBaseNode(); // Force the identical direction for all closest edges. // It is important to sort multiple results for the same edge by its wayIndex boolean doReverse = v3 > closestEdge.getAdjNode(); if (v3 == closestEdge.getAdjNode()) { // check for special case #162 where adj == base and force direction via latitude comparison PointList pl = closestEdge.fetchWayGeometry(FetchMode.PILLAR_ONLY); if (pl.size() > 1) doReverse = pl.getLat(0) > pl.getLat(pl.size() - 1); } if (doReverse) { closestEdge = closestEdge.detach(true); PointList fullPL = closestEdge.fetchWayGeometry(FetchMode.ALL); snap.setClosestEdge(closestEdge);// ON pillar node if (snap.getSnappedPosition() == Position.PILLAR) snap.setWayIndex((fullPL.size() - snap.getWayIndex()) - 1); else// for case "OFF pillar node" snap.setWayIndex((fullPL.size() - snap.getWayIndex()) - 2); if (snap.getWayIndex() < 0) throw new IllegalStateException((("Problem with wayIndex while reversing closest edge:" + closestEdge) + ", ") + snap); } // find multiple results on same edge int edgeId = closestEdge.getEdge(); List<Snap> list = edge2res.get(edgeId); if (list == null) { list = new ArrayList<>(5); edge2res.put(edgeId, list); } list.add(snap); } // Phase 2 - now it is clear which points cut one edge // 1. create point lists // 2. create virtual edges between virtual nodes and its neighbor (virtual or normal nodes) edge2res.forEach(new IntObjectPredicate<List<Snap>>() { @Override public boolean apply(int edgeId, List<Snap> results) { // we can expect at least one entry in the results EdgeIteratorState v9 = results.get(0).getClosestEdge();final PointList fullPL = v9.fetchWayGeometry(FetchMode.ALL); int baseNode = v9.getBaseNode(); Collections.sort(results, new Comparator<Snap>() { @Override public int compare(Snap o1, Snap o2) { int diff = Integer.compare(o1.getWayIndex(), o2.getWayIndex()); if (diff == 0) { return Double.compare(distanceOfSnappedPointToPillarNode(o1), distanceOfSnappedPointToPillarNode(o2)); } else { return diff; } } private double distanceOfSnappedPointToPillarNode(Snap o) { GHPoint snappedPoint = o.getSnappedPoint(); double fromLat = fullPL.getLat(o.getWayIndex()); double fromLon = fullPL.getLon(o.getWayIndex()); return DistancePlaneProjection.DIST_PLANE.calcNormalizedDist(fromLat, fromLon, snappedPoint.lat, snappedPoint.lon); } }); GHPoint3D prevPoint = fullPL.get(0); int adjNode = v9.getAdjNode(); int origEdgeKey = v9.getEdgeKey(); int origRevEdgeKey = v9.getReverseEdgeKey(); int prevWayIndex = 1; int prevNodeId = baseNode; int virtNodeId = queryOverlay.getVirtualNodes().size() + firstVirtualNodeId; boolean addedEdges = false; // Create base and adjacent PointLists for all non-equal virtual nodes. // We do so via inserting them at the correct position of fullPL and cutting the // fullPL into the right pieces. for (int i = 0; i < results.size(); i++) { Snap res = results.get(i); if (res.getClosestEdge().getBaseNode() != baseNode) throw new IllegalStateException((("Base nodes have to be identical but were not: " + v9) + " vs ") + res.getClosestEdge()); GHPoint3D currSnapped = res.getSnappedPoint(); // no new virtual nodes if very close ("snap" together) if (Snap.considerEqual(prevPoint.lat, prevPoint.lon, currSnapped.lat, currSnapped.lon)) { res.setClosestNode(prevNodeId); res.setSnappedPoint(prevPoint); res.setWayIndex(i == 0 ? 0 : results.get(i - 1).getWayIndex()); res.setSnappedPosition(i == 0 ? Position.TOWER : results.get(i - 1).getSnappedPosition()); res.setQueryDistance(DIST_PLANE.calcDist(prevPoint.lat, prevPoint.lon, res.getQueryPoint().lat, res.getQueryPoint().lon)); continue; } queryOverlay.getClosestEdges().add(res.getClosestEdge().getEdge()); boolean isPillar = res.getSnappedPosition() == Position.PILLAR; createEdges(origEdgeKey, origRevEdgeKey, prevPoint, prevWayIndex, isPillar, res.getSnappedPoint(), res.getWayIndex(), fullPL, v9, prevNodeId, virtNodeId); queryOverlay.getVirtualNodes().add(currSnapped.lat, currSnapped.lon, currSnapped.ele); // add edges again to set adjacent edges for newVirtNodeId if (addedEdges) { queryOverlay.addVirtualEdge(queryOverlay.getVirtualEdge(queryOverlay.getNumVirtualEdges() - 2)); queryOverlay.addVirtualEdge(queryOverlay.getVirtualEdge(queryOverlay.getNumVirtualEdges() - 2)); } addedEdges = true; res.setClosestNode(virtNodeId); prevNodeId = virtNodeId; prevWayIndex = res.getWayIndex() + 1; prevPoint = currSnapped; virtNodeId++; } // two edges between last result and adjacent node are still missing if not all points skipped if (addedEdges) createEdges(origEdgeKey, origRevEdgeKey, prevPoint, prevWayIndex, false, fullPL.get(fullPL.size() - 1), fullPL.size() - 2, fullPL, v9, virtNodeId - 1, adjNode); return true; } }); }
3.26
graphhopper_OSMNodeData_addCopyOfNode_rdh
/** * Creates a copy of the coordinates stored for the given node ID * * @return the (artificial) OSM node ID created for the copied node and the associated ID */ SegmentNode addCopyOfNode(SegmentNode node) { GHPoint3D point = getCoordinates(node.id); if (point == null) throw new IllegalStateException(("Cannot copy node : " + node.osmNodeId) + ", because it is missing"); final long v5 = nextArtificialOSMNodeId++; if (idsByOsmNodeIds.put(v5, INTERMEDIATE_NODE) != EMPTY_NODE)throw new IllegalStateException("Artificial osm node id already exists: " + v5); long id = addPillarNode(v5, point.getLat(), point.getLon(), point.getEle()); return new SegmentNode(v5, id, node.tags); }
3.26
graphhopper_OSMNodeData_addCoordinatesIfMapped_rdh
/** * Stores the given coordinates for the given OSM node ID, but only if a non-empty node type was set for this * OSM node ID previously. * * @return the node type this OSM node was associated with before this method was called */ public long addCoordinatesIfMapped(long osmNodeId, double lat, double lon, DoubleSupplier getEle) { long nodeType = idsByOsmNodeIds.get(osmNodeId); if (nodeType == EMPTY_NODE) return nodeType; else if ((nodeType == JUNCTION_NODE) || (nodeType == CONNECTION_NODE)) addTowerNode(osmNodeId, lat, lon, getEle.getAsDouble()); else if ((nodeType == INTERMEDIATE_NODE) || (nodeType == END_NODE)) addPillarNode(osmNodeId, lat, lon, getEle.getAsDouble());else throw new IllegalStateException((("Unknown node type: " + nodeType) + ", or coordinates already set. Possibly duplicate OSM node ID: ") + osmNodeId); return nodeType; }
3.26
graphhopper_OSMNodeData_getNodeCount_rdh
/** * * @return the number of mapped nodes (tower + pillar, but also including pillar nodes that were converted to tower) */ public long getNodeCount() { return idsByOsmNodeIds.getSize(); }
3.26
graphhopper_OSMNodeData_getNodeTagCapacity_rdh
/** * * @return the number of nodes for which we store tags */ public long getNodeTagCapacity() { return nodeKVStorage.getCapacity(); }
3.26
graphhopper_AlternativeRoute_isAlreadyExisting_rdh
/** * This method returns true if the specified tid is already existent in the * traversalIDMap */ boolean isAlreadyExisting(final int tid) { final AtomicBoolean exists = new AtomicBoolean(false); traversalIdMap.forEach(new IntObjectPredicate<IntSet>() { @Override public boolean apply(int key, IntSet set) { if (set.contains(tid)) { exists.set(true); return false; } return true;} }); return exists.get(); }
3.26
graphhopper_AlternativeRoute_addToMap_rdh
/** * This method adds the traversal IDs of the specified path as set to the specified map. */ AtomicInteger addToMap(GHIntObjectHashMap<IntSet> map, Path path) { IntSet set = new GHIntHashSet(); final AtomicInteger startTID = new AtomicInteger(-1); for (EdgeIteratorState iterState : path.calcEdges()) { int tid = traversalMode.createTraversalId(iterState, false); set.add(tid);if (startTID.get() < 0) { // for node based traversal we need to explicitly add base node as starting node and to list if (!traversalMode.isEdgeBased()) { tid = iterState.getBaseNode(); set.add(tid); } startTID.set(tid); } } map.put(startTID.get(), set); return startTID; }
3.26
graphhopper_AlternativeRoute_getFirstShareEE_rdh
/** * Extract path until we stumble over an existing traversal id */ SPTEntry getFirstShareEE(SPTEntry startEE, boolean reverse) { while (startEE.parent != null) { // TODO we could make use of traversal ID directly if stored in SPTEntry int tid = traversalMode.createTraversalId(graph.getEdgeIteratorState(startEE.edge, startEE.parent.adjNode), reverse); if (isAlreadyExisting(tid)) return startEE; startEE = startEE.parent; } return startEE; }
3.26
graphhopper_AlternativeRoute_isBestPath_rdh
// returns true if fromSPTEntry is identical to the specified best path boolean isBestPath(SPTEntry fromSPTEntry) { if (traversalMode.isEdgeBased()) { if (GHUtility.getEdgeFromEdgeKey(v8.get()) == fromSPTEntry.edge) { if (fromSPTEntry.parent == null) throw new IllegalStateException("best path must have no parent but was non-null: " + fromSPTEntry); if ((bestEntry.get() != null) && (bestEntry.get().edge != fromSPTEntry.edge)) throw new IllegalStateException((((("there can be only one best entry but was " + fromSPTEntry) + " vs old: ") + bestEntry.get()) + " ") + graph.getEdgeIteratorState(fromSPTEntry.edge, fromSPTEntry.adjNode).fetchWayGeometry(FetchMode.ALL)); bestEntry.set(fromSPTEntry);return true; } } else if (fromSPTEntry.parent == null) { if (v8.get() != fromSPTEntry.adjNode) throw new IllegalStateException(((("Start traversal ID has to be identical to root edge entry " + "which is the plateau start of the best path but was: ") + v8) + " vs. adjNode: ") + fromSPTEntry.adjNode); if (bestEntry.get() != null) throw new IllegalStateException((((("there can be only one best entry but was " + fromSPTEntry) + " vs old: ") + bestEntry.get()) + " ") + graph.getEdgeIteratorState(fromSPTEntry.edge, fromSPTEntry.adjNode).fetchWayGeometry(FetchMode.ALL)); bestEntry.set(fromSPTEntry); return true; } return false; }
3.26
graphhopper_AlternativeRoute_m0_rdh
/** * Return the current worst weight for all alternatives */ double m0() { if (alternatives.isEmpty()) throw new IllegalStateException("Empty alternative list cannot happen"); return alternatives.get(alternatives.size() - 1).sortBy; }
3.26
graphhopper_GHLongLongBTree_getCapacity_rdh
/** * * @return used bytes */long getCapacity() { long cap = (((keys.length * (8 + 4)) + (3 * 12)) + 4) + 1; if (!isLeaf) { cap += children.length * 4;for (int i = 0; i < children.length; i++) { if (children[i] != null) { cap += children[i].getCapacity(); } } }return cap; }
3.26
graphhopper_GHLongLongBTree_m0_rdh
/** * * @return memory usage in MB */ @Override public int m0() { return Math.round(root.getCapacity() / Helper.MB); }
3.26
graphhopper_RAMDataAccess_store_rdh
/** * * @param store * true if in-memory data should be saved when calling flush */ public RAMDataAccess store(boolean store) { this.store = store; return this; }
3.26
graphhopper_Transfers_getTransfersToStop_rdh
// Starts implementing the proposed GTFS extension for route and trip specific transfer rules. // So far, only the route is supported. List<Transfer> getTransfersToStop(String toStopId, String toRouteId) { final List<Transfer> allInboundTransfers = transfersToStop.getOrDefault(toStopId, Collections.emptyList()); final Map<String, List<Transfer>> byFromStop = allInboundTransfers.stream().filter(t -> (t.transfer_type == 0) || (t.transfer_type == 2)).filter(t -> (t.to_route_id == null) || toRouteId.equals(t.to_route_id)).collect(Collectors.groupingBy(t -> t.from_stop_id)); final List<Transfer> result = new ArrayList<>(); byFromStop.forEach((fromStop, transfers) -> { if (hasNoRouteSpecificArrivalTransferRules(fromStop)) { Transfer myRule = new Transfer(); myRule.from_stop_id = fromStop; myRule.to_stop_id = toStopId;if (transfers.size() == 1) myRule.min_transfer_time = transfers.get(0).min_transfer_time; result.add(myRule); } else { routesByStop.getOrDefault(fromStop, Collections.emptySet()).forEach(fromRoute -> { final Transfer mostSpecificRule = findMostSpecificRule(transfers, fromRoute, toRouteId); final Transfer myRule = new Transfer(); myRule.to_route_id = toRouteId; myRule.from_route_id = fromRoute; myRule.to_stop_id = mostSpecificRule.to_stop_id; myRule.from_stop_id = mostSpecificRule.from_stop_id; myRule.transfer_type = mostSpecificRule.transfer_type; myRule.min_transfer_time = mostSpecificRule.min_transfer_time; myRule.from_trip_id = mostSpecificRule.from_trip_id; myRule.to_trip_id = mostSpecificRule.to_trip_id; result.add(myRule); }); }}); if (result.stream().noneMatch(t -> t.from_stop_id.equals(toStopId))) { final Transfer withinStationTransfer = new Transfer(); withinStationTransfer.from_stop_id = toStopId; withinStationTransfer.to_stop_id = toStopId; result.add(withinStationTransfer); } return result; }
3.26
graphhopper_DistanceCalc3D_m0_rdh
/** * * @param fromHeight * in meters above 0 * @param toHeight * in meters above 0 */ public double m0(double fromLat, double fromLon, double fromHeight, double toLat, double toLon, double toHeight) { double len = super.calcDist(fromLat, fromLon, toLat, toLon); double delta = Math.abs(toHeight - fromHeight); return Math.sqrt((delta * delta) + (len * len)); }
3.26
graphhopper_MatrixResponse_hasErrors_rdh
/** * * @return true if one or more error found */ public boolean hasErrors() { return !errors.isEmpty(); }
3.26
graphhopper_MatrixResponse_getWeight_rdh
/** * Returns the weight for the specific entry (from -&gt; to) in arbitrary units ('costs'), or * {@link Double#MAX_VALUE} in case no connection was found (and {@link GHMRequest#setFailFast(boolean)} was set * to true). */ public double getWeight(int from, int to) { if (hasErrors()) { throw new IllegalStateException((((("Cannot return weight (" + from) + ",") + to) + ") if errors occurred ") + getErrors()); } if (from >= weights.length) { throw new IllegalStateException((("Cannot get 'from' " + from) + " from weights with size ") + weights.length); } else if (to >= weights[from].length) { throw new IllegalStateException((("Cannot get 'to' " + to) + " from weights with size ") + weights[from].length); } return weights[from][to]; }
3.26
graphhopper_MatrixResponse_getTime_rdh
/** * Returns the time for the specific entry (from -&gt; to) in milliseconds or {@link Long#MAX_VALUE} in case * no connection was found (and {@link GHMRequest#setFailFast(boolean)} was set to true). */ public long getTime(int from, int to) { if (hasErrors()) { throw new IllegalStateException((((("Cannot return time (" + from) + ",") + to) + ") if errors occurred ") + getErrors()); } if (from >= f0.length) { throw new IllegalStateException((("Cannot get 'from' " + from) + " from times with size ") + f0.length); } else if (to >= f0[from].length) { throw new IllegalStateException((("Cannot get 'to' " + to) + " from times with size ") + f0[from].length); } return f0[from][to]; }
3.26
graphhopper_MatrixResponse_getDistance_rdh
/** * Returns the distance for the specific entry (from -&gt; to) in meter or {@link Double#MAX_VALUE} in case * no connection was found (and {@link GHMRequest#setFailFast(boolean)} was set to true). */public double getDistance(int from, int to) { if (hasErrors()) { throw new IllegalStateException((((("Cannot return distance (" + from) + ",") + to) + ") if errors occurred ") + getErrors()); } if (from >= distances.length) { throw new IllegalStateException((("Cannot get 'from' " + from) + " from distances with size ") + distances.length); } else if (to >= distances[from].length) { throw new IllegalStateException((("Cannot get 'to' " + to) + " from distances with size ") + distances[from].length); } return distances[from][to] == Integer.MAX_VALUE ? Double.MAX_VALUE : distances[from][to]; }
3.26
graphhopper_MatrixResponse_hasProblems_rdh
/** * * @return true if there are invalid or disconnected points (which both do not yield an error in case we do not fail fast). * @see GHMRequest#setFailFast(boolean) */ public boolean hasProblems() { return ((!disconnectedPoints.isEmpty()) || (!invalidFromPoints.isEmpty())) || (!invalidToPoints.isEmpty()); }
3.26
graphhopper_QueryGraph_m0_rdh
/** * Assigns the 'unfavored' flag to a virtual edge (for both directions) */ public void m0(int virtualEdgeId) { if (!isVirtualEdge(virtualEdgeId))return; VirtualEdgeIteratorState edge = getVirtualEdge(getInternalVirtualEdgeId(virtualEdgeId)); edge.setUnfavored(true); unfavoredEdges.add(edge); // we have to set the unfavored flag also for the virtual edge state that is used when we discover the same edge // from the adjacent node. note that the unfavored flag will be set for both 'directions' of the same edge state. VirtualEdgeIteratorState reverseEdge = getVirtualEdge(getPosOfReverseEdge(getInternalVirtualEdgeId(virtualEdgeId))); reverseEdge.setUnfavored(true); unfavoredEdges.add(reverseEdge); }
3.26
graphhopper_QueryGraph_clearUnfavoredStatus_rdh
/** * Removes the 'unfavored' status of all virtual edges. */ public void clearUnfavoredStatus() { for (VirtualEdgeIteratorState edge : unfavoredEdges) { edge.setUnfavored(false); } unfavoredEdges.clear(); }
3.26
graphhopper_StopWatch_getCurrentSeconds_rdh
/** * returns the total elapsed time on this stopwatch without the need of stopping it */ public float getCurrentSeconds() { if (notStarted()) { return 0; } long lastNanos = (lastTime < 0) ? 0 : System.nanoTime() - lastTime; return (elapsedNanos + lastNanos) / 1.0E9F; }
3.26
graphhopper_StopWatch_getMillisDouble_rdh
/** * returns the elapsed time in ms but includes the fraction as well to get a precise value */ public double getMillisDouble() { return elapsedNanos / 1000000.0; }
3.26
graphhopper_PrepareContractionHierarchies_useFixedNodeOrdering_rdh
/** * Instead of heuristically determining a node ordering for the graph contraction it is also possible * to use a fixed ordering. For example this allows re-using a previously calculated node ordering. * This will speed up CH preparation, but might lead to slower queries. */ public PrepareContractionHierarchies useFixedNodeOrdering(NodeOrderingProvider nodeOrderingProvider) { if (nodeOrderingProvider.getNumNodes() != nodes) { throw new IllegalArgumentException((((("contraction order size (" + nodeOrderingProvider.getNumNodes()) + ")") + " must be equal to number of nodes in graph (") + nodes) + ")."); } this.nodeOrderingProvider = nodeOrderingProvider; return this; }
3.26
graphhopper_ViaRouting_lookup_rdh
/** * * @throws MultiplePointsNotFoundException * in case one or more points could not be resolved */ public static List<Snap> lookup(EncodedValueLookup lookup, List<GHPoint> points, EdgeFilter snapFilter, LocationIndex locationIndex, List<String> snapPreventions, List<String> pointHints, DirectedEdgeFilter directedSnapFilter, List<Double> headings) {if (points.size() < 2) throw new IllegalArgumentException("At least 2 points have to be specified, but was:" + points.size()); final EnumEncodedValue<RoadClass> roadClassEnc = lookup.getEnumEncodedValue(RoadClass.KEY, RoadClass.class); final EnumEncodedValue<RoadEnvironment> roadEnvEnc = lookup.getEnumEncodedValue(RoadEnvironment.KEY, RoadEnvironment.class); EdgeFilter strictEdgeFilter = (snapPreventions.isEmpty()) ? snapFilter : new SnapPreventionEdgeFilter(snapFilter, roadClassEnc, roadEnvEnc, snapPreventions); List<Snap> snaps = new ArrayList<>(points.size()); IntArrayList pointsNotFound = new IntArrayList(); for (int placeIndex = 0; placeIndex < points.size(); placeIndex++) { GHPoint point = points.get(placeIndex); Snap snap = null; if ((placeIndex < headings.size()) && (!Double.isNaN(headings.get(placeIndex)))) { if ((!pointHints.isEmpty()) && (!Helper.isEmpty(pointHints.get(placeIndex)))) throw new IllegalArgumentException(("Cannot specify heading and point_hint at the same time. " + "Make sure you specify either an empty point_hint (String) or a NaN heading (double) for point ") + placeIndex); snap = locationIndex.findClosest(point.lat, point.lon, new HeadingEdgeFilter(directedSnapFilter, headings.get(placeIndex), point)); } else if (!pointHints.isEmpty()) { snap = locationIndex.findClosest(point.lat, point.lon, new NameSimilarityEdgeFilter(strictEdgeFilter, pointHints.get(placeIndex), point, 170)); } else if (!snapPreventions.isEmpty()) { snap = locationIndex.findClosest(point.lat, point.lon, strictEdgeFilter); } if ((snap == null) || (!snap.isValid())) snap = locationIndex.findClosest(point.lat, point.lon, snapFilter); if (!snap.isValid()) pointsNotFound.add(placeIndex); snaps.add(snap); } if (!pointsNotFound.isEmpty()) throw new MultiplePointsNotFoundException(pointsNotFound); return snaps; }
3.26
graphhopper_ViaRouting_buildEdgeRestrictions_rdh
/** * Determines restrictions for the start/target edges to account for the heading, pass_through and curbside parameters * for a single via-route leg. * * @param fromHeading * the heading at the start node of this leg, or NaN if no restriction should be applied * @param toHeading * the heading at the target node (the vehicle's heading when arriving at the target), or NaN if * no restriction should be applied * @param incomingEdge * the last edge of the previous leg (or {@link EdgeIterator#NO_EDGE} if not available */ private static EdgeRestrictions buildEdgeRestrictions(QueryGraph queryGraph, Snap fromSnap, Snap toSnap, double fromHeading, double toHeading, int incomingEdge, boolean passThrough, String fromCurbside, String toCurbside, DirectedEdgeFilter edgeFilter) { EdgeRestrictions edgeRestrictions = new EdgeRestrictions(); // curbsides if ((!fromCurbside.equals(CURBSIDE_ANY)) || (!toCurbside.equals(CURBSIDE_ANY))) { DirectedEdgeFilter directedEdgeFilter = (edge, reverse) -> { // todo: maybe find a cleaner way to obtain the original edge given a VirtualEdgeIterator (not VirtualEdgeIteratorState) if (queryGraph.isVirtualEdge(edge.getEdge())) { EdgeIteratorState virtualEdge = queryGraph.getEdgeIteratorStateForKey(edge.getEdgeKey()); EdgeIteratorState origEdge = queryGraph.getEdgeIteratorStateForKey(((VirtualEdgeIteratorState) (virtualEdge)).getOriginalEdgeKey()); return edgeFilter.accept(origEdge, reverse); } else return edgeFilter.accept(edge, reverse); }; DirectionResolver directionResolver = new DirectionResolver(queryGraph, directedEdgeFilter); DirectionResolverResult fromDirection = directionResolver.resolveDirections(fromSnap.getClosestNode(), fromSnap.getQueryPoint()); DirectionResolverResult toDirection = directionResolver.resolveDirections(toSnap.getClosestNode(), toSnap.getQueryPoint()); int sourceOutEdge = DirectionResolverResult.getOutEdge(fromDirection, fromCurbside); int targetInEdge = DirectionResolverResult.getInEdge(toDirection, toCurbside); if (fromSnap.getClosestNode() == toSnap.getClosestNode()) { // special case where we go from one point back to itself. for example going from a point A // with curbside right to the same point with curbside right is interpreted as 'being there // already' -> empty path. Similarly if the curbside for the start/target is not even specified // there is no need to drive a loop. However, going from point A/right to point A/left (or the // other way around) means we need to drive some kind of loop to get back to the same location // (arriving on the other side of the road). if ((((Helper.isEmpty(fromCurbside) || Helper.isEmpty(toCurbside)) || fromCurbside.equals(CURBSIDE_ANY)) || toCurbside.equals(CURBSIDE_ANY)) || fromCurbside.equals(toCurbside)) { // we just disable start/target edge constraints to get an empty path sourceOutEdge = ANY_EDGE; targetInEdge = ANY_EDGE; } } edgeRestrictions.setSourceOutEdge(sourceOutEdge); edgeRestrictions.setTargetInEdge(targetInEdge); } // heading if ((!Double.isNaN(fromHeading)) || (!Double.isNaN(toHeading))) { // todo: for heading/pass_through with edge-based routing (especially CH) we have to find the edge closest // to the heading and use it as sourceOutEdge/targetInEdge here. the heading penalty will not be applied // this way (unless we implement this), but this is more or less ok as we can use finite u-turn costs // instead. maybe the hardest part is dealing with headings that cannot be fulfilled, like in one-way // streets. see also #1765 HeadingResolver headingResolver = new HeadingResolver(queryGraph); if (!Double.isNaN(fromHeading)) edgeRestrictions.getUnfavoredEdges().addAll(headingResolver.getEdgesWithDifferentHeading(fromSnap.getClosestNode(), fromHeading)); if (!Double.isNaN(toHeading)) { toHeading += 180; if (toHeading > 360) toHeading -= 360; edgeRestrictions.getUnfavoredEdges().addAll(headingResolver.getEdgesWithDifferentHeading(toSnap.getClosestNode(), toHeading)); } } // pass through if ((incomingEdge != NO_EDGE) && passThrough) edgeRestrictions.getUnfavoredEdges().add(incomingEdge); return edgeRestrictions; }
3.26
graphhopper_CarAccessParser_isBackwardOneway_rdh
/** * make sure that isOneway is called before */ protected boolean isBackwardOneway(ReaderWay way) { return (way.hasTag("oneway", "-1") || way.hasTag("vehicle:forward", restrictedValues)) || way.hasTag("motor_vehicle:forward", restrictedValues); }
3.26
graphhopper_CarAccessParser_isForwardOneway_rdh
/** * make sure that isOneway is called before */ protected boolean isForwardOneway(ReaderWay way) { return ((!way.hasTag("oneway", "-1")) && (!way.hasTag("vehicle:forward", restrictedValues))) && (!way.hasTag("motor_vehicle:forward", restrictedValues)); }
3.26
graphhopper_VirtualEdgeIteratorState_getOriginalEdgeKey_rdh
/** * This method returns the original (not virtual!) edge key. I.e. also the direction is * already correctly encoded. * * @see EdgeIteratorState#getEdgeKey() */ public int getOriginalEdgeKey() { return originalEdgeKey; }
3.26
graphhopper_MinHeapWithUpdate_peekValue_rdh
/** * * @return the value of the next element to be polled */ public float peekValue() { return vals[1]; }
3.26
graphhopper_MinHeapWithUpdate_peekId_rdh
/** * * @return the id of the next element to be polled, i.e. the same as calling poll() without removing the element */ public int peekId() { return tree[1]; }
3.26
graphhopper_MinHeapWithUpdate_contains_rdh
/** * * @return true if the heap contains an element with the given id */ public boolean contains(int id) { checkIdInRange(id); return positions[id] != NOT_PRESENT; }
3.26
graphhopper_MinHeapWithUpdate_update_rdh
/** * Updates the element with the given id. The complexity of this method is O(log(N)), just like push/poll. * Its illegal to update elements that are not contained in the heap. Use {@link #contains} to check the existence * of an id. */ public void update(int id, float value) { checkIdInRange(id); int index = positions[id]; if (index < 0) throw new IllegalStateException(("The heap does not contain: " + id) + ". Use the contains method to check this before calling update"); float prev = vals[index]; vals[index] = value; if (value > prev) percolateDown(index); else if (value < prev) percolateUp(index); }
3.26
graphhopper_AccessFilter_allEdges_rdh
/** * Accepts all edges that are either forward or backward according to the given accessEnc. * Edges where neither one of the flags is enabled will still not be accepted. If you need to retrieve all edges * regardless of their encoding use {@link EdgeFilter#ALL_EDGES} instead. */ public static AccessFilter allEdges(BooleanEncodedValue accessEnc) { return new AccessFilter(accessEnc, true, true); }
3.26
graphhopper_DistanceCalcEuclidean_calcNormalizedDist_rdh
/** * Returns the specified length in normalized meter. */ @Override public double calcNormalizedDist(double dist) { return dist * dist; }
3.26
graphhopper_AStar_setApproximation_rdh
/** * * @param approx * defines how distance to goal Node is approximated */ public AStar setApproximation(WeightApproximator approx) { weightApprox = approx; return this;}
3.26
graphhopper_MaxWeight_create_rdh
/** * Currently enables to store 0.1 to max=0.1*2⁸ tons and infinity. If a value is between the maximum and infinity * it is assumed to use the maximum value. To save bits it might make more sense to store only a few values like * it was done with the MappedDecimalEncodedValue still handling (or rounding) of unknown values is unclear. */public static DecimalEncodedValue create() { return new DecimalEncodedValueImpl(KEY, 8, 0, 0.1, false, false, true); }
3.26
graphhopper_Helper_degreeToInt_rdh
/** * Converts into an integer to be compatible with the still limited DataAccess class (accepts * only integer values). But this conversion also reduces memory consumption where the precision * loss is acceptable. As +- 180° and +-90° are assumed as maximum values. * * @return the integer of the specified degree */ public static int degreeToInt(double deg) { if (deg >= Double.MAX_VALUE) return Integer.MAX_VALUE; if (deg <= (-Double.MAX_VALUE)) return -Integer.MAX_VALUE; return ((int) (deg * DEGREE_FACTOR)); }
3.26
graphhopper_Helper_eleToInt_rdh
/** * Converts elevation value (in meters) into integer for storage. */ public static int eleToInt(double ele) { if (ele >= Integer.MAX_VALUE) return Integer.MAX_VALUE; return ((int) (ele * ELE_FACTOR)); }
3.26
graphhopper_Helper_createFormatter_rdh
/** * Creates a SimpleDateFormat with ENGLISH locale. */ public static DateFormat createFormatter(String str) { DateFormat df = new SimpleDateFormat(str, Locale.ENGLISH); df.setTimeZone(UTC); return df; }
3.26
graphhopper_Helper_keepIn_rdh
/** * This methods returns the value or min if too small or max if too big. */ public static double keepIn(double value, double min, double max) { return Math.max(min, Math.min(value, max)); }
3.26
graphhopper_Helper_isFileMapped_rdh
/** * Determines if the specified ByteBuffer is one which maps to a file! */ public static boolean isFileMapped(ByteBuffer bb) { if (bb instanceof MappedByteBuffer) { try { ((MappedByteBuffer) (bb)).isLoaded(); return true; } catch (UnsupportedOperationException ex) { } } return false; }
3.26
graphhopper_Helper_intToEle_rdh
/** * Converts the integer value retrieved from storage into elevation (in meters). Do not expect * more precision than meters although it currently is! */ public static double intToEle(int integEle) { if (integEle == Integer.MAX_VALUE) return Double.MAX_VALUE; return integEle / ELE_FACTOR;}
3.26
graphhopper_Helper_staticHashCode_rdh
/** * Produces a static hashcode for a string that is platform independent and still compatible to the default * of openjdk. Do not use for performance critical applications. * * @see String#hashCode() */ public static int staticHashCode(String str) { int len = str.length(); int val = 0; for (int idx = 0; idx < len; ++idx) { val = (31 * val) + str.charAt(idx); } return val; }
3.26
graphhopper_Helper_toObject_rdh
/** * This method probes the specified string for a boolean, int, long, float and double. If all this fails it returns * the unchanged string. */ public static Object toObject(String string) { if ("true".equalsIgnoreCase(string) || "false".equalsIgnoreCase(string)) return Boolean.parseBoolean(string); try { return Integer.parseInt(string);} catch (NumberFormatException ex) { try { return Long.parseLong(string); } catch (NumberFormatException ex2) { try { return Float.parseFloat(string); } catch (NumberFormatException ex3) { try { return Double.parseDouble(string); } catch (NumberFormatException ex4) { // give up and simply return the string return string; } } } } }
3.26
graphhopper_Helper_parseList_rdh
/** * parses a string like [a,b,c] */ public static List<String> parseList(String listStr) { String trimmed = listStr.trim(); if (trimmed.length() < 2) return Collections.emptyList(); String[] items = trimmed.substring(1, trimmed.length() - 1).split(","); List<String> result = new ArrayList<>(); for (String item : items) { String s = item.trim(); if (!s.isEmpty()) { result.add(s); } } return result; }
3.26
graphhopper_Helper_intToDegree_rdh
/** * Converts back the integer value. * * @return the degree value of the specified integer */ public static double intToDegree(int storedInt) { if (storedInt == Integer.MAX_VALUE) return Double.MAX_VALUE; if (storedInt == (-Integer.MAX_VALUE)) return -Double.MAX_VALUE; return ((double) (storedInt)) / DEGREE_FACTOR; }
3.26
graphhopper_Helper_round_rdh
/** * Round the value to the specified number of decimal places, i.e. decimalPlaces=2 means we round to two decimal * places. Using negative values like decimalPlaces=-2 means we round to two places before the decimal point. */ public static double round(double value, int decimalPlaces) { double factor = Math.pow(10, decimalPlaces); return Math.round(value * factor) / factor; }
3.26
graphhopper_Snap_calcSnappedPoint_rdh
/** * Calculates the closest point on the edge from the query point. If too close to a tower or pillar node this method * might change the snappedPosition and wayIndex. */ public void calcSnappedPoint(DistanceCalc distCalc) { if (closestEdge == null) throw new IllegalStateException("No closest edge?"); if (snappedPoint != null) throw new IllegalStateException("Calculate snapped point only once"); PointList fullPL = getClosestEdge().fetchWayGeometry(FetchMode.ALL); double tmpLat = fullPL.getLat(wayIndex); double tmpLon = fullPL.getLon(wayIndex); double tmpEle = fullPL.getEle(wayIndex); if (snappedPosition != Position.EDGE) { snappedPoint = new GHPoint3D(tmpLat, tmpLon, tmpEle); return; } double queryLat = getQueryPoint().lat; double queryLon = getQueryPoint().lon; double adjLat = fullPL.getLat(wayIndex + 1); double adjLon = fullPL.getLon(wayIndex + 1); if (distCalc.validEdgeDistance(queryLat, queryLon, tmpLat, tmpLon, adjLat, adjLon)) { GHPoint crossingPoint = distCalc.calcCrossingPointToEdge(queryLat, queryLon, tmpLat, tmpLon, adjLat, adjLon); double adjEle = fullPL.getEle(wayIndex + 1); // We want to prevent extra virtual nodes and very short virtual edges in case the snap/crossing point is // very close to a tower node. Since we delayed the calculation of the crossing point until here, we need // to correct the Snap.Position in these cases. Note that it is possible that the query point is very far // from the tower node, but the crossing point is still very close to it. if (considerEqual(crossingPoint.lat, crossingPoint.lon, tmpLat, tmpLon)) { snappedPosition = (wayIndex == 0) ? Position.TOWER : Position.PILLAR; snappedPoint = new GHPoint3D(tmpLat, tmpLon, tmpEle); } else if (considerEqual(crossingPoint.lat, crossingPoint.lon, adjLat, adjLon)) { wayIndex++; snappedPosition = (wayIndex == (fullPL.size() - 1)) ? Position.TOWER : Position.PILLAR; snappedPoint = new GHPoint3D(adjLat, adjLon, adjEle); } else { snappedPoint = new GHPoint3D(crossingPoint.lat, crossingPoint.lon, (tmpEle + adjEle) / 2); } } else { // outside of edge segment [wayIndex, wayIndex+1] should not happen for EDGE assert false : (((((("incorrect pos: " + snappedPosition) + " for ") + snappedPoint) + ", ") + fullPL) + ", ") + wayIndex; }}
3.26
graphhopper_Snap_getSnappedPosition_rdh
/** * * @return 0 if on edge. 1 if on pillar node and 2 if on tower node. */ public Position getSnappedPosition() { return snappedPosition; }
3.26
graphhopper_Snap_isValid_rdh
/** * * @return true if a closest node was found */ public boolean isValid() { return closestNode >= 0; }
3.26
graphhopper_Snap_getQueryDistance_rdh
/** * * @return the distance of the query to the snapped coordinates. In meter */ public double getQueryDistance() {return queryDistance; }
3.26
graphhopper_Snap_getSnappedPoint_rdh
/** * Calculates the position of the query point 'snapped' to a close road segment or node. Call * calcSnappedPoint before, if not, an IllegalStateException is thrown. */ public GHPoint3D getSnappedPoint() { if (snappedPoint == null) throw new IllegalStateException("Calculate snapped point before!"); return snappedPoint; }
3.26
graphhopper_VLongStorage_writeVLong_rdh
/** * Writes an long in a variable-length format. Writes between one and nine bytes. Smaller values * take fewer bytes. Negative numbers are not supported. * <p> * The format is described further in Lucene its DataOutput#writeVInt(int) * <p> * See DataInput readVLong of Lucene */ public final void writeVLong(long i) { assert i >= 0L; while ((i & (~0x7fL)) != 0L) { writeByte(((byte) ((i & 0x7fL) | 0x80L))); i >>>= 7; } writeByte(((byte) (i))); }
3.26
graphhopper_VLongStorage_readVLong_rdh
/** * Reads a long stored in variable-length format. Reads between one and nine bytes. Smaller * values take fewer bytes. Negative numbers are not supported. * <p> * The format is described further in DataOutput writeVInt(int) from Lucene. */ public long readVLong() { /* This is the original code of this method, but a Hotspot bug (see LUCENE-2975) corrupts the for-loop if readByte() is inlined. So the loop was unwinded! byte b = readByte(); long i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = readByte(); i |= (b & 0x7FL) << shift; } return i; */ byte b = readByte(); if (b >= 0) { return b; } long i = b & 0x7fL; b = readByte(); i |= (b & 0x7fL) << 7; if (b >= 0) {return i; } b = readByte();i |= (b & 0x7fL) << 14; if (b >= 0) { return i; } b = readByte(); i |= (b & 0x7fL) << 21; if (b >= 0) { return i; } b = readByte(); i |= (b & 0x7fL) << 28; if (b >= 0) { return i; } b = readByte(); i |= (b & 0x7fL) << 35; if (b >= 0) { return i; } b = readByte(); i |= (b & 0x7fL) << 42; if (b >= 0) { return i; } b = readByte(); i |= (b & 0x7fL) << 49; if (b >= 0) { return i; } b = readByte(); i |= (b & 0x7fL) << 56; if (b >= 0) { return i; } throw new RuntimeException("Invalid vLong detected (negative values disallowed)"); }
3.26
graphhopper_PathDetailsFromEdges_calcDetails_rdh
/** * Calculates the PathDetails for a Path. This method will return fast, if there are no calculators. * * @param pathBuilderFactory * Generates the relevant PathBuilders * @return List of PathDetails for this Path */ public static Map<String, List<PathDetail>> calcDetails(Path path, EncodedValueLookup evLookup, Weighting weighting, List<String> requestedPathDetails, PathDetailsBuilderFactory pathBuilderFactory, int previousIndex, Graph graph) { if ((!path.isFound()) || requestedPathDetails.isEmpty()) return Collections.emptyMap(); HashSet<String> uniquePD = new HashSet<>(requestedPathDetails.size()); Collection<String> v1 = requestedPathDetails.stream().filter(pd -> !uniquePD.add(pd)).collect(Collectors.toList()); if (!v1.isEmpty()) throw new IllegalArgumentException("Do not use duplicate path details: " + v1); List<PathDetailsBuilder> pathBuilders = pathBuilderFactory.createPathDetailsBuilders(requestedPathDetails, path, evLookup, weighting, graph); if (pathBuilders.isEmpty()) return Collections.emptyMap(); path.forEveryEdge(new PathDetailsFromEdges(pathBuilders, previousIndex)); Map<String, List<PathDetail>> pathDetails = new HashMap<>(pathBuilders.size());for (PathDetailsBuilder builder : pathBuilders) { Map.Entry<String, List<PathDetail>> entry = builder.build(); List<PathDetail> v6 = pathDetails.put(entry.getKey(), entry.getValue()); if (v6 != null) throw new IllegalStateException("Some PathDetailsBuilders use duplicate key: " + entry.getKey()); } return pathDetails; }
3.26
graphhopper_ArrayUtil_permutation_rdh
/** * Creates an IntArrayList filled with a permutation of the numbers 0,1,2,...,size-1 */ public static IntArrayList permutation(int size, Random rnd) { IntArrayList result = iota(size); shuffle(result, rnd); return result; }
3.26
graphhopper_ArrayUtil_withoutConsecutiveDuplicates_rdh
/** * Creates a copy of the given list where all consecutive duplicates are removed */ public static IntIndexedContainer withoutConsecutiveDuplicates(IntIndexedContainer arr) { IntArrayList result = new IntArrayList(); if (arr.isEmpty()) return result; int prev = arr.get(0); result.add(prev); for (int i = 1; i < arr.size(); i++) {int v20 = arr.get(i); if (v20 != prev) result.add(v20); prev = v20; } return result; }
3.26
graphhopper_ArrayUtil_iota_rdh
/** * Creates an IntArrayList filled with the integers 0,1,2,3,...,size-1 */ public static IntArrayList iota(int size) { return range(0, size); }
3.26
graphhopper_ArrayUtil_transform_rdh
/** * Maps one array using another, i.e. every element arr[x] is replaced by map[arr[x]] */ public static void transform(IntIndexedContainer arr, IntIndexedContainer map) { for (int i = 0; i < arr.size(); ++i) arr.set(i, map.get(arr.get(i))); }
3.26
graphhopper_ArrayUtil_invert_rdh
/** * Creates a new array where each element represents the index position of this element in the given array * or is set to -1 if this element does not appear in the input array. None of the elements of the input array may * be equal or larger than the arrays length. */ public static int[] invert(int[] arr) { int[] result = new int[arr.length]; Arrays.fill(result, -1); for (int i = 0; i < arr.length; i++) result[arr[i]] = i; return result; }
3.26
graphhopper_ArrayUtil_applyOrder_rdh
/** * Creates a copy of the given array such that it is ordered by the given order. * The order can be shorter or equal, but not longer than the array. */ public static int[] applyOrder(int[] arr, int[] order) { if (order.length > arr.length) throw new IllegalArgumentException("sort order must not be shorter than array"); int[] result = new int[order.length]; for (int i = 0; i < result.length; ++i) result[i] = arr[order[i]]; return result; }
3.26
graphhopper_ArrayUtil_shuffle_rdh
/** * Shuffles the elements of the given list in place and returns it */ public static IntArrayList shuffle(IntArrayList list, Random random) {int maxHalf = list.size() / 2; for (int x1 = 0; x1 < maxHalf; x1++) { int x2 = random.nextInt(maxHalf) + maxHalf; int tmp = list.buffer[x1]; list.buffer[x1] = list.buffer[x2]; list.buffer[x2] = tmp; } return list; }
3.26
graphhopper_ArrayUtil_zero_rdh
/** * Creates an IntArrayList filled with zeros */ public static IntArrayList zero(int size) { IntArrayList result = new IntArrayList(size); result.elementsCount = size; return result; }
3.26
graphhopper_ArrayUtil_range_rdh
/** * Creates an IntArrayList filled with the integers [startIncl,endExcl[ */ public static IntArrayList range(int startIncl, int endExcl) { IntArrayList result = new IntArrayList(endExcl - startIncl); result.elementsCount = endExcl - startIncl; for (int i = 0; i < result.size(); ++i) result.set(i, startIncl + i); return result; }
3.26
graphhopper_ArrayUtil_reverse_rdh
/** * Reverses the order of the given list's elements in place and returns it */ public static IntArrayList reverse(IntArrayList list) { final int[] buffer = list.buffer; int tmp; for (int start = 0, end = list.size() - 1; start < end; start++ , end--) { // swap the values tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return list; }
3.26