proj_name
stringclasses
26 values
relative_path
stringlengths
42
188
class_name
stringlengths
2
53
func_name
stringlengths
2
49
masked_class
stringlengths
68
178k
func_body
stringlengths
56
6.8k
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/OSMTollParser.java
OSMTollParser
handleWayTags
class OSMTollParser implements TagParser { private static final List<String> HGV_TAGS = Collections.unmodifiableList(Arrays.asList("toll:hgv", "toll:N2", "toll:N3")); private final EnumEncodedValue<Toll> tollEnc; public OSMTollParser(EnumEncodedValue<Toll> tollEnc) { this.tollEnc = tollEnc; } @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {<FILL_FUNCTION_BODY>} }
Toll toll; if (readerWay.hasTag("toll", "yes")) { toll = Toll.ALL; } else if (readerWay.hasTag(HGV_TAGS, "yes")) { toll = Toll.HGV; } else if (readerWay.hasTag("toll", "no")) { toll = Toll.NO; } else { toll = Toll.MISSING; } CountryRule countryRule = readerWay.getTag("country_rule", null); if (countryRule != null) toll = countryRule.getToll(readerWay, toll); tollEnc.setEnum(false, edgeId, edgeIntAccess, toll);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/OSMTrackTypeParser.java
OSMTrackTypeParser
handleWayTags
class OSMTrackTypeParser implements TagParser { private final EnumEncodedValue<TrackType> trackTypeEnc; public OSMTrackTypeParser(EnumEncodedValue<TrackType> trackTypeEnc) { this.trackTypeEnc = trackTypeEnc; } @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {<FILL_FUNCTION_BODY>} }
String trackTypeTag = readerWay.getTag("tracktype"); TrackType trackType = TrackType.find(trackTypeTag); if (trackType != MISSING) trackTypeEnc.setEnum(false, edgeId, edgeIntAccess, trackType);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/OSMWayIDParser.java
OSMWayIDParser
handleWayTags
class OSMWayIDParser implements TagParser { private final IntEncodedValue osmWayIdEnc; public OSMWayIDParser(IntEncodedValue osmWayIdEnc) { this.osmWayIdEnc = osmWayIdEnc; } @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {<FILL_FUNCTION_BODY>} }
if (way.getId() > osmWayIdEnc.getMaxStorableInt()) throw new IllegalArgumentException("Cannot store OSM way ID: " + way.getId() + " as it is too large (> " + osmWayIdEnc.getMaxStorableInt() + "). You can disable " + osmWayIdEnc.getName() + " if you do not " + "need to store the OSM way IDs"); int wayId = Math.toIntExact(way.getId()); osmWayIdEnc.setInt(false, edgeId, edgeIntAccess, wayId);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/RacingBikePriorityParser.java
RacingBikePriorityParser
collect
class RacingBikePriorityParser extends BikeCommonPriorityParser { public RacingBikePriorityParser(EncodedValueLookup lookup) { this(lookup.getDecimalEncodedValue(VehiclePriority.key("racingbike")), lookup.getDecimalEncodedValue(VehicleSpeed.key("racingbike")), lookup.getEnumEncodedValue(BikeNetwork.KEY, RouteNetwork.class)); } protected RacingBikePriorityParser(DecimalEncodedValue priorityEnc, DecimalEncodedValue speedEnc, EnumEncodedValue<RouteNetwork> bikeRouteEnc) { super(priorityEnc, speedEnc, bikeRouteEnc); addPushingSection("path"); preferHighwayTags.add("road"); preferHighwayTags.add("secondary"); preferHighwayTags.add("secondary_link"); preferHighwayTags.add("tertiary"); preferHighwayTags.add("tertiary_link"); preferHighwayTags.add("residential"); avoidHighwayTags.put("motorway", BAD); avoidHighwayTags.put("motorway_link", BAD); avoidHighwayTags.put("trunk", BAD); avoidHighwayTags.put("trunk_link", BAD); avoidHighwayTags.put("primary", AVOID_MORE); avoidHighwayTags.put("primary_link", AVOID_MORE); routeMap.put(INTERNATIONAL, BEST.getValue()); routeMap.put(NATIONAL, BEST.getValue()); routeMap.put(REGIONAL, VERY_NICE.getValue()); routeMap.put(LOCAL, UNCHANGED.getValue()); setSpecificClassBicycle("roadcycling"); avoidSpeedLimit = 81; } @Override void collect(ReaderWay way, double wayTypeSpeed, TreeMap<Double, PriorityCode> weightToPrioMap) {<FILL_FUNCTION_BODY>} }
super.collect(way, wayTypeSpeed, weightToPrioMap); String highway = way.getTag("highway"); if ("service".equals(highway) || "residential".equals(highway)) { weightToPrioMap.put(40d, SLIGHT_AVOID); } else if ("track".equals(highway)) { String trackType = way.getTag("tracktype"); if ("grade1".equals(trackType)) weightToPrioMap.put(110d, PREFER); else if (trackType == null || trackType.startsWith("grade")) weightToPrioMap.put(110d, AVOID_MORE); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/StateParser.java
StateParser
handleWayTags
class StateParser implements TagParser { private final EnumEncodedValue<State> stateEnc; public StateParser(EnumEncodedValue<State> stateEnc) { this.stateEnc = stateEnc; } @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {<FILL_FUNCTION_BODY>} }
State country = way.getTag("country_state", State.MISSING); stateEnc.setEnum(false, edgeId, edgeIntAccess, country);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/tour/MultiPointTour.java
MultiPointTour
getHeadingForIteration
class MultiPointTour extends TourStrategy { private final int allPoints; private final double initialHeading; public MultiPointTour(Random random, double distanceInMeter, int allPoints) { this(random, distanceInMeter, allPoints, Double.NaN); } public MultiPointTour(Random random, double distanceInMeter, int allPoints, double initialHeading) { super(random, distanceInMeter); this.allPoints = allPoints; if (Double.isNaN(initialHeading)) this.initialHeading = random.nextInt(360); else this.initialHeading = initialHeading; } @Override public int getNumberOfGeneratedPoints() { return allPoints - 1; } @Override public double getDistanceForIteration(int iteration) { return slightlyModifyDistance(overallDistance / (allPoints + 1)); } @Override public double getHeadingForIteration(int iteration) {<FILL_FUNCTION_BODY>} }
if (iteration == 0) return initialHeading; return initialHeading + 360.0 * iteration / allPoints;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/tour/TourStrategy.java
TourStrategy
slightlyModifyDistance
class TourStrategy { protected final Random random; protected final double overallDistance; public TourStrategy(Random random, double distanceInMeter) { this.random = random; this.overallDistance = distanceInMeter; } /** * Defines the number of points that are generated */ public abstract int getNumberOfGeneratedPoints(); /** * Returns the distance in meter that is used for the generated point of a certain iteration */ public abstract double getDistanceForIteration(int iteration); /** * Returns the north based heading between 0 and 360 for a certain iteration. */ public abstract double getHeadingForIteration(int iteration); /** * Modifies the Distance up to +-10% */ protected double slightlyModifyDistance(double distance) {<FILL_FUNCTION_BODY>} }
double distanceModification = random.nextDouble() * .1 * distance; if (random.nextBoolean()) distanceModification = -distanceModification; return distance + distanceModification;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/AbstractWeighting.java
AbstractWeighting
calcEdgeMillis
class AbstractWeighting implements Weighting { protected final BooleanEncodedValue accessEnc; protected final DecimalEncodedValue speedEnc; private final TurnCostProvider turnCostProvider; protected AbstractWeighting(BooleanEncodedValue accessEnc, DecimalEncodedValue speedEnc, TurnCostProvider turnCostProvider) { if (!Weighting.isValidName(getName())) throw new IllegalStateException("Not a valid name for a Weighting: " + getName()); this.accessEnc = accessEnc; this.speedEnc = speedEnc; this.turnCostProvider = turnCostProvider; } @Override public long calcEdgeMillis(EdgeIteratorState edgeState, boolean reverse) {<FILL_FUNCTION_BODY>} @Override public double calcTurnWeight(int inEdge, int viaNode, int outEdge) { return turnCostProvider.calcTurnWeight(inEdge, viaNode, outEdge); } @Override public long calcTurnMillis(int inEdge, int viaNode, int outEdge) { return turnCostProvider.calcTurnMillis(inEdge, viaNode, outEdge); } @Override public boolean hasTurnCosts() { return turnCostProvider != NO_TURN_COST_PROVIDER; } @Override public String toString() { return getName() + "|" + speedEnc.getName(); } }
if (reverse && !edgeState.getReverse(accessEnc) || !reverse && !edgeState.get(accessEnc)) throw new IllegalStateException("Calculating time should not require to read speed from edge in wrong direction. " + "(" + edgeState.getBaseNode() + " - " + edgeState.getAdjNode() + ") " + edgeState.fetchWayGeometry(FetchMode.ALL) + ", dist: " + edgeState.getDistance() + " " + "Reverse:" + reverse + ", fwd:" + edgeState.get(accessEnc) + ", bwd:" + edgeState.getReverse(accessEnc) + ", fwd-speed: " + edgeState.get(speedEnc) + ", bwd-speed: " + edgeState.getReverse(speedEnc)); double speed = reverse ? edgeState.getReverse(speedEnc) : edgeState.get(speedEnc); if (Double.isInfinite(speed) || Double.isNaN(speed) || speed < 0) throw new IllegalStateException("Invalid speed stored in edge! " + speed); if (speed == 0) throw new IllegalStateException("Speed cannot be 0 for unblocked edge, use access properties to mark edge blocked! Should only occur for shortest path calculation. See #242."); return Math.round(edgeState.getDistance() / speed * 3.6 * 1000);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/AvoidEdgesWeighting.java
AvoidEdgesWeighting
calcEdgeWeight
class AvoidEdgesWeighting extends AbstractAdjustedWeighting { // contains the edge IDs of the already visited edges protected IntSet avoidedEdges = new GHIntHashSet(); private double edgePenaltyFactor = 5.0; public AvoidEdgesWeighting(Weighting superWeighting) { super(superWeighting); } public AvoidEdgesWeighting setEdgePenaltyFactor(double edgePenaltyFactor) { this.edgePenaltyFactor = edgePenaltyFactor; return this; } public AvoidEdgesWeighting setAvoidedEdges(IntSet avoidedEdges) { this.avoidedEdges = avoidedEdges; return this; } @Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {<FILL_FUNCTION_BODY>} @Override public String getName() { return "avoid_edges"; } }
double weight = superWeighting.calcEdgeWeight(edgeState, reverse); if (avoidedEdges.contains(edgeState.getEdge())) return weight * edgePenaltyFactor; return weight;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/BalancedWeightApproximator.java
BalancedWeightApproximator
approximate
class BalancedWeightApproximator { private final WeightApproximator uniDirApproximatorForward, uniDirApproximatorReverse; // Constants to shift the estimate (reverse estimate) so that it is actually 0 at the destination (source). double fromOffset, toOffset; public BalancedWeightApproximator(WeightApproximator weightApprox) { if (weightApprox == null) throw new IllegalArgumentException("WeightApproximator cannot be null"); uniDirApproximatorForward = weightApprox; uniDirApproximatorReverse = weightApprox.reverse(); } public WeightApproximator getApproximation() { return uniDirApproximatorForward; } public void setFromTo(int from, int to) { uniDirApproximatorReverse.setTo(from); uniDirApproximatorForward.setTo(to); fromOffset = 0.5 * uniDirApproximatorForward.approximate(from); toOffset = 0.5 * uniDirApproximatorReverse.approximate(to); } public double approximate(int node, boolean reverse) {<FILL_FUNCTION_BODY>} public double getSlack() { return uniDirApproximatorForward.getSlack(); } @Override public String toString() { return uniDirApproximatorForward.toString(); } }
double weightApproximation = 0.5 * (uniDirApproximatorForward.approximate(node) - uniDirApproximatorReverse.approximate(node)); if (reverse) { return fromOffset - weightApproximation; } else { return toOffset + weightApproximation; }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/BeelineWeightApproximator.java
BeelineWeightApproximator
approximate
class BeelineWeightApproximator implements WeightApproximator { private final NodeAccess nodeAccess; private final Weighting weighting; private final double minWeightPerDistance; private DistanceCalc distanceCalc = DistanceCalcEarth.DIST_EARTH; private double toLat, toLon; private double epsilon = 1; public BeelineWeightApproximator(NodeAccess nodeAccess, Weighting weighting) { this.nodeAccess = nodeAccess; this.weighting = weighting; this.minWeightPerDistance = weighting.calcMinWeightPerDistance(); } @Override public void setTo(int toNode) { toLat = nodeAccess.getLat(toNode); toLon = nodeAccess.getLon(toNode); } public WeightApproximator setEpsilon(double epsilon) { this.epsilon = epsilon; return this; } @Override public WeightApproximator reverse() { return new BeelineWeightApproximator(nodeAccess, weighting).setDistanceCalc(distanceCalc).setEpsilon(epsilon); } @Override public double getSlack() { return 0; } @Override public double approximate(int fromNode) {<FILL_FUNCTION_BODY>} public BeelineWeightApproximator setDistanceCalc(DistanceCalc distanceCalc) { this.distanceCalc = distanceCalc; return this; } @Override public String toString() { return "beeline"; } }
double fromLat = nodeAccess.getLat(fromNode); double fromLon = nodeAccess.getLon(fromNode); double dist2goal = distanceCalc.calcDist(toLat, toLon, fromLat, fromLon); double weight2goal = minWeightPerDistance * dist2goal; return weight2goal * epsilon;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/DefaultTurnCostProvider.java
DefaultTurnCostProvider
calcTurnWeight
class DefaultTurnCostProvider implements TurnCostProvider { private final BooleanEncodedValue turnRestrictionEnc; private final TurnCostStorage turnCostStorage; private final int uTurnCostsInt; private final double uTurnCosts; public DefaultTurnCostProvider(BooleanEncodedValue turnRestrictionEnc, TurnCostStorage turnCostStorage) { this(turnRestrictionEnc, turnCostStorage, TurnCostsConfig.INFINITE_U_TURN_COSTS); } /** * @param uTurnCosts the costs of a u-turn in seconds, for {@link TurnCostsConfig#INFINITE_U_TURN_COSTS} the u-turn costs * will be infinite */ public DefaultTurnCostProvider(BooleanEncodedValue turnRestrictionEnc, TurnCostStorage turnCostStorage, int uTurnCosts) { if (uTurnCosts < 0 && uTurnCosts != INFINITE_U_TURN_COSTS) { throw new IllegalArgumentException("u-turn costs must be positive, or equal to " + INFINITE_U_TURN_COSTS + " (=infinite costs)"); } this.uTurnCostsInt = uTurnCosts; this.uTurnCosts = uTurnCosts < 0 ? Double.POSITIVE_INFINITY : uTurnCosts; if (turnCostStorage == null) { throw new IllegalArgumentException("No storage set to calculate turn weight"); } // if null the TurnCostProvider can be still useful for edge-based routing this.turnRestrictionEnc = turnRestrictionEnc; this.turnCostStorage = turnCostStorage; } public BooleanEncodedValue getTurnRestrictionEnc() { return turnRestrictionEnc; } @Override public double calcTurnWeight(int edgeFrom, int nodeVia, int edgeTo) {<FILL_FUNCTION_BODY>} @Override public long calcTurnMillis(int inEdge, int viaNode, int outEdge) { return (long) (1000 * calcTurnWeight(inEdge, viaNode, outEdge)); } @Override public String toString() { return "default_tcp_" + uTurnCostsInt; } }
if (!EdgeIterator.Edge.isValid(edgeFrom) || !EdgeIterator.Edge.isValid(edgeTo)) { return 0; } double tCost = 0; if (edgeFrom == edgeTo) { // note that the u-turn costs overwrite any turn costs set in TurnCostStorage tCost = uTurnCosts; } else { if (turnRestrictionEnc != null) tCost = turnCostStorage.get(turnRestrictionEnc, edgeFrom, nodeVia, edgeTo) ? Double.POSITIVE_INFINITY : 0; } return tCost;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/QueryGraphWeighting.java
QueryGraphWeighting
calcTurnWeight
class QueryGraphWeighting implements Weighting { private final Weighting weighting; private final int firstVirtualNodeId; private final int firstVirtualEdgeId; private final IntArrayList closestEdges; public QueryGraphWeighting(Weighting weighting, int firstVirtualNodeId, int firstVirtualEdgeId, IntArrayList closestEdges) { this.weighting = weighting; this.firstVirtualNodeId = firstVirtualNodeId; this.firstVirtualEdgeId = firstVirtualEdgeId; this.closestEdges = closestEdges; } @Override public double calcMinWeightPerDistance() { return weighting.calcMinWeightPerDistance(); } @Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) { return weighting.calcEdgeWeight(edgeState, reverse); } @Override public double calcTurnWeight(int inEdge, int viaNode, int outEdge) {<FILL_FUNCTION_BODY>} private boolean isUTurn(int inEdge, int outEdge) { return inEdge == outEdge; } @Override public long calcEdgeMillis(EdgeIteratorState edgeState, boolean reverse) { return weighting.calcEdgeMillis(edgeState, reverse); } @Override public long calcTurnMillis(int inEdge, int viaNode, int outEdge) { // todo: here we do not allow calculating turn weights that aren't turn times, also see #1590 return (long) (1000 * calcTurnWeight(inEdge, viaNode, outEdge)); } @Override public boolean hasTurnCosts() { return weighting.hasTurnCosts(); } @Override public String getName() { return weighting.getName(); } @Override public String toString() { return getName(); } private int getOriginalEdge(int edge) { return closestEdges.get((edge - firstVirtualEdgeId) / 2); } private boolean isVirtualNode(int node) { return node >= firstVirtualNodeId; } private boolean isVirtualEdge(int edge) { return edge >= firstVirtualEdgeId; } }
if (!EdgeIterator.Edge.isValid(inEdge) || !EdgeIterator.Edge.isValid(outEdge)) { return 0; } if (isVirtualNode(viaNode)) { if (isUTurn(inEdge, outEdge)) { // do not allow u-turns at virtual nodes, otherwise the route depends on whether or not there are // virtual via nodes, see #1672. note since we are turning between virtual edges here we need to compare // the *virtual* edge ids (the orig edge would always be the same for all virtual edges at a virtual // node), see #1593 return Double.POSITIVE_INFINITY; } else { return 0; } } // to calculate the actual turn costs or detect u-turns we need to look at the original edge of each virtual // edge, see #1593 if (isVirtualEdge(inEdge)) { inEdge = getOriginalEdge(inEdge); } if (isVirtualEdge(outEdge)) { outEdge = getOriginalEdge(outEdge); } return weighting.calcTurnWeight(inEdge, viaNode, outEdge);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/SpeedWeighting.java
SpeedWeighting
calcTurnWeight
class SpeedWeighting implements Weighting { private final DecimalEncodedValue speedEnc; private final TurnCostProvider turnCostProvider; public SpeedWeighting(DecimalEncodedValue speedEnc) { this(speedEnc, TurnCostProvider.NO_TURN_COST_PROVIDER); } public SpeedWeighting(DecimalEncodedValue speedEnc, DecimalEncodedValue turnCostEnc, TurnCostStorage turnCostStorage, double uTurnCosts) { if (turnCostStorage == null || turnCostEnc == null) throw new IllegalArgumentException("This SpeedWeighting constructor expects turnCostEnc and turnCostStorage to be != null"); if (uTurnCosts < 0) throw new IllegalArgumentException("u-turn costs must be positive"); this.speedEnc = speedEnc; this.turnCostProvider = new TurnCostProvider() { @Override public double calcTurnWeight(int inEdge, int viaNode, int outEdge) {<FILL_FUNCTION_BODY>} @Override public long calcTurnMillis(int inEdge, int viaNode, int outEdge) { return (long) (1000 * calcTurnWeight(inEdge, viaNode, outEdge)); } }; } public SpeedWeighting(DecimalEncodedValue speedEnc, TurnCostProvider turnCostProvider) { this.speedEnc = speedEnc; this.turnCostProvider = turnCostProvider; } @Override public double calcMinWeightPerDistance() { return 1 / speedEnc.getMaxStorableDecimal(); } @Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) { double speed = reverse ? edgeState.getReverse(speedEnc) : edgeState.get(speedEnc); if (speed == 0) return Double.POSITIVE_INFINITY; return edgeState.getDistance() / speed; } @Override public long calcEdgeMillis(EdgeIteratorState edgeState, boolean reverse) { return (long) (1000 * calcEdgeWeight(edgeState, reverse)); } @Override public double calcTurnWeight(int inEdge, int viaNode, int outEdge) { return turnCostProvider.calcTurnWeight(inEdge, viaNode, outEdge); } @Override public long calcTurnMillis(int inEdge, int viaNode, int outEdge) { return turnCostProvider.calcTurnMillis(inEdge, viaNode, outEdge); } @Override public boolean hasTurnCosts() { return turnCostProvider != TurnCostProvider.NO_TURN_COST_PROVIDER; } @Override public String getName() { return "speed"; } }
if (!EdgeIterator.Edge.isValid(inEdge) || !EdgeIterator.Edge.isValid(outEdge)) return 0; if (inEdge == outEdge) return Math.max(turnCostStorage.get(turnCostEnc, inEdge, viaNode, outEdge), uTurnCosts); else return turnCostStorage.get(turnCostEnc, inEdge, viaNode, outEdge);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/custom/ConditionalExpressionVisitor.java
ConditionalExpressionVisitor
parse
class ConditionalExpressionVisitor implements Visitor.AtomVisitor<Boolean, Exception> { private static final Set<String> allowedMethodParents = new HashSet<>(Arrays.asList("edge", "Math")); private static final Set<String> allowedMethods = new HashSet<>(Arrays.asList("ordinal", "getDistance", "getName", "contains", "sqrt", "abs")); private final ParseResult result; private final TreeMap<Integer, Replacement> replacements = new TreeMap<>(); private final NameValidator variableValidator; private final ClassHelper classHelper; private String invalidMessage; public ConditionalExpressionVisitor(ParseResult result, NameValidator variableValidator, ClassHelper classHelper) { this.result = result; this.variableValidator = variableValidator; this.classHelper = classHelper; } // allow only methods and other identifiers (constants and encoded values) boolean isValidIdentifier(String identifier) { if (variableValidator.isValid(identifier)) { if (!Character.isUpperCase(identifier.charAt(0))) result.guessedVariables.add(identifier); return true; } return false; } @Override public Boolean visitRvalue(Java.Rvalue rv) throws Exception { if (rv instanceof Java.AmbiguousName) { Java.AmbiguousName n = (Java.AmbiguousName) rv; if (n.identifiers.length == 1) { String arg = n.identifiers[0]; if (arg.startsWith(IN_AREA_PREFIX)) { int start = rv.getLocation().getColumnNumber() - 1; replacements.put(start, new Replacement(start, arg.length(), CustomWeightingHelper.class.getSimpleName() + ".in(this." + arg + ", edge)")); result.guessedVariables.add(arg); return true; } else { // e.g. like road_class if (isValidIdentifier(arg)) return true; invalidMessage = "'" + arg + "' not available"; return false; } } invalidMessage = "identifier " + n + " invalid"; return false; } if (rv instanceof Java.Literal) { return true; } else if (rv instanceof Java.UnaryOperation) { Java.UnaryOperation uo = (Java.UnaryOperation) rv; if (uo.operator.equals("!")) return uo.operand.accept(this); if (uo.operator.equals("-")) return uo.operand.accept(this); return false; } else if (rv instanceof Java.MethodInvocation) { Java.MethodInvocation mi = (Java.MethodInvocation) rv; if (allowedMethods.contains(mi.methodName) && mi.target != null) { Java.AmbiguousName n = (Java.AmbiguousName) mi.target.toRvalue(); if (n.identifiers.length == 2) { if (allowedMethodParents.contains(n.identifiers[0])) { // edge.getDistance(), Math.sqrt(x) => check target name i.e. edge or Math if (mi.arguments.length == 0) { result.guessedVariables.add(n.identifiers[0]); // return "edge" return true; } else if (mi.arguments.length == 1) { // return "x" but verify before return mi.arguments[0].accept(this); } } else if (variableValidator.isValid(n.identifiers[0])) { // road_class.ordinal() if (mi.arguments.length == 0) { result.guessedVariables.add(n.identifiers[0]); // return road_class return true; } } } } invalidMessage = mi.methodName + " is an illegal method in a conditional expression"; return false; } else if (rv instanceof Java.ParenthesizedExpression) { return ((Java.ParenthesizedExpression) rv).value.accept(this); } else if (rv instanceof Java.BinaryOperation) { Java.BinaryOperation binOp = (Java.BinaryOperation) rv; int startRH = binOp.rhs.getLocation().getColumnNumber() - 1; if (binOp.lhs instanceof Java.AmbiguousName && ((Java.AmbiguousName) binOp.lhs).identifiers.length == 1) { String lhVarAsString = ((Java.AmbiguousName) binOp.lhs).identifiers[0]; boolean eqOps = binOp.operator.equals("==") || binOp.operator.equals("!="); if (binOp.rhs instanceof Java.AmbiguousName && ((Java.AmbiguousName) binOp.rhs).identifiers.length == 1) { // Make enum explicit as NO or OTHER can occur in other enums so convert "toll == NO" to "toll == Toll.NO" String rhValueAsString = ((Java.AmbiguousName) binOp.rhs).identifiers[0]; if (variableValidator.isValid(lhVarAsString) && Helper.toUpperCase(rhValueAsString).equals(rhValueAsString)) { if (!eqOps) throw new IllegalArgumentException("Operator " + binOp.operator + " not allowed for enum"); String value = classHelper.getClassName(binOp.lhs.toString()); replacements.put(startRH, new Replacement(startRH, rhValueAsString.length(), value + "." + rhValueAsString)); } } } return binOp.lhs.accept(this) && binOp.rhs.accept(this); } return false; } @Override public Boolean visitPackage(Java.Package p) { return false; } @Override public Boolean visitType(Java.Type t) { return false; } @Override public Boolean visitConstructorInvocation(Java.ConstructorInvocation ci) { return false; } /** * Enforce simple expressions of user input to increase security. * * @return ParseResult with ok if it is a valid and "simple" expression. It contains all guessed variables and a * converted expression that includes class names for constants to avoid conflicts e.g. when doing "toll == Toll.NO" * instead of "toll == NO". */ static ParseResult parse(String expression, NameValidator validator, ClassHelper helper) {<FILL_FUNCTION_BODY>} static class Replacement { int start; int oldLength; String newString; public Replacement(int start, int oldLength, String newString) { this.start = start; this.oldLength = oldLength; this.newString = newString; } } }
ParseResult result = new ParseResult(); try { Parser parser = new Parser(new Scanner("ignore", new StringReader(expression))); Java.Atom atom = parser.parseConditionalExpression(); // after parsing the expression the input should end (otherwise it is not "simple") if (parser.peek().type == TokenType.END_OF_INPUT) { result.guessedVariables = new LinkedHashSet<>(); ConditionalExpressionVisitor visitor = new ConditionalExpressionVisitor(result, validator, helper); result.ok = atom.accept(visitor); result.invalidMessage = visitor.invalidMessage; if (result.ok) { result.converted = new StringBuilder(expression.length()); int start = 0; for (Replacement replace : visitor.replacements.values()) { result.converted.append(expression, start, replace.start).append(replace.newString); start = replace.start + replace.oldLength; } result.converted.append(expression.substring(start)); } } } catch (Exception ex) { } return result;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/custom/CustomWeighting.java
CustomWeighting
calcEdgeWeight
class CustomWeighting implements Weighting { public static final String NAME = "custom"; /** * Converting to seconds is not necessary but makes adding other penalties easier (e.g. turn * costs or traffic light costs etc) */ private final static double SPEED_CONV = 3.6; private final double distanceInfluence; private final double headingPenaltySeconds; private final EdgeToDoubleMapping edgeToSpeedMapping; private final EdgeToDoubleMapping edgeToPriorityMapping; private final TurnCostProvider turnCostProvider; private final MaxCalc maxPrioCalc; private final MaxCalc maxSpeedCalc; public CustomWeighting(TurnCostProvider turnCostProvider, Parameters parameters) { if (!Weighting.isValidName(getName())) throw new IllegalStateException("Not a valid name for a Weighting: " + getName()); this.turnCostProvider = turnCostProvider; this.edgeToSpeedMapping = parameters.getEdgeToSpeedMapping(); this.maxSpeedCalc = parameters.getMaxSpeedCalc(); this.edgeToPriorityMapping = parameters.getEdgeToPriorityMapping(); this.maxPrioCalc = parameters.getMaxPrioCalc(); this.headingPenaltySeconds = parameters.getHeadingPenaltySeconds(); // given unit is s/km -> convert to s/m this.distanceInfluence = parameters.getDistanceInfluence() / 1000.0; if (this.distanceInfluence < 0) throw new IllegalArgumentException("distance_influence cannot be negative " + this.distanceInfluence); } @Override public double calcMinWeightPerDistance() { return 1d / (maxSpeedCalc.calcMax() / SPEED_CONV) / maxPrioCalc.calcMax() + distanceInfluence; } @Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {<FILL_FUNCTION_BODY>} double calcSeconds(double distance, EdgeIteratorState edgeState, boolean reverse) { double speed = edgeToSpeedMapping.get(edgeState, reverse); if (speed == 0) return Double.POSITIVE_INFINITY; if (speed < 0) throw new IllegalArgumentException("Speed cannot be negative"); return distance / speed * SPEED_CONV; } @Override public long calcEdgeMillis(EdgeIteratorState edgeState, boolean reverse) { return Math.round(calcSeconds(edgeState.getDistance(), edgeState, reverse) * 1000); } @Override public double calcTurnWeight(int inEdge, int viaNode, int outEdge) { return turnCostProvider.calcTurnWeight(inEdge, viaNode, outEdge); } @Override public long calcTurnMillis(int inEdge, int viaNode, int outEdge) { return turnCostProvider.calcTurnMillis(inEdge, viaNode, outEdge); } @Override public boolean hasTurnCosts() { return turnCostProvider != NO_TURN_COST_PROVIDER; } @Override public String getName() { return NAME; } @FunctionalInterface public interface EdgeToDoubleMapping { double get(EdgeIteratorState edge, boolean reverse); } @FunctionalInterface public interface MaxCalc { double calcMax(); } public static class Parameters { private final EdgeToDoubleMapping edgeToSpeedMapping; private final EdgeToDoubleMapping edgeToPriorityMapping; private final MaxCalc maxSpeedCalc; private final MaxCalc maxPrioCalc; private final double distanceInfluence; private final double headingPenaltySeconds; public Parameters(EdgeToDoubleMapping edgeToSpeedMapping, MaxCalc maxSpeedCalc, EdgeToDoubleMapping edgeToPriorityMapping, MaxCalc maxPrioCalc, double distanceInfluence, double headingPenaltySeconds) { this.edgeToSpeedMapping = edgeToSpeedMapping; this.maxSpeedCalc = maxSpeedCalc; this.edgeToPriorityMapping = edgeToPriorityMapping; this.maxPrioCalc = maxPrioCalc; this.distanceInfluence = distanceInfluence; this.headingPenaltySeconds = headingPenaltySeconds; } public EdgeToDoubleMapping getEdgeToSpeedMapping() { return edgeToSpeedMapping; } public EdgeToDoubleMapping getEdgeToPriorityMapping() { return edgeToPriorityMapping; } public MaxCalc getMaxSpeedCalc() { return maxSpeedCalc; } public MaxCalc getMaxPrioCalc() { return maxPrioCalc; } public double getDistanceInfluence() { return distanceInfluence; } public double getHeadingPenaltySeconds() { return headingPenaltySeconds; } } }
double priority = edgeToPriorityMapping.get(edgeState, reverse); if (priority == 0) return Double.POSITIVE_INFINITY; final double distance = edgeState.getDistance(); double seconds = calcSeconds(distance, edgeState, reverse); if (Double.isInfinite(seconds)) return Double.POSITIVE_INFINITY; // add penalty at start/stop/via points if (edgeState.get(EdgeIteratorState.UNFAVORED_EDGE)) seconds += headingPenaltySeconds; double distanceCosts = distance * distanceInfluence; if (Double.isInfinite(distanceCosts)) return Double.POSITIVE_INFINITY; return seconds / priority + distanceCosts;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/custom/CustomWeightingHelper.java
CustomWeightingHelper
calcMaxSpeed
class CustomWeightingHelper { static double GLOBAL_MAX_SPEED = 999; static double GLOBAL_PRIORITY = 1; protected EncodedValueLookup lookup; protected CustomModel customModel; protected CustomWeightingHelper() { } public void init(CustomModel customModel, EncodedValueLookup lookup, Map<String, JsonFeature> areas) { this.lookup = lookup; this.customModel = customModel; } public double getPriority(EdgeIteratorState edge, boolean reverse) { return getRawPriority(edge, reverse); } public double getSpeed(EdgeIteratorState edge, boolean reverse) { return getRawSpeed(edge, reverse); } protected final double getRawSpeed(EdgeIteratorState edge, boolean reverse) { return 1; } protected final double getRawPriority(EdgeIteratorState edge, boolean reverse) { return 1; } public final double calcMaxSpeed() {<FILL_FUNCTION_BODY>} public final double calcMaxPriority() { MinMax minMaxPriority = new MinMax(0, GLOBAL_PRIORITY); List<Statement> statements = customModel.getPriority(); if (!statements.isEmpty() && "true".equals(statements.get(0).getCondition())) { String value = statements.get(0).getValue(); if (lookup.hasEncodedValue(value)) minMaxPriority.max = lookup.getDecimalEncodedValue(value).getMaxOrMaxStorableDecimal(); } FindMinMax.findMinMax(minMaxPriority, statements, lookup); if (minMaxPriority.min < 0) throw new IllegalArgumentException("priority has to be >=0 but can be negative (" + minMaxPriority.min + ")"); if (minMaxPriority.max < 0) throw new IllegalArgumentException("maximum priority has to be >=0 but was " + minMaxPriority.max); return minMaxPriority.max; } public static boolean in(Polygon p, EdgeIteratorState edge) { BBox edgeBBox = GHUtility.createBBox(edge); BBox polyBBOX = p.getBounds(); if (!polyBBOX.intersects(edgeBBox)) return false; if (p.isRectangle() && polyBBOX.contains(edgeBBox)) return true; return p.intersects(edge.fetchWayGeometry(FetchMode.ALL).makeImmutable()); // TODO PERF: cache bbox and edge wayGeometry for multiple area } }
MinMax minMaxSpeed = new MinMax(0, GLOBAL_MAX_SPEED); FindMinMax.findMinMax(minMaxSpeed, customModel.getSpeed(), lookup); if (minMaxSpeed.min < 0) throw new IllegalArgumentException("speed has to be >=0 but can be negative (" + minMaxSpeed.min + ")"); if (minMaxSpeed.max <= 0) throw new IllegalArgumentException("maximum speed has to be >0 but was " + minMaxSpeed.max); if (minMaxSpeed.max == GLOBAL_MAX_SPEED) throw new IllegalArgumentException("The first statement for 'speed' must be unconditionally to set the speed. But it was " + customModel.getSpeed().get(0)); return minMaxSpeed.max;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/weighting/custom/FindMinMax.java
FindMinMax
findMinMaxForBlock
class FindMinMax { /** * This method throws an exception when this CustomModel would decrease the edge weight compared to the specified * baseModel as in such a case the optimality of A* with landmarks can no longer be guaranteed (as the preparation * is based on baseModel). */ public static void checkLMConstraints(CustomModel baseModel, CustomModel queryModel, EncodedValueLookup lookup) { if (queryModel.isInternal()) throw new IllegalArgumentException("CustomModel of query cannot be internal"); if (queryModel.getDistanceInfluence() != null) { double bmDI = baseModel.getDistanceInfluence() == null ? 0 : baseModel.getDistanceInfluence(); if (queryModel.getDistanceInfluence() < bmDI) throw new IllegalArgumentException("CustomModel in query can only use distance_influence bigger or equal to " + bmDI + ", but was: " + queryModel.getDistanceInfluence()); } checkMultiplyValue(queryModel.getPriority(), lookup); checkMultiplyValue(queryModel.getSpeed(), lookup); } private static void checkMultiplyValue(List<Statement> list, EncodedValueLookup lookup) { for (Statement statement : list) { if (statement.getOperation() == Statement.Op.MULTIPLY) { MinMax minMax = ValueExpressionVisitor.findMinMax(statement.getValue(), lookup); if (minMax.max > 1) throw new IllegalArgumentException("maximum of value '" + statement.getValue() + "' cannot be larger than 1, but was: " + minMax.max); else if (minMax.min < 0) throw new IllegalArgumentException("minimum of value '" + statement.getValue() + "' cannot be smaller than 0, but was: " + minMax.min); } } } /** * This method returns the smallest value possible in "min" and the smallest value that cannot be * exceeded by any edge in max. */ static MinMax findMinMax(MinMax minMax, List<Statement> statements, EncodedValueLookup lookup) { // 'blocks' of the statements are applied one after the other. A block consists of one (if) or more statements (elseif+else) List<List<Statement>> blocks = CustomModelParser.splitIntoBlocks(statements); for (List<Statement> block : blocks) findMinMaxForBlock(minMax, block, lookup); return minMax; } private static void findMinMaxForBlock(final MinMax minMax, List<Statement> block, EncodedValueLookup lookup) {<FILL_FUNCTION_BODY>} }
if (block.isEmpty() || !IF.equals(block.get(0).getKeyword())) throw new IllegalArgumentException("Every block must start with an if-statement"); MinMax minMaxBlock; if (block.get(0).getCondition().trim().equals("true")) { minMaxBlock = block.get(0).getOperation().apply(minMax, ValueExpressionVisitor.findMinMax(block.get(0).getValue(), lookup)); if (minMaxBlock.max < 0) throw new IllegalArgumentException("statement resulted in negative value: " + block.get(0)); } else { minMaxBlock = new MinMax(Double.MAX_VALUE, 0); boolean foundElse = false; for (Statement s : block) { if (s.getKeyword() == ELSE) foundElse = true; MinMax tmp = s.getOperation().apply(minMax, ValueExpressionVisitor.findMinMax(s.getValue(), lookup)); if (tmp.max < 0) throw new IllegalArgumentException("statement resulted in negative value: " + s); minMaxBlock.min = Math.min(minMaxBlock.min, tmp.min); minMaxBlock.max = Math.max(minMaxBlock.max, tmp.max); } // if there is no 'else' statement it's like there is a 'neutral' branch that leaves the initial value as is if (!foundElse) { minMaxBlock.min = Math.min(minMaxBlock.min, minMax.min); minMaxBlock.max = Math.max(minMaxBlock.max, minMax.max); } } minMax.min = minMaxBlock.min; minMax.max = minMaxBlock.max;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/AbstractDataAccess.java
AbstractDataAccess
readHeader
class AbstractDataAccess implements DataAccess { protected static final int SEGMENT_SIZE_MIN = 1 << 7; // reserve some space for downstream usage (in classes using/extending this) protected static final int HEADER_OFFSET = 20 * 4 + 20; protected static final byte[] EMPTY = new byte[1024]; private static final int SEGMENT_SIZE_DEFAULT = 1 << 20; protected final ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; protected final BitUtil bitUtil = BitUtil.LITTLE; private final String location; protected int[] header = new int[(HEADER_OFFSET - 20) / 4]; protected String name; protected int segmentSizeInBytes; protected int segmentSizePower; protected int indexDivisor; protected boolean closed = false; public AbstractDataAccess(String name, String location, int segmentSize) { this.name = name; if (!Helper.isEmpty(location) && !location.endsWith("/")) throw new IllegalArgumentException("Create DataAccess object via its corresponding Directory!"); this.location = location; if (segmentSize < 0) segmentSize = SEGMENT_SIZE_DEFAULT; setSegmentSize(segmentSize); } @Override public String getName() { return name; } protected String getFullName() { return location + name; } @Override public void close() { closed = true; } @Override public boolean isClosed() { return closed; } @Override public void setHeader(int bytePos, int value) { bytePos >>= 2; header[bytePos] = value; } @Override public int getHeader(int bytePos) { bytePos >>= 2; return header[bytePos]; } /** * Writes some internal data into the beginning of the specified file. */ protected void writeHeader(RandomAccessFile file, long length, int segmentSize) throws IOException { file.seek(0); file.writeUTF("GH"); file.writeLong(length); file.writeInt(segmentSize); for (int i = 0; i < header.length; i++) { file.writeInt(header[i]); } } protected long readHeader(RandomAccessFile raFile) throws IOException {<FILL_FUNCTION_BODY>} protected void copyHeader(DataAccess da) { for (int h = 0; h < header.length * 4; h += 4) { da.setHeader(h, getHeader(h)); } } DataAccess setSegmentSize(int bytes) { if (bytes > 0) { // segment size should be a power of 2 int tmp = (int) (Math.log(bytes) / Math.log(2)); segmentSizeInBytes = Math.max((int) Math.pow(2, tmp), SEGMENT_SIZE_MIN); } segmentSizePower = (int) (Math.log(segmentSizeInBytes) / Math.log(2)); indexDivisor = segmentSizeInBytes - 1; return this; } @Override public int getSegmentSize() { return segmentSizeInBytes; } @Override public String toString() { return getFullName(); } public boolean isStoring() { return true; } protected boolean isIntBased() { return false; } }
raFile.seek(0); if (raFile.length() == 0) return -1; String versionHint = raFile.readUTF(); if (!"GH".equals(versionHint)) throw new IllegalArgumentException("Not a GraphHopper file " + getFullName() + "! Expected 'GH' as file marker but was " + versionHint); long bytes = raFile.readLong(); setSegmentSize(raFile.readInt()); for (int i = 0; i < header.length; i++) { header[i] = raFile.readInt(); } return bytes;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/CHConfig.java
CHConfig
equals
class CHConfig { /** * will be used to store and identify the CH graph data on disk */ private final String chGraphName; private final Weighting weighting; private final boolean edgeBased; public static CHConfig nodeBased(String chGraphName, Weighting weighting) { return new CHConfig(chGraphName, weighting, false); } public static CHConfig edgeBased(String chGraphName, Weighting weighting) { return new CHConfig(chGraphName, weighting, true); } public CHConfig(String chGraphName, Weighting weighting, boolean edgeBased) { validateProfileName(chGraphName); this.chGraphName = chGraphName; this.weighting = weighting; this.edgeBased = edgeBased; } public Weighting getWeighting() { return weighting; } public boolean isEdgeBased() { return edgeBased; } public TraversalMode getTraversalMode() { return edgeBased ? TraversalMode.EDGE_BASED : TraversalMode.NODE_BASED; } public String toFileName() { return chGraphName; } public String toString() { return chGraphName; } public String getName() { return chGraphName; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return getName().hashCode(); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CHConfig chConfig = (CHConfig) o; return getName().equals(chConfig.getName());
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/CHStorageBuilder.java
CHStorageBuilder
checkNewShortcut
class CHStorageBuilder { private final CHStorage storage; public CHStorageBuilder(CHStorage chStorage) { // todo: maybe CHStorageBuilder should create CHStorage, not receive it here this.storage = chStorage; } public void setLevel(int node, int level) { storage.setLevel(storage.toNodePointer(node), level); } public void setLevelForAllNodes(int level) { for (int node = 0; node < storage.getNodes(); node++) setLevel(node, level); } public void setIdentityLevels() { for (int node = 0; node < storage.getNodes(); node++) setLevel(node, node); } public int addShortcutNodeBased(int a, int b, int accessFlags, double weight, int skippedEdge1, int skippedEdge2) { checkNewShortcut(a, b); int shortcut = storage.shortcutNodeBased(a, b, accessFlags, weight, skippedEdge1, skippedEdge2); // we keep track of the last shortcut for each node (-1 if there are no shortcuts), but // we do not register the shortcut at node b, because b is the higher level node (so no need to 'see' the lower // level node a) setLastShortcut(a, shortcut); return shortcut; } /** * @param origKeyFirst The first original edge key that is skipped by this shortcut *in the direction of the shortcut*. * This definition assumes that edge-based shortcuts are one-directional, and they are. * For example for the following shortcut edge from x to y: x->u->v->w->y , * which skips the shortcuts x->v and v->y the first original edge key would be the one of the edge x->u * @param origKeyLast like origKeyFirst, but the last orig edge key, i.e. the key of w->y in above example */ public int addShortcutEdgeBased(int a, int b, int accessFlags, double weight, int skippedEdge1, int skippedEdge2, int origKeyFirst, int origKeyLast) { checkNewShortcut(a, b); int shortcut = storage.shortcutEdgeBased(a, b, accessFlags, weight, skippedEdge1, skippedEdge2, origKeyFirst, origKeyLast); setLastShortcut(a, shortcut); return shortcut; } public void replaceSkippedEdges(IntUnaryOperator mapping) { for (int i = 0; i < storage.getShortcuts(); ++i) { long shortcutPointer = storage.toShortcutPointer(i); int skip1 = storage.getSkippedEdge1(shortcutPointer); int skip2 = storage.getSkippedEdge2(shortcutPointer); storage.setSkippedEdges(shortcutPointer, mapping.applyAsInt(skip1), mapping.applyAsInt(skip2)); } } private void checkNewShortcut(int a, int b) {<FILL_FUNCTION_BODY>} private void setLastShortcut(int node, int shortcut) { storage.setLastShortcut(storage.toNodePointer(node), shortcut); } private int getLevel(int node) { checkNodeId(node); return storage.getLevel(storage.toNodePointer(node)); } private void checkNodeId(int node) { if (node >= storage.getNodes() || node < 0) throw new IllegalArgumentException("node " + node + " is invalid. Not in [0," + storage.getNodes() + ")"); } }
checkNodeId(a); checkNodeId(b); if (getLevel(a) >= storage.getNodes() || getLevel(a) < 0) throw new IllegalArgumentException("Invalid level for node " + a + ": " + getLevel(a) + ". Node a must" + " be assigned a valid level before we add shortcuts a->b or a<-b"); if (a != b && getLevel(a) == getLevel(b)) throw new IllegalArgumentException("Different nodes must not have the same level, got levels " + getLevel(a) + " and " + getLevel(b) + " for nodes " + a + " and " + b); if (a != b && getLevel(a) > getLevel(b)) throw new IllegalArgumentException("The level of nodeA must be smaller than the level of nodeB, but got: " + getLevel(a) + " and " + getLevel(b) + ". When inserting shortcut: " + a + "-" + b); if (storage.getShortcuts() > 0) { int prevNodeA = storage.getNodeA(storage.toShortcutPointer(storage.getShortcuts() - 1)); int prevLevelA = getLevel(prevNodeA); if (getLevel(a) < prevLevelA) { throw new IllegalArgumentException("Invalid level for node " + a + ": " + getLevel(a) + ". The level " + "must be equal to or larger than the lower level node of the previous shortcut (node: " + prevNodeA + ", level: " + prevLevelA + ")"); } }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/DAType.java
DAType
hashCode
class DAType { /** * The DA object is hold entirely in-memory. Loading and flushing is a no-op. See RAMDataAccess. */ public static final DAType RAM = new DAType(MemRef.HEAP, false, false, true); /** * Optimized RAM DA type for integer access. The set and getBytes methods cannot be used. */ public static final DAType RAM_INT = new DAType(MemRef.HEAP, false, true, true); /** * The DA object is hold entirely in-memory. It will read load disc and flush to it if they * equivalent methods are called. See RAMDataAccess. */ public static final DAType RAM_STORE = new DAType(MemRef.HEAP, true, false, true); /** * Optimized RAM_STORE DA type for integer access. The set and getBytes methods cannot be used. */ public static final DAType RAM_INT_STORE = new DAType(MemRef.HEAP, true, true, true); /** * Memory mapped DA object. See MMapDataAccess. */ public static final DAType MMAP = new DAType(MemRef.MMAP, true, false, true); /** * Read-only memory mapped DA object. To avoid write access useful for reading on mobile or * embedded data stores. */ public static final DAType MMAP_RO = new DAType(MemRef.MMAP, true, false, false); private final MemRef memRef; private final boolean storing; private final boolean integ; private final boolean allowWrites; public DAType(DAType type) { this(type.getMemRef(), type.isStoring(), type.isInteg(), type.isAllowWrites()); } public DAType(MemRef memRef, boolean storing, boolean integ, boolean allowWrites) { this.memRef = memRef; this.storing = storing; this.integ = integ; this.allowWrites = allowWrites; } public static DAType fromString(String dataAccess) { dataAccess = toUpperCase(dataAccess); DAType type; if (dataAccess.contains("SYNC")) throw new IllegalArgumentException("SYNC option is no longer supported, see #982"); else if (dataAccess.contains("MMAP_RO")) type = DAType.MMAP_RO; else if (dataAccess.contains("MMAP")) type = DAType.MMAP; else if (dataAccess.contains("UNSAFE")) throw new IllegalArgumentException("UNSAFE option is no longer supported, see #1620"); else if (dataAccess.equals("RAM")) type = DAType.RAM; else type = DAType.RAM_STORE; return type; } /** * Memory mapped or purely in memory? default is HEAP */ MemRef getMemRef() { return memRef; } public boolean isAllowWrites() { return allowWrites; } /** * @return true if data resides in the JVM heap. */ public boolean isInMemory() { return memRef == MemRef.HEAP; } public boolean isMMap() { return memRef == MemRef.MMAP; } /** * Temporary data or store (with loading and storing)? default is false */ public boolean isStoring() { return storing; } /** * Optimized for integer values? default is false */ public boolean isInteg() { return integ; } @Override public String toString() { String str; if (getMemRef() == MemRef.MMAP) str = "MMAP"; else str = "RAM"; if (isInteg()) str += "_INT"; if (isStoring()) str += "_STORE"; return str; } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final DAType other = (DAType) obj; if (this.memRef != other.memRef) return false; if (this.storing != other.storing) return false; if (this.integ != other.integ) return false; return true; } public enum MemRef { HEAP, MMAP } }
int hash = 7; hash = 59 * hash + 37 * this.memRef.hashCode(); hash = 59 * hash + (this.storing ? 1 : 0); hash = 59 * hash + (this.integ ? 1 : 0); return hash;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/GHDirectory.java
GHDirectory
remove
class GHDirectory implements Directory { protected final String location; private final DAType typeFallback; // first rule matches => LinkedHashMap private final Map<String, DAType> defaultTypes = new LinkedHashMap<>(); private final Map<String, Integer> mmapPreloads = new LinkedHashMap<>(); private final Map<String, DataAccess> map = Collections.synchronizedMap(new HashMap<>()); public GHDirectory(String _location, DAType defaultType) { this.typeFallback = defaultType; if (isEmpty(_location)) _location = new File("").getAbsolutePath(); if (!_location.endsWith("/")) _location += "/"; location = _location; File dir = new File(location); if (dir.exists() && !dir.isDirectory()) throw new RuntimeException("file '" + dir + "' exists but is not a directory"); } /** * Configure the DAType (specified by the value) of a single DataAccess object (specified by the key). For "MMAP" you * can prepend "preload." to the name and specify a percentage which preloads the DataAccess into physical memory of * the specified percentage (only applied for load, not for import). * As keys can be patterns the order is important and the LinkedHashMap is forced as type. */ public Directory configure(LinkedHashMap<String, String> config) { for (Map.Entry<String, String> kv : config.entrySet()) { String value = kv.getValue().trim(); if (kv.getKey().startsWith("preload.")) try { String pattern = kv.getKey().substring("preload.".length()); mmapPreloads.put(pattern, Integer.parseInt(value)); } catch (NumberFormatException ex) { throw new IllegalArgumentException("DataAccess " + kv.getKey() + " has an incorrect preload value: " + value); } else { String pattern = kv.getKey(); defaultTypes.put(pattern, DAType.fromString(value)); } } return this; } /** * Returns the preload value or 0 if no patterns match. * See {@link #configure(LinkedHashMap)} */ int getPreload(String name) { for (Map.Entry<String, Integer> entry : mmapPreloads.entrySet()) if (name.matches(entry.getKey())) return entry.getValue(); return 0; } public void loadMMap() { for (DataAccess da : map.values()) { if (!(da instanceof MMapDataAccess)) continue; int preload = getPreload(da.getName()); if (preload > 0) ((MMapDataAccess) da).load(preload); } } @Override public DataAccess create(String name) { return create(name, getDefault(name, typeFallback)); } @Override public DataAccess create(String name, int segmentSize) { return create(name, getDefault(name, typeFallback), segmentSize); } private DAType getDefault(String name, DAType typeFallback) { for (Map.Entry<String, DAType> entry : defaultTypes.entrySet()) if (name.matches(entry.getKey())) return entry.getValue(); return typeFallback; } @Override public DataAccess create(String name, DAType type) { return create(name, type, -1); } @Override public DataAccess create(String name, DAType type, int segmentSize) { if (!name.equals(toLowerCase(name))) throw new IllegalArgumentException("Since 0.7 DataAccess objects does no longer accept upper case names"); if (map.containsKey(name)) // we do not allow creating two DataAccess with the same name, because on disk there can only be one DA // per file name throw new IllegalStateException("DataAccess " + name + " has already been created"); DataAccess da; if (type.isInMemory()) { if (type.isInteg()) { if (type.isStoring()) da = new RAMIntDataAccess(name, location, true, segmentSize); else da = new RAMIntDataAccess(name, location, false, segmentSize); } else if (type.isStoring()) da = new RAMDataAccess(name, location, true, segmentSize); else da = new RAMDataAccess(name, location, false, segmentSize); } else if (type.isMMap()) { da = new MMapDataAccess(name, location, type.isAllowWrites(), segmentSize); } else { throw new IllegalArgumentException("DAType not supported " + type); } map.put(name, da); return da; } @Override public void close() { for (DataAccess da : map.values()) { da.close(); } map.clear(); } @Override public void clear() { for (DataAccess da : map.values()) { da.close(); removeBackingFile(da, da.getName()); } map.clear(); } @Override public void remove(String name) {<FILL_FUNCTION_BODY>} private void removeBackingFile(DataAccess da, String name) { if (da.getType().isStoring()) removeDir(new File(location + name)); } @Override public DAType getDefaultType() { return typeFallback; } /** * This method returns the default DAType of the specified DataAccess (as string). If preferInts is true then this * method returns e.g. RAM_INT if the type of the specified DataAccess is RAM. */ public DAType getDefaultType(String dataAccess, boolean preferInts) { DAType type = getDefault(dataAccess, typeFallback); if (preferInts && type.isInMemory()) return type.isStoring() ? RAM_INT_STORE : RAM_INT; return type; } public boolean isStoring() { return typeFallback.isStoring(); } @Override public Directory create() { if (isStoring()) new File(location).mkdirs(); return this; } @Override public String toString() { return getLocation(); } @Override public String getLocation() { return location; } @Override public Map<String, DataAccess> getDAs() { return map; } }
DataAccess old = map.remove(name); if (old == null) throw new IllegalStateException("Couldn't remove DataAccess: " + name); old.close(); removeBackingFile(old, name);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/GHNodeAccess.java
GHNodeAccess
setTurnCostIndex
class GHNodeAccess implements NodeAccess { private final BaseGraphNodesAndEdges store; public GHNodeAccess(BaseGraphNodesAndEdges store) { this.store = store; } @Override public void ensureNode(int nodeId) { store.ensureNodeCapacity(nodeId); } @Override public final void setNode(int nodeId, double lat, double lon, double ele) { store.ensureNodeCapacity(nodeId); store.setLat(store.toNodePointer(nodeId), lat); store.setLon(store.toNodePointer(nodeId), lon); if (store.withElevation()) { // meter precision is sufficient for now store.setEle(store.toNodePointer(nodeId), ele); store.bounds.update(lat, lon, ele); } else { store.bounds.update(lat, lon); } } @Override public final double getLat(int nodeId) { return store.getLat(store.toNodePointer(nodeId)); } @Override public final double getLon(int nodeId) { return store.getLon(store.toNodePointer(nodeId)); } @Override public final double getEle(int nodeId) { if (!store.withElevation()) throw new IllegalStateException("elevation is disabled"); return store.getEle(store.toNodePointer(nodeId)); } @Override public final void setTurnCostIndex(int index, int turnCostIndex) {<FILL_FUNCTION_BODY>} @Override public final int getTurnCostIndex(int index) { if (store.withTurnCosts()) return store.getTurnCostRef(store.toNodePointer(index)); else throw new AssertionError("This graph does not support turn costs"); } @Override public final boolean is3D() { return store.withElevation(); } @Override public int getDimension() { return store.withElevation() ? 3 : 2; } }
if (store.withTurnCosts()) { // todo: remove ensure? store.ensureNodeCapacity(index); store.setTurnCostRef(store.toNodePointer(index), turnCostIndex); } else { throw new AssertionError("This graph does not support turn costs"); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/IntsRef.java
IntsRef
isValid
class IntsRef implements Comparable<IntsRef> { /** * An IntsRef with an array of size 0. */ public static final IntsRef EMPTY = new IntsRef(0, false); /** * The contents of the IntsRef. Cannot be {@code null}. */ public final int[] ints; /** * Offset of first valid integer. */ public final int offset; /** * Length of used ints. */ public final int length; /** * Create a IntsRef pointing to a new int array of size <code>capacity</code> leading to capacity*32 bits. * Offset will be zero and length will be the capacity. */ public IntsRef(int capacity) { this(capacity, true); } private IntsRef(int capacity, boolean checked) { if (checked && capacity == 0) throw new IllegalArgumentException("Use instance EMPTY instead of capacity 0"); ints = new int[capacity]; length = capacity; offset = 0; } /** * This instance will directly reference ints w/o making a copy. * ints should not be null. */ public IntsRef(int[] ints, int offset, int length) { this.ints = ints; this.offset = offset; this.length = length; assert isValid(); } @Override public int hashCode() { final int prime = 31; int result = 0; final int end = offset + length; for (int i = offset; i < end; i++) { result = prime * result + ints[i]; } return result; } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other instanceof IntsRef) { return this.intsEquals((IntsRef) other); } return false; } public boolean intsEquals(IntsRef other) { if (length == other.length) { int otherUpto = other.offset; final int[] otherInts = other.ints; final int end = offset + length; for (int upto = offset; upto < end; upto++, otherUpto++) { if (ints[upto] != otherInts[otherUpto]) { return false; } } return true; } else { return false; } } /** * Signed int order comparison */ @Override public int compareTo(IntsRef other) { if (this == other) return 0; final int[] aInts = this.ints; int aUpto = this.offset; final int[] bInts = other.ints; int bUpto = other.offset; final int aStop = aUpto + Math.min(this.length, other.length); while (aUpto < aStop) { int aInt = aInts[aUpto++]; int bInt = bInts[bUpto++]; if (aInt > bInt) { return 1; } else if (aInt < bInt) { return -1; } } // One is a prefix of the other, or, they are equal: return this.length - other.length; } /** * Creates a new IntsRef that points to a copy of the ints from * <code>other</code> * <p> * The returned IntsRef will have a length of other.length * and an offset of zero. */ public static IntsRef deepCopyOf(IntsRef other) { return new IntsRef(Arrays.copyOfRange(other.ints, other.offset, other.offset + other.length), 0, other.length); } /** * Performs internal consistency checks. * Always returns true (or throws IllegalStateException) */ public boolean isValid() {<FILL_FUNCTION_BODY>} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); final int end = offset + length; for (int i = offset; i < end; i++) { if (i > offset) { sb.append(' '); } sb.append(Integer.toHexString(ints[i])); } sb.append(']'); return sb.toString(); } public boolean isEmpty() { for (int i = 0; i < ints.length; i++) { if (ints[i] != 0) return false; } return true; } }
if (ints == null) { throw new IllegalStateException("ints is null"); } if (length < 0) { throw new IllegalStateException("length is negative: " + length); } if (length > ints.length) { throw new IllegalStateException("length is out of bounds: " + length + ",ints.length=" + ints.length); } if (offset < 0) { throw new IllegalStateException("offset is negative: " + offset); } if (offset > ints.length) { throw new IllegalStateException("offset out of bounds: " + offset + ",ints.length=" + ints.length); } if (offset + length < 0) { throw new IllegalStateException("offset+length is negative: offset=" + offset + ",length=" + length); } if (offset + length > ints.length) { throw new IllegalStateException("offset+length out of bounds: offset=" + offset + ",length=" + length + ",ints.length=" + ints.length); } return true;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/NativeFSLockFactory.java
NativeFSLockFactory
tryLock
class NativeFSLockFactory implements LockFactory { private File lockDir; public NativeFSLockFactory() { } public NativeFSLockFactory(File dir) { this.lockDir = dir; } public static void main(String[] args) throws IOException { // trying FileLock mechanics in different processes File file = new File("tmp.lock"); file.createNewFile(); FileChannel channel = new RandomAccessFile(file, "r").getChannel(); boolean shared = true; FileLock lock1 = channel.tryLock(0, Long.MAX_VALUE, shared); System.out.println("locked " + lock1); System.in.read(); System.out.println("release " + lock1); lock1.release(); } @Override public void setLockDir(File lockDir) { this.lockDir = lockDir; } @Override public synchronized GHLock create(String fileName, boolean writeAccess) { if (lockDir == null) throw new RuntimeException("Set lockDir before creating " + (writeAccess ? "write" : "read") + " locks"); return new NativeLock(lockDir, fileName, writeAccess); } @Override public synchronized void forceRemove(String fileName, boolean writeAccess) { if (lockDir.exists()) { create(fileName, writeAccess).release(); File lockFile = new File(lockDir, fileName); if (lockFile.exists() && !lockFile.delete()) throw new RuntimeException("Cannot delete " + lockFile); } } static class NativeLock implements GHLock { private final String name; private final File lockDir; private final File lockFile; private final boolean writeLock; private RandomAccessFile tmpRaFile; private FileChannel tmpChannel; private FileLock tmpLock; private Exception failedReason; public NativeLock(File lockDir, String fileName, boolean writeLock) { this.name = fileName; this.lockDir = lockDir; this.lockFile = new File(lockDir, fileName); this.writeLock = writeLock; } @Override public synchronized boolean tryLock() {<FILL_FUNCTION_BODY>} private synchronized boolean lockExists() { return tmpLock != null; } @Override public synchronized boolean isLocked() { if (!lockFile.exists()) return false; if (lockExists()) return true; try { boolean obtained = tryLock(); if (obtained) release(); return !obtained; } catch (Exception ex) { return false; } } @Override public synchronized void release() { if (lockExists()) { try { failedReason = null; tmpLock.release(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { tmpLock = null; try { tmpChannel.close(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { tmpChannel = null; try { tmpRaFile.close(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { tmpRaFile = null; } } } lockFile.delete(); } } @Override public String getName() { return name; } @Override public Exception getObtainFailedReason() { return failedReason; } @Override public String toString() { return lockFile.toString(); } } }
// already locked if (lockExists()) return false; // on-the-fly: make sure directory exists if (!lockDir.exists()) { if (!lockDir.mkdirs()) throw new RuntimeException("Directory " + lockDir + " does not exist and cannot be created to place lock file there: " + lockFile); } if (!lockDir.isDirectory()) throw new IllegalArgumentException("lockDir has to be a directory: " + lockDir); try { failedReason = null; // we need write access even for read locks - in order to create the lock file! tmpRaFile = new RandomAccessFile(lockFile, "rw"); } catch (IOException ex) { failedReason = ex; return false; } try { tmpChannel = tmpRaFile.getChannel(); try { tmpLock = tmpChannel.tryLock(0, Long.MAX_VALUE, !writeLock); // OverlappingFileLockException is not an IOException! } catch (Exception ex) { failedReason = ex; } finally { if (tmpLock == null) { Helper.close(tmpChannel); tmpChannel = null; } } } finally { if (tmpChannel == null) { Helper.close(tmpRaFile); tmpRaFile = null; } } return lockExists();
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/RoutingCHEdgeIteratorImpl.java
RoutingCHEdgeIteratorImpl
next
class RoutingCHEdgeIteratorImpl extends RoutingCHEdgeIteratorStateImpl implements RoutingCHEdgeExplorer, RoutingCHEdgeIterator { private final BaseGraph.EdgeIteratorImpl baseIterator; private final boolean outgoing; private final boolean incoming; private int nextEdgeId; public static RoutingCHEdgeIteratorImpl outEdges(CHStorage chStore, BaseGraph baseGraph, Weighting weighting) { return new RoutingCHEdgeIteratorImpl(chStore, baseGraph, weighting, true, false); } public static RoutingCHEdgeIteratorImpl inEdges(CHStorage chStore, BaseGraph baseGraph, Weighting weighting) { return new RoutingCHEdgeIteratorImpl(chStore, baseGraph, weighting, false, true); } public RoutingCHEdgeIteratorImpl(CHStorage chStore, BaseGraph baseGraph, Weighting weighting, boolean outgoing, boolean incoming) { super(chStore, baseGraph, new BaseGraph.EdgeIteratorImpl(baseGraph, EdgeFilter.ALL_EDGES), weighting); this.baseIterator = (BaseGraph.EdgeIteratorImpl) super.baseEdgeState; this.outgoing = outgoing; this.incoming = incoming; } @Override EdgeIteratorState edgeState() { return baseIterator; } @Override public RoutingCHEdgeIterator setBaseNode(int baseNode) { assert baseGraph.isFrozen(); baseIterator.setBaseNode(baseNode); int lastShortcut = store.getLastShortcut(store.toNodePointer(baseNode)); nextEdgeId = edgeId = lastShortcut < 0 ? baseIterator.edgeId : baseGraph.getEdges() + lastShortcut; return this; } @Override public boolean next() {<FILL_FUNCTION_BODY>} @Override public String toString() { return getEdge() + " " + getBaseNode() + "-" + getAdjNode(); } private boolean finiteWeight(boolean reverse) { return !Double.isInfinite(getOrigEdgeWeight(reverse)); } }
// we first traverse shortcuts (in decreasing order) and when we are done we use the base iterator to traverse // the base edges as well. shortcuts are filtered using shortcutFilter, but base edges are only filtered by // access/finite weight. while (nextEdgeId >= baseGraph.getEdges()) { shortcutPointer = store.toShortcutPointer(nextEdgeId - baseGraph.getEdges()); baseNode = store.getNodeA(shortcutPointer); adjNode = store.getNodeB(shortcutPointer); edgeId = nextEdgeId; nextEdgeId--; if (nextEdgeId < baseGraph.getEdges() || store.getNodeA(store.toShortcutPointer(nextEdgeId - baseGraph.getEdges())) != baseNode) nextEdgeId = baseIterator.edgeId; // todo: note that it would be more efficient (but cost more memory) to separate in/out edges, // especially for edge-based where we do not use bidirectional shortcuts // this is needed for edge-based CH, see #1525 // background: we need to explicitly accept shortcut edges that are loops so they will be // found as 'incoming' edges no matter which directions we are looking at // todo: or maybe this is not really needed as edge-based shortcuts are not bidirectional anyway? if ((baseNode == adjNode && (store.getFwdAccess(shortcutPointer) || store.getBwdAccess(shortcutPointer))) || (outgoing && store.getFwdAccess(shortcutPointer) || incoming && store.getBwdAccess(shortcutPointer))) return true; } // similar to baseIterator.next(), but we apply our own filter and set edgeId while (EdgeIterator.Edge.isValid(baseIterator.nextEdgeId)) { baseIterator.goToNext(); // we update edgeId even when iterating base edges. is it faster to do this also for base/adjNode? edgeId = baseIterator.edgeId; if ((outgoing && finiteWeight(false)) || (incoming && finiteWeight(true))) return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/RoutingCHGraphImpl.java
RoutingCHGraphImpl
getEdgeIteratorState
class RoutingCHGraphImpl implements RoutingCHGraph { private final BaseGraph baseGraph; private final CHStorage chStorage; private final Weighting weighting; public static RoutingCHGraph fromGraph(BaseGraph baseGraph, CHStorage chStorage, CHConfig chConfig) { return new RoutingCHGraphImpl(baseGraph, chStorage, chConfig.getWeighting()); } public RoutingCHGraphImpl(BaseGraph baseGraph, CHStorage chStorage, Weighting weighting) { if (weighting.hasTurnCosts() && !chStorage.isEdgeBased()) throw new IllegalArgumentException("Weighting has turn costs, but CHStorage is node-based"); this.baseGraph = baseGraph; this.chStorage = chStorage; this.weighting = weighting; } @Override public int getNodes() { return baseGraph.getNodes(); } @Override public int getEdges() { return baseGraph.getEdges() + chStorage.getShortcuts(); } @Override public int getShortcuts() { return chStorage.getShortcuts(); } @Override public RoutingCHEdgeExplorer createInEdgeExplorer() { return RoutingCHEdgeIteratorImpl.inEdges(chStorage, baseGraph, weighting); } @Override public RoutingCHEdgeExplorer createOutEdgeExplorer() { return RoutingCHEdgeIteratorImpl.outEdges(chStorage, baseGraph, weighting); } @Override public RoutingCHEdgeIteratorState getEdgeIteratorState(int chEdge, int adjNode) {<FILL_FUNCTION_BODY>} @Override public int getLevel(int node) { return chStorage.getLevel(chStorage.toNodePointer(node)); } @Override public Graph getBaseGraph() { return baseGraph; } @Override public Weighting getWeighting() { return weighting; } @Override public boolean hasTurnCosts() { return weighting.hasTurnCosts(); } @Override public boolean isEdgeBased() { return chStorage.isEdgeBased(); } @Override public double getTurnWeight(int edgeFrom, int nodeVia, int edgeTo) { return weighting.calcTurnWeight(edgeFrom, nodeVia, edgeTo); } @Override public void close() { if (!baseGraph.isClosed()) baseGraph.close(); chStorage.close(); } }
RoutingCHEdgeIteratorStateImpl edgeState = new RoutingCHEdgeIteratorStateImpl(chStorage, baseGraph, new BaseGraph.EdgeIteratorStateImpl(baseGraph), weighting); if (edgeState.init(chEdge, adjNode)) return edgeState; // if edgeId exists, but adjacent nodes do not match return null;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/SimpleFSLockFactory.java
SimpleFSLockFactory
tryLock
class SimpleFSLockFactory implements LockFactory { private File lockDir; public SimpleFSLockFactory() { } public SimpleFSLockFactory(File dir) { this.lockDir = dir; } @Override public void setLockDir(File lockDir) { this.lockDir = lockDir; } @Override public synchronized GHLock create(String fileName, boolean writeAccess) { // TODO no read access-only support if (lockDir == null) throw new RuntimeException("Set lockDir before creating locks"); return new SimpleLock(lockDir, fileName); } @Override public synchronized void forceRemove(String fileName, boolean writeAccess) { if (lockDir.exists()) { File lockFile = new File(lockDir, fileName); if (lockFile.exists() && !lockFile.delete()) throw new RuntimeException("Cannot delete " + lockFile); } } static class SimpleLock implements GHLock { private final File lockDir; private final File lockFile; private final String name; private IOException failedReason; public SimpleLock(File lockDir, String fileName) { this.name = fileName; this.lockDir = lockDir; this.lockFile = new File(lockDir, fileName); } @Override public synchronized boolean tryLock() {<FILL_FUNCTION_BODY>} @Override public synchronized boolean isLocked() { return lockFile.exists(); } @Override public synchronized void release() { if (isLocked() && lockFile.exists() && !lockFile.delete()) throw new RuntimeException("Cannot release lock file: " + lockFile); } @Override public String getName() { return name; } @Override public synchronized Exception getObtainFailedReason() { return failedReason; } @Override public String toString() { return lockFile.toString(); } } }
// make sure directory exists, do it on-the-fly (not possible when setLockDir is called) if (!lockDir.exists()) { if (!lockDir.mkdirs()) throw new RuntimeException("Directory " + lockDir + " does not exist and cannot be created to place lock file there: " + lockFile); } // this test can only be performed after the dir has created! if (!lockDir.isDirectory()) throw new IllegalArgumentException("lockDir has to be a directory: " + lockDir); try { return lockFile.createNewFile(); } catch (IOException ex) { failedReason = ex; return false; }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/StorableProperties.java
StorableProperties
loadExisting
class StorableProperties { private static final Logger LOGGER = LoggerFactory.getLogger(StorableProperties.class); private final Map<String, String> map = new LinkedHashMap<>(); private final DataAccess da; private final Directory dir; public StorableProperties(Directory dir) { this.dir = dir; // reduce size int segmentSize = 1 << 15; this.da = dir.create("properties", segmentSize); } public synchronized boolean loadExisting() {<FILL_FUNCTION_BODY>} public synchronized void flush() { try { StringWriter sw = new StringWriter(); saveProperties(map, sw); // TODO at the moment the size is limited to da.segmentSize() ! byte[] bytes = sw.toString().getBytes(UTF_CS); da.setBytes(0, bytes, bytes.length); da.flush(); // todo: would not be needed if the properties file used a format that is compatible with common text tools if (dir.getDefaultType().isStoring()) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(dir.getLocation() + "/properties.txt"))) { writer.write(sw.toString()); } } } catch (IOException ex) { throw new RuntimeException(ex); } } public synchronized StorableProperties remove(String key) { map.remove(key); return this; } public synchronized StorableProperties putAll(Map<String, String> externMap) { map.putAll(externMap); return this; } public synchronized StorableProperties put(String key, String val) { map.put(key, val); return this; } /** * Before it saves this value it creates a string out of it. */ public synchronized StorableProperties put(String key, Object val) { if (!key.equals(toLowerCase(key))) throw new IllegalArgumentException("Do not use upper case keys (" + key + ") for StorableProperties since 0.7"); map.put(key, val.toString()); return this; } public synchronized String get(String key) { if (!key.equals(toLowerCase(key))) throw new IllegalArgumentException("Do not use upper case keys (" + key + ") for StorableProperties since 0.7"); return map.getOrDefault(key, ""); } public synchronized Map<String, String> getAll() { return map; } public synchronized void close() { da.close(); } public synchronized boolean isClosed() { return da.isClosed(); } public synchronized StorableProperties create(long size) { da.create(size); return this; } public synchronized long getCapacity() { return da.getCapacity(); } public synchronized boolean containsVersion() { return map.containsKey("nodes.version") || map.containsKey("edges.version") || map.containsKey("geometry.version") || map.containsKey("location_index.version") || map.containsKey("string_index.version"); } @Override public synchronized String toString() { return da.toString(); } static void loadProperties(Map<String, String> map, Reader tmpReader) throws IOException { BufferedReader reader = new BufferedReader(tmpReader); String line; try { while ((line = reader.readLine()) != null) { if (line.startsWith("//") || line.startsWith("#")) { continue; } if (Helper.isEmpty(line)) { continue; } int index = line.indexOf("="); if (index < 0) { LOGGER.warn("Skipping configuration at line:" + line); continue; } String field = line.substring(0, index); String value = line.substring(index + 1); map.put(field.trim(), value.trim()); } } finally { reader.close(); } } }
if (!da.loadExisting()) return false; int len = (int) da.getCapacity(); byte[] bytes = new byte[len]; da.getBytes(0, bytes, len); try { loadProperties(map, new StringReader(new String(bytes, UTF_CS))); return true; } catch (IOException ex) { throw new IllegalStateException(ex); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/VLongStorage.java
VLongStorage
writeVLong
class VLongStorage { private byte[] bytes; private int pointer = 0; public VLongStorage() { this(10); } public VLongStorage(int cap) { this(new byte[cap]); } public VLongStorage(byte[] bytes) { this.bytes = bytes; } public void seek(long pos) { // TODO long vs. int pointer = (int) pos; } public long getPosition() { return pointer; } public long getLength() { return bytes.length; } byte readByte() { byte b = bytes[pointer]; pointer++; return b; } void writeByte(byte b) { if (pointer >= bytes.length) { int cap = Math.max(10, (int) (pointer * 1.5f)); bytes = Arrays.copyOf(bytes, cap); } bytes[pointer] = b; pointer++; } /** * 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) {<FILL_FUNCTION_BODY>} /** * 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)"); } public void trimToSize() { if (bytes.length > pointer) { byte[] tmp = new byte[pointer]; System.arraycopy(bytes, 0, tmp, 0, pointer); bytes = tmp; } } public byte[] getBytes() { return bytes; } }
assert i >= 0L; while ((i & ~0x7FL) != 0L) { writeByte((byte) ((i & 0x7FL) | 0x80L)); i >>>= 7; } writeByte((byte) i);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/index/InMemConstructionIndex.java
InMemConstructionIndex
addToAllTilesOnLine
class InMemConstructionIndex { interface InMemEntry { boolean isLeaf(); } static class InMemLeafEntry extends IntArrayList implements InMemEntry { public InMemLeafEntry(int count) { super(count); } @Override public final boolean isLeaf() { return true; } @Override public String toString() { return "LEAF " + /*key +*/ " " + super.toString(); } IntArrayList getResults() { return this; } } static class InMemTreeEntry implements InMemEntry { InMemEntry[] subEntries; public InMemTreeEntry(int subEntryNo) { subEntries = new InMemEntry[subEntryNo]; } public InMemEntry getSubEntry(int index) { return subEntries[index]; } public void setSubEntry(int index, InMemEntry subEntry) { this.subEntries[index] = subEntry; } @Override public final boolean isLeaf() { return false; } @Override public String toString() { return "TREE"; } } final PixelGridTraversal pixelGridTraversal; final SpatialKeyAlgo keyAlgo; final int[] entries; final byte[] shifts; final InMemTreeEntry root; public InMemConstructionIndex(IndexStructureInfo indexStructureInfo) { this.root = new InMemTreeEntry(indexStructureInfo.getEntries()[0]); this.entries = indexStructureInfo.getEntries(); this.shifts = indexStructureInfo.getShifts(); this.pixelGridTraversal = indexStructureInfo.getPixelGridTraversal(); this.keyAlgo = indexStructureInfo.getKeyAlgo(); } public void addToAllTilesOnLine(final int value, final double lat1, final double lon1, final double lat2, final double lon2) {<FILL_FUNCTION_BODY>} void put(long key, int value) { put(key << (64 - keyAlgo.getBits()), root, 0, value); } private void put(long keyPart, InMemEntry entry, int depth, int value) { if (entry.isLeaf()) { InMemLeafEntry leafEntry = (InMemLeafEntry) entry; // Avoid adding the same edge id multiple times. // Since each edge id is handled only once, this can only happen when // this method is called several times in a row with the same edge id, // so it is enough to check the last entry. // (It happens when one edge has several segments. Every segment is traversed // on its own, without de-duplicating the tiles that are touched.) if (leafEntry.isEmpty() || leafEntry.get(leafEntry.size() - 1) != value) { leafEntry.add(value); } } else { int index = (int) (keyPart >>> (64 - shifts[depth])); keyPart = keyPart << shifts[depth]; InMemTreeEntry treeEntry = ((InMemTreeEntry) entry); InMemEntry subentry = treeEntry.getSubEntry(index); depth++; if (subentry == null) { if (depth == entries.length) { subentry = new InMemLeafEntry(4); } else { subentry = new InMemTreeEntry(entries[depth]); } treeEntry.setSubEntry(index, subentry); } put(keyPart, subentry, depth, value); } } }
if (!DIST_PLANE.isCrossBoundary(lon1, lon2)) { // Find all the tiles on the line from (y1, x1) to (y2, y2) in tile coordinates (y, x) pixelGridTraversal.traverse(new Coordinate(lon1, lat1), new Coordinate(lon2, lat2), p -> { long key = keyAlgo.encode((int) p.x, (int) p.y); put(key, value); }); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/index/IndexStructureInfo.java
IndexStructureInfo
create
class IndexStructureInfo { private final int[] entries; private final byte[] shifts; private final PixelGridTraversal pixelGridTraversal; private final SpatialKeyAlgo keyAlgo; private final BBox bounds; private final int parts; public IndexStructureInfo(int[] entries, byte[] shifts, PixelGridTraversal pixelGridTraversal, SpatialKeyAlgo keyAlgo, BBox bounds, int parts) { this.entries = entries; this.shifts = shifts; this.pixelGridTraversal = pixelGridTraversal; this.keyAlgo = keyAlgo; this.bounds = bounds; this.parts = parts; } public static IndexStructureInfo create(BBox bounds, int minResolutionInMeter) {<FILL_FUNCTION_BODY>} private static byte getShift(int entries) { byte b = (byte) Math.round(Math.log(entries) / Math.log(2)); if (b <= 0) throw new IllegalStateException("invalid shift:" + b); return b; } public int[] getEntries() { return entries; } public byte[] getShifts() { return shifts; } public PixelGridTraversal getPixelGridTraversal() { return pixelGridTraversal; } public SpatialKeyAlgo getKeyAlgo() { return keyAlgo; } public BBox getBounds() { return bounds; } public int getParts() { return parts; } public double getDeltaLat() { return (bounds.maxLat - bounds.minLat) / parts; } public double getDeltaLon() { return (bounds.maxLon - bounds.minLon) / parts; } }
// I still need to be able to save and load an empty LocationIndex, and I can't when the extent // is zero. if (!bounds.isValid()) bounds = new BBox(-10.0, 10.0, -10.0, 10.0); double lat = Math.min(Math.abs(bounds.maxLat), Math.abs(bounds.minLat)); double maxDistInMeter = Math.max( (bounds.maxLat - bounds.minLat) / 360 * C, (bounds.maxLon - bounds.minLon) / 360 * DIST_EARTH.calcCircumference(lat)); double tmp = maxDistInMeter / minResolutionInMeter; tmp = tmp * tmp; IntArrayList tmpEntries = new IntArrayList(); // the last one is always 4 to reduce costs if only a single entry tmp /= 4; while (tmp > 1) { int tmpNo; if (tmp >= 16) { tmpNo = 16; } else if (tmp >= 4) { tmpNo = 4; } else { break; } tmpEntries.add(tmpNo); tmp /= tmpNo; } tmpEntries.add(4); int[] entries = tmpEntries.toArray(); if (entries.length < 1) { // at least one depth should have been specified throw new IllegalStateException("depth needs to be at least 1"); } int depth = entries.length; byte[] shifts = new byte[depth]; int lastEntry = entries[0]; for (int i1 = 0; i1 < depth; i1++) { if (lastEntry < entries[i1]) { throw new IllegalStateException("entries should decrease or stay but was:" + Arrays.toString(entries)); } lastEntry = entries[i1]; shifts[i1] = getShift(entries[i1]); } int shiftSum = 0; long parts = 1; for (int i = 0; i < shifts.length; i++) { shiftSum += shifts[i]; parts *= entries[i]; } if (shiftSum > 64) throw new IllegalStateException("sum of all shifts does not fit into a long variable"); parts = (int) Math.round(Math.sqrt(parts)); return new IndexStructureInfo(entries, shifts, new PixelGridTraversal((int) parts, bounds), new SpatialKeyAlgo(shiftSum, bounds), bounds, (int) parts);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/index/PixelGridTraversal.java
PixelGridTraversal
traverse
class PixelGridTraversal { private final double deltaY; private final double deltaX; int parts; BBox bounds; public PixelGridTraversal(int parts, BBox bounds) { this.parts = parts; this.bounds = bounds; deltaY = (bounds.maxLat - bounds.minLat) / parts; deltaX = (bounds.maxLon - bounds.minLon) / parts; } public void traverse(Coordinate a, Coordinate b, Consumer<Coordinate> consumer) {<FILL_FUNCTION_BODY>} }
double ax = a.x - bounds.minLon; double ay = a.y - bounds.minLat; double bx = b.x - bounds.minLon; double by = b.y - bounds.minLat; int stepX = ax < bx ? 1 : -1; int stepY = ay < by ? 1 : -1; double tDeltaX = deltaX / Math.abs(bx - ax); double tDeltaY = deltaY / Math.abs(by - ay); // Bounding this with parts - 1 only concerns the case where we are exactly on the bounding box. // (The next cell would already start there..) int x = Math.min((int) (ax / deltaX), parts - 1); int y = Math.min((int) (ay / deltaY), parts - 1); int x2 = Math.min((int) (bx / deltaX), parts - 1); int y2 = Math.min((int) (by / deltaY), parts - 1); double tMaxX = ((x + (stepX < 0 ? 0 : 1)) * deltaX - ax) / (bx - ax); double tMaxY = ((y + (stepY < 0 ? 0 : 1)) * deltaY - ay) / (by - ay); consumer.accept(new Coordinate(x, y)); while (y != y2 || x != x2) { if ((tMaxX < tMaxY || y == y2) && x != x2) { tMaxX += tDeltaX; x += stepX; } else { tMaxY += tDeltaY; y += stepY; } consumer.accept(new Coordinate(x, y)); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/storage/index/Snap.java
Snap
getSnappedPoint
class Snap { public static final int INVALID_NODE = -1; private final GHPoint queryPoint; private double queryDistance = Double.MAX_VALUE; private int wayIndex = -1; private int closestNode = INVALID_NODE; private EdgeIteratorState closestEdge; private GHPoint3D snappedPoint; private Position snappedPosition; public Snap(double queryLat, double queryLon) { queryPoint = new GHPoint(queryLat, queryLon); } /** * Returns the closest matching node. This is either a tower node of the base graph * or a virtual node (see also {@link QueryGraph#create(BaseGraph, List)}). * * @return {@link #INVALID_NODE} if nothing found, this should be avoided via a call of 'isValid' */ public int getClosestNode() { return closestNode; } public void setClosestNode(int node) { closestNode = node; } /** * @return the distance of the query to the snapped coordinates. In meter */ public double getQueryDistance() { return queryDistance; } public void setQueryDistance(double dist) { queryDistance = dist; } public int getWayIndex() { return wayIndex; } public void setWayIndex(int wayIndex) { this.wayIndex = wayIndex; } /** * @return 0 if on edge. 1 if on pillar node and 2 if on tower node. */ public Position getSnappedPosition() { return snappedPosition; } public void setSnappedPosition(Position pos) { this.snappedPosition = pos; } /** * @return true if a closest node was found */ public boolean isValid() { return closestNode >= 0; } public EdgeIteratorState getClosestEdge() { return closestEdge; } public void setClosestEdge(EdgeIteratorState edge) { closestEdge = edge; } public GHPoint getQueryPoint() { return queryPoint; } /** * 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() {<FILL_FUNCTION_BODY>} public void setSnappedPoint(GHPoint3D point) { this.snappedPoint = point; } /** * 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, queryLon = getQueryPoint().lon; double adjLat = fullPL.getLat(wayIndex + 1), 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; } } public static boolean considerEqual(double lat, double lon, double lat2, double lon2) { return Math.abs(lat - lat2) < 1e-6 && Math.abs(lon - lon2) < 1e-6; } @Override public String toString() { if (closestEdge != null) return snappedPosition + ", " + closestNode + " " + closestEdge.getEdge() + ":" + closestEdge.getBaseNode() + "-" + closestEdge.getAdjNode() + " snap: [" + Helper.round6(snappedPoint.getLat()) + ", " + Helper.round6(snappedPoint.getLon()) + "]," + " query: [" + Helper.round6(queryPoint.getLat()) + "," + Helper.round6(queryPoint.getLon()) + "]"; return closestNode + ", " + queryPoint + ", " + wayIndex; } /** * Whether the query point is projected onto a tower node, pillar node or somewhere within * the closest edge. * <p> * Due to precision differences it is hard to define when something is exactly 90° or "on-node" * like TOWER or PILLAR or if it is more "on-edge" (EDGE). The default mechanism is to prefer * "on-edge" even if it could be 90°. To prefer "on-node" you could use e.g. GHPoint.equals with * a default precision of 1e-6. * <p> * * @see DistanceCalc#validEdgeDistance */ public enum Position { EDGE, TOWER, PILLAR } }
if (snappedPoint == null) throw new IllegalStateException("Calculate snapped point before!"); return snappedPoint;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/AngleCalc.java
AngleCalc
isClockwise
class AngleCalc { public static final AngleCalc ANGLE_CALC = new AngleCalc(); private final static double PI_4 = Math.PI / 4.0; private final static double PI_2 = Math.PI / 2.0; private final static double PI3_4 = 3.0 * Math.PI / 4.0; static double atan2(double y, double x) { // kludge to prevent 0/0 condition double absY = Math.abs(y) + 1e-10; double r, angle; if (x < 0.0) { r = (x + absY) / (absY - x); angle = PI3_4; } else { r = (x - absY) / (x + absY); angle = PI_4; } angle += (0.1963 * r * r - 0.9817) * r; if (y < 0.0) // negate if in quad III or IV return -angle; return angle; } public double calcOrientation(double lat1, double lon1, double lat2, double lon2) { return calcOrientation(lat1, lon1, lat2, lon2, true); } /** * Return orientation of line relative to east. * <p> * * @param exact If false the atan gets calculated faster, but it might contain small errors * @return Orientation in interval -pi to +pi where 0 is east */ public double calcOrientation(double lat1, double lon1, double lat2, double lon2, boolean exact) { double shrinkFactor = cos(toRadians((lat1 + lat2) / 2)); if (exact) return Math.atan2(lat2 - lat1, shrinkFactor * (lon2 - lon1)); else return atan2(lat2 - lat1, shrinkFactor * (lon2 - lon1)); } /** * convert north based clockwise azimuth (0, 360) into x-axis/east based angle (-Pi, Pi) */ public double convertAzimuth2xaxisAngle(double azimuth) { if (Double.compare(azimuth, 360) > 0 || Double.compare(azimuth, 0) < 0) { throw new IllegalArgumentException("Azimuth " + azimuth + " must be in (0, 360)"); } double angleXY = PI_2 - azimuth / 180. * Math.PI; if (angleXY < -Math.PI) angleXY += 2 * Math.PI; if (angleXY > Math.PI) angleXY -= 2 * Math.PI; return angleXY; } /** * Change the representation of an orientation, so the difference to the given baseOrientation * will be smaller or equal to PI (180 degree). This is achieved by adding or subtracting a * 2*PI, so the direction of the orientation will not be changed */ public double alignOrientation(double baseOrientation, double orientation) { double resultOrientation; if (baseOrientation >= 0) { if (orientation < -Math.PI + baseOrientation) resultOrientation = orientation + 2 * Math.PI; else resultOrientation = orientation; } else if (orientation > +Math.PI + baseOrientation) resultOrientation = orientation - 2 * Math.PI; else resultOrientation = orientation; return resultOrientation; } /** * Calculate the azimuth in degree for a line given by two coordinates. Direction in 'degree' * where 0 is north, 90 is east, 180 is south and 270 is west. */ public double calcAzimuth(double lat1, double lon1, double lat2, double lon2) { double orientation = Math.PI / 2 - calcOrientation(lat1, lon1, lat2, lon2); if (orientation < 0) orientation += 2 * Math.PI; return Math.toDegrees(Helper.round4(orientation)) % 360; } public String azimuth2compassPoint(double azimuth) { String cp; double slice = 360.0 / 16; if (azimuth < slice) { cp = "N"; } else if (azimuth < slice * 3) { cp = "NE"; } else if (azimuth < slice * 5) { cp = "E"; } else if (azimuth < slice * 7) { cp = "SE"; } else if (azimuth < slice * 9) { cp = "S"; } else if (azimuth < slice * 11) { cp = "SW"; } else if (azimuth < slice * 13) { cp = "W"; } else if (azimuth < slice * 15) { cp = "NW"; } else { cp = "N"; } return cp; } /** * @return true if the given vectors follow a clockwise order abc, bca or cab, * false if the order is counter-clockwise cba, acb or bac, e.g. this returns true: * a b * | / * 0 - c */ public boolean isClockwise(double aX, double aY, double bX, double bY, double cX, double cY) {<FILL_FUNCTION_BODY>} }
// simply compare angles between a,b and b,c final double angleDiff = (cX - aX) * (bY - aY) - (cY - aY) * (bX - aX); return angleDiff < 0;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/BreadthFirstSearch.java
BreadthFirstSearch
start
class BreadthFirstSearch extends XFirstSearch { @Override public void start(EdgeExplorer explorer, int startNode) {<FILL_FUNCTION_BODY>} }
SimpleIntDeque fifo = new SimpleIntDeque(); GHBitSet visited = createBitSet(); visited.add(startNode); fifo.push(startNode); int current; while (!fifo.isEmpty()) { current = fifo.pop(); if (!goFurther(current)) continue; EdgeIterator iter = explorer.setBaseNode(current); while (iter.next()) { int connectedId = iter.getAdjNode(); if (checkAdjacent(iter) && !visited.contains(connectedId)) { visited.add(connectedId); fifo.push(connectedId); } } }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/Constants.java
Constants
getMajorVersion
class Constants { /** * The value of <code>System.getProperty("java.version")</code>. * */ public static final String JAVA_VERSION = System.getProperty("java.version"); /** * The value of <code>System.getProperty("os.name")</code>. * */ public static final String OS_NAME = System.getProperty("os.name"); /** * True iff running on Linux. */ public static final boolean LINUX = OS_NAME.startsWith("Linux"); /** * True iff running on Windows. */ public static final boolean WINDOWS = OS_NAME.startsWith("Windows"); /** * True iff running on Mac OS X */ public static final boolean MAC_OS_X = OS_NAME.startsWith("Mac OS X"); public static final String OS_ARCH = System.getProperty("os.arch"); public static final String OS_VERSION = System.getProperty("os.version"); public static final String JAVA_VENDOR = System.getProperty("java.vendor"); public static final String JVM_SPEC_VERSION = System.getProperty("java.specification.version"); public static final boolean JRE_IS_MINIMUM_JAVA9; private static final int JVM_MAJOR_VERSION; private static final int JVM_MINOR_VERSION; public static final int VERSION_NODE = 9; public static final int VERSION_EDGE = 22; // this should be increased whenever the format of the serialized EncodingManager is changed public static final int VERSION_EM = 3; public static final int VERSION_SHORTCUT = 9; public static final int VERSION_NODE_CH = 0; public static final int VERSION_GEOMETRY = 6; public static final int VERSION_TURN_COSTS = 0; public static final int VERSION_LOCATION_IDX = 5; public static final int VERSION_KV_STORAGE = 2; /** * The version without the snapshot string */ public static final String VERSION; public static final String BUILD_DATE; /** * Details about the git commit this artifact was built for, can be null (if not built using maven) */ public static final GitInfo GIT_INFO; public static final boolean SNAPSHOT; static { final StringTokenizer st = new StringTokenizer(JVM_SPEC_VERSION, "."); JVM_MAJOR_VERSION = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { JVM_MINOR_VERSION = Integer.parseInt(st.nextToken()); } else { JVM_MINOR_VERSION = 0; } JRE_IS_MINIMUM_JAVA9 = JVM_MAJOR_VERSION > 1 || (JVM_MAJOR_VERSION == 1 && JVM_MINOR_VERSION >= 9); String version = "0.0"; try { // see com/graphhopper/version file in resources which is modified in the maven packaging process // to contain the current version List<String> v = readFile(new InputStreamReader(GraphHopper.class.getResourceAsStream("version"), UTF_CS)); version = v.get(0); } catch (Exception ex) { System.err.println("GraphHopper Initialization ERROR: cannot read version!? " + ex.getMessage()); } int indexM = version.indexOf("-"); if ("${project.version}".equals(version)) { VERSION = "0.0"; SNAPSHOT = true; System.err.println("GraphHopper Initialization WARNING: maven did not preprocess the version file! Do not use the jar for a release!"); } else if ("0.0".equals(version)) { VERSION = "0.0"; SNAPSHOT = true; System.err.println("GraphHopper Initialization WARNING: cannot get version!?"); } else { String tmp = version; // throw away the "-SNAPSHOT" if (indexM >= 0) tmp = version.substring(0, indexM); SNAPSHOT = toLowerCase(version).contains("-snapshot"); VERSION = tmp; } String buildDate = ""; try { List<String> v = readFile(new InputStreamReader(GraphHopper.class.getResourceAsStream("builddate"), UTF_CS)); buildDate = v.get(0); } catch (Exception ex) { } BUILD_DATE = buildDate; List<String> gitInfos = null; try { gitInfos = readFile(new InputStreamReader(GraphHopper.class.getResourceAsStream("gitinfo"), UTF_CS)); if (gitInfos.size() != 6) { System.err.println("GraphHopper Initialization WARNING: unexpected git info: " + gitInfos.toString()); gitInfos = null; } else if (gitInfos.get(1).startsWith("$")) { gitInfos = null; } } catch (Exception ex) { } GIT_INFO = gitInfos == null ? null : new GitInfo(gitInfos.get(1), gitInfos.get(2), gitInfos.get(3), gitInfos.get(4), Boolean.parseBoolean(gitInfos.get(5))); } public static String getVersions() { return VERSION_NODE + "," + VERSION_EDGE + "," + VERSION_GEOMETRY + "," + VERSION_LOCATION_IDX + "," + VERSION_KV_STORAGE + "," + VERSION_SHORTCUT; } public static String getMajorVersion() {<FILL_FUNCTION_BODY>} }
int firstIdx = VERSION.indexOf("."); if (firstIdx < 0) throw new IllegalStateException("Cannot extract major version from version " + VERSION); int sndIdx = VERSION.indexOf(".", firstIdx + 1); if (sndIdx < 0) return VERSION; return VERSION.substring(0, sndIdx);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/DepthFirstSearch.java
DepthFirstSearch
start
class DepthFirstSearch extends XFirstSearch { /** * beginning with startNode add all following nodes to LIFO queue. If node has been already * explored before, skip reexploration. */ @Override public void start(EdgeExplorer explorer, int startNode) {<FILL_FUNCTION_BODY>} }
IntArrayDeque stack = new IntArrayDeque(); GHBitSet explored = createBitSet(); stack.addLast(startNode); int current; while (stack.size() > 0) { current = stack.removeLast(); if (!explored.contains(current) && goFurther(current)) { EdgeIterator iter = explorer.setBaseNode(current); while (iter.next()) { int connectedId = iter.getAdjNode(); if (checkAdjacent(iter)) { stack.addLast(connectedId); } } explored.add(current); } }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/DistanceCalc3D.java
DistanceCalc3D
calcDist
class DistanceCalc3D extends DistanceCalcEarth { /** * @param fromHeight in meters above 0 * @param toHeight in meters above 0 */ public double calcDist(double fromLat, double fromLon, double fromHeight, double toLat, double toLon, double toHeight) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "EXACT3D"; } }
double len = super.calcDist(fromLat, fromLon, toLat, toLon); double delta = Math.abs(toHeight - fromHeight); return Math.sqrt(delta * delta + len * len);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/DistanceCalcEuclidean.java
DistanceCalcEuclidean
createBBox
class DistanceCalcEuclidean extends DistanceCalcEarth { @Override public double calcDist(double fromY, double fromX, double toY, double toX) { return sqrt(calcNormalizedDist(fromY, fromX, toY, toX)); } @Override public double calcDist3D(double fromY, double fromX, double fromHeight, double toY, double toX, double toHeight) { return sqrt(calcNormalizedDist(fromY, fromX, toY, toX) + calcNormalizedDist(toHeight - fromHeight)); } @Override public double calcDenormalizedDist(double normedDist) { return sqrt(normedDist); } /** * Returns the specified length in normalized meter. */ @Override public double calcNormalizedDist(double dist) { return dist * dist; } double calcShrinkFactor(double a_lat_deg, double b_lat_deg) { return 1.; } /** * Calculates in normalized meter */ @Override public double calcNormalizedDist(double fromY, double fromX, double toY, double toX) { double dX = fromX - toX; double dY = fromY - toY; return dX * dX + dY * dY; } @Override public String toString() { return "2D"; } @Override public double calcCircumference(double lat) { throw new UnsupportedOperationException("Not supported for the 2D Euclidean space"); } @Override public boolean isDateLineCrossOver(double lon1, double lon2) { throw new UnsupportedOperationException("Not supported for the 2D Euclidean space"); } @Override public BBox createBBox(double lat, double lon, double radiusInMeter) {<FILL_FUNCTION_BODY>} @Override public GHPoint projectCoordinate(double latInDeg, double lonInDeg, double distanceInMeter, double headingClockwiseFromNorth) { throw new UnsupportedOperationException("Not supported for the 2D Euclidean space"); } @Override public GHPoint intermediatePoint(double f, double lat1, double lon1, double lat2, double lon2) { double delatLat = lat2 - lat1; double deltaLon = lon2 - lon1; double midLat = lat1 + delatLat * f; double midLon = lon1 + deltaLon * f; return new GHPoint(midLat, midLon); } @Override public boolean isCrossBoundary(double lon1, double lon2) { throw new UnsupportedOperationException("Not supported for the 2D Euclidean space"); } @Override public double calcNormalizedEdgeDistance(double ry, double rx, double ay, double ax, double by, double bx) { return calcNormalizedEdgeDistance3D( ry, rx, 0, ay, ax, 0, by, bx, 0 ); } @Override public double calcNormalizedEdgeDistance3D(double ry, double rx, double rz, double ay, double ax, double az, double by, double bx, double bz) { double dx = bx - ax; double dy = by - ay; double dz = bz - az; double norm = dx * dx + dy * dy + dz * dz; double factor = ((rx - ax) * dx + (ry - ay) * dy + (rz - az) * dz) / norm; if (Double.isNaN(factor)) factor = 0; // x,y,z is projection of r onto segment a-b double cx = ax + factor * dx; double cy = ay + factor * dy; double cz = az + factor * dz; double rdx = cx - rx; double rdy = cy - ry; double rdz = cz - rz; return rdx * rdx + rdy * rdy + rdz * rdz; } }
throw new UnsupportedOperationException("Not supported for the 2D Euclidean space");
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/DistancePlaneProjection.java
DistancePlaneProjection
calcNormalizedDist
class DistancePlaneProjection extends DistanceCalcEarth { public static final DistancePlaneProjection DIST_PLANE = new DistancePlaneProjection(); @Override public double calcDist(double fromLat, double fromLon, double toLat, double toLon) { double normedDist = calcNormalizedDist(fromLat, fromLon, toLat, toLon); return R * sqrt(normedDist); } @Override public double calcDist3D(double fromLat, double fromLon, double fromHeight, double toLat, double toLon, double toHeight) { double dEleNorm = hasElevationDiff(fromHeight, toHeight) ? calcNormalizedDist(toHeight - fromHeight) : 0; double normedDist = calcNormalizedDist(fromLat, fromLon, toLat, toLon); return R * sqrt(normedDist + dEleNorm); } @Override public double calcDenormalizedDist(double normedDist) { return R * sqrt(normedDist); } @Override public double calcNormalizedDist(double dist) { double tmp = dist / R; return tmp * tmp; } @Override public double calcNormalizedDist(double fromLat, double fromLon, double toLat, double toLon) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "PLANE_PROJ"; } }
double dLat = toRadians(toLat - fromLat); double dLon = toRadians(toLon - fromLon); double left = cos(toRadians((fromLat + toLat) / 2)) * dLon; return dLat * dLat + left * left;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/Downloader.java
Downloader
downloadFile
class Downloader { private final String userAgent; private String referrer = "http://graphhopper.com"; private String acceptEncoding = "gzip, deflate"; private int timeout = 4000; public Downloader(String userAgent) { this.userAgent = userAgent; } public static void main(String[] args) throws IOException { new Downloader("GraphHopper Downloader").downloadAndUnzip("http://graphhopper.com/public/maps/0.1/europe_germany_berlin.ghz", "somefolder", val -> System.out.println("progress:" + val)); } public Downloader setTimeout(int timeout) { this.timeout = timeout; return this; } public Downloader setReferrer(String referrer) { this.referrer = referrer; return this; } /** * This method initiates a connect call of the provided connection and returns the response * stream. It only returns the error stream if it is available and readErrorStreamNoException is * true otherwise it throws an IOException if an error happens. Furthermore it wraps the stream * to decompress it if the connection content encoding is specified. */ public InputStream fetch(HttpURLConnection connection, boolean readErrorStreamNoException) throws IOException { // create connection but before reading get the correct inputstream based on the compression and if error connection.connect(); InputStream is; if (readErrorStreamNoException && connection.getResponseCode() >= 400 && connection.getErrorStream() != null) is = connection.getErrorStream(); else is = connection.getInputStream(); if (is == null) throw new IOException("Stream is null. Message:" + connection.getResponseMessage()); // wrap try { String encoding = connection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) is = new GZIPInputStream(is); else if (encoding != null && encoding.equalsIgnoreCase("deflate")) is = new InflaterInputStream(is, new Inflater(true)); } catch (IOException ex) { } return is; } public InputStream fetch(String url) throws IOException { return fetch(createConnection(url), false); } public HttpURLConnection createConnection(String urlStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Will yield in a POST request: conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(true); conn.setRequestProperty("Referrer", referrer); conn.setRequestProperty("User-Agent", userAgent); // suggest respond to be gzipped or deflated (which is just another compression) // http://stackoverflow.com/q/3932117 conn.setRequestProperty("Accept-Encoding", acceptEncoding); conn.setReadTimeout(timeout); conn.setConnectTimeout(timeout); return conn; } public void downloadFile(String url, String toFile) throws IOException {<FILL_FUNCTION_BODY>} public void downloadAndUnzip(String url, String toFolder, final LongConsumer progressListener) throws IOException { HttpURLConnection conn = createConnection(url); final int length = conn.getContentLength(); InputStream iStream = fetch(conn, false); new Unzipper().unzip(iStream, new File(toFolder), sumBytes -> progressListener.accept((int) (100 * sumBytes / length))); } public String downloadAsString(String url, boolean readErrorStreamNoException) throws IOException { return Helper.isToString(fetch(createConnection(url), readErrorStreamNoException)); } }
HttpURLConnection conn = createConnection(url); InputStream iStream = fetch(conn, false); int size = 8 * 1024; BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(toFile), size); InputStream in = new BufferedInputStream(iStream, size); try { byte[] buffer = new byte[size]; int numRead; while ((numRead = in.read(buffer)) != -1) { writer.write(buffer, 0, numRead); } } finally { Helper.close(iStream); Helper.close(writer); Helper.close(in); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/GitInfo.java
GitInfo
toString
class GitInfo { private final String commitHash; private final String commitTime; private final String commitMessage; private final String branch; private final boolean dirty; public GitInfo(String commitHash, String commitTime, String commitMessage, String branch, boolean dirty) { this.commitHash = commitHash; this.commitTime = commitTime; this.commitMessage = commitMessage; this.branch = branch; this.dirty = dirty; } public String getCommitHash() { return commitHash; } public String getCommitTime() { return commitTime; } public String getCommitMessage() { return commitMessage; } public String getBranch() { return branch; } public boolean isDirty() { return dirty; } public String toString() {<FILL_FUNCTION_BODY>} }
return String.join("|", Arrays.asList(commitHash, branch, "dirty=" + dirty, commitTime, commitMessage));
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/Instructions.java
Instructions
find
class Instructions { /** * This method is useful for navigation devices to find the next instruction for the specified * coordinate (e.g. the current position). * <p> * * @param instructions the instructions to query * @param maxDistance the maximum acceptable distance to the instruction (in meter) * @return the next Instruction or null if too far away. */ public static Instruction find(InstructionList instructions, double lat, double lon, double maxDistance) {<FILL_FUNCTION_BODY>} }
// handle special cases if (instructions.size() == 0) { return null; } PointList points = instructions.get(0).getPoints(); double prevLat = points.getLat(0); double prevLon = points.getLon(0); DistanceCalc distCalc = DistanceCalcEarth.DIST_EARTH; double foundMinDistance = distCalc.calcNormalizedDist(lat, lon, prevLat, prevLon); int foundInstruction = 0; // Search the closest edge to the query point if (instructions.size() > 1) { for (int instructionIndex = 0; instructionIndex < instructions.size(); instructionIndex++) { points = instructions.get(instructionIndex).getPoints(); for (int pointIndex = 0; pointIndex < points.size(); pointIndex++) { double currLat = points.getLat(pointIndex); double currLon = points.getLon(pointIndex); if (!(instructionIndex == 0 && pointIndex == 0)) { // calculate the distance from the point to the edge double distance; int index = instructionIndex; if (distCalc.validEdgeDistance(lat, lon, currLat, currLon, prevLat, prevLon)) { distance = distCalc.calcNormalizedEdgeDistance(lat, lon, currLat, currLon, prevLat, prevLon); if (pointIndex > 0) index++; } else { distance = distCalc.calcNormalizedDist(lat, lon, currLat, currLon); if (pointIndex > 0) index++; } if (distance < foundMinDistance) { foundMinDistance = distance; foundInstruction = index; } } prevLat = currLat; prevLon = currLon; } } } if (distCalc.calcDenormalizedDist(foundMinDistance) > maxDistance) return null; // special case finish condition if (foundInstruction == instructions.size()) foundInstruction--; return instructions.get(foundInstruction);
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/MiniPerfTest.java
MiniPerfTest
start
class MiniPerfTest { private static final double NS_PER_S = 1e9; private static final double NS_PER_MS = 1e6; private static final double NS_PER_US = 1e3; private int counts = 100; private long fullTime = 0; private long max; private long min = Long.MAX_VALUE; private int dummySum; /** * Important: Make sure to use the dummy sum in your program somewhere such that it's calculation cannot be skipped * by the JVM. Either use {@link #getDummySum()} or {@link #getReport()} after running this method. */ public MiniPerfTest start(Task m) {<FILL_FUNCTION_BODY>} public interface Task { /** * @return return some integer as result from your processing to make sure that the JVM cannot * optimize (away) the call or within the call something. */ int doCalc(boolean warmup, int run); } public MiniPerfTest setIterations(int counts) { this.counts = counts; return this; } /** * @return minimum time of every call, in ms */ public double getMin() { return min / NS_PER_MS; } /** * @return maximum time of every calls, in ms */ public double getMax() { return max / NS_PER_MS; } /** * @return time for all calls accumulated, in ms */ public double getSum() { return fullTime / NS_PER_MS; } /** * @return mean time per call, in ms */ public double getMean() { return getSum() / counts; } private String formatDuration(double durationNs) { double divisor; String unit; if (durationNs > 1e7d) { divisor = NS_PER_S; unit = "s"; } else if (durationNs > 1e4d) { divisor = NS_PER_MS; unit = "ms"; } else { divisor = NS_PER_US; unit = "µs"; } return nf(durationNs / divisor) + unit; } public String getReport() { double meanNs = ((double) fullTime) / counts; return "sum:" + formatDuration(fullTime) + ", time/call:" + formatDuration(meanNs) + ", dummy: " + dummySum; } public int getDummySum() { return dummySum; } private String nf(Number num) { return new DecimalFormat("#.###", DecimalFormatSymbols.getInstance(Locale.ROOT)).format(num); } }
int warmupCount = Math.max(1, counts / 3); for (int i = 0; i < warmupCount; i++) { dummySum += m.doCalc(true, i); } long startFull = System.nanoTime(); for (int i = 0; i < counts; i++) { long start = System.nanoTime(); dummySum += m.doCalc(false, i); long time = System.nanoTime() - start; if (time < min) min = time; if (time > max) max = time; } fullTime = System.nanoTime() - startFull; return this;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/RamerDouglasPeucker.java
RamerDouglasPeucker
subSimplify
class RamerDouglasPeucker { private double normedMaxDist; private double elevationMaxDistance; private double maxDistance; private DistanceCalc calc; private boolean approx; public RamerDouglasPeucker() { setApproximation(true); // 1m setMaxDistance(1); // elevation ignored by default setElevationMaxDistance(Double.MAX_VALUE); } public void setApproximation(boolean a) { approx = a; if (approx) calc = DistancePlaneProjection.DIST_PLANE; else calc = DistanceCalcEarth.DIST_EARTH; } /** * maximum distance of discrepancy (from the normal way) in meter */ public RamerDouglasPeucker setMaxDistance(double dist) { this.normedMaxDist = calc.calcNormalizedDist(dist); this.maxDistance = dist; return this; } /** * maximum elevation distance of discrepancy (from the normal way) in meters */ public RamerDouglasPeucker setElevationMaxDistance(double dist) { this.elevationMaxDistance = dist; return this; } /** * Simplifies the <code>points</code>, from index 0 to size-1. * <p> * It is a wrapper method for {@link RamerDouglasPeucker#simplify(PointList, int, int)}. * * @return The number removed points */ public int simplify(PointList points) { return simplify(points, 0, points.size() - 1); } public int simplify(PointList points, int fromIndex, int lastIndex) { return simplify(points, fromIndex, lastIndex, true); } /** * Simplifies a part of the <code>points</code>. The <code>fromIndex</code> and <code>lastIndex</code> * are guaranteed to be kept. * * @param points The PointList to simplify * @param fromIndex Start index to simplify, should be <= <code>lastIndex</code> * @param lastIndex Simplify up to this index * @param compress Whether the <code>points</code> shall be compressed or not, if set to false no points * are actually removed, but instead their lat/lon/ele is only set to NaN * @return The number of removed points */ public int simplify(PointList points, int fromIndex, int lastIndex, boolean compress) { int removed = 0; int size = lastIndex - fromIndex; if (approx) { int delta = 500; int segments = size / delta + 1; int start = fromIndex; for (int i = 0; i < segments; i++) { // start of next is end of last segment, except for the last removed += subSimplify(points, start, Math.min(lastIndex, start + delta)); start += delta; } } else { removed = subSimplify(points, fromIndex, lastIndex); } if (removed > 0 && compress) removeNaN(points); return removed; } // keep the points of fromIndex and lastIndex int subSimplify(PointList points, int fromIndex, int lastIndex) {<FILL_FUNCTION_BODY>} /** * Fills all entries of the point list that are NaN with the subsequent values (and therefore shortens the list) */ static void removeNaN(PointList pointList) { int curr = 0; for (int i = 0; i < pointList.size(); i++) { if (!Double.isNaN(pointList.getLat(i))) { pointList.set(curr, pointList.getLat(i), pointList.getLon(i), pointList.getEle(i)); curr++; } } pointList.trimToSize(curr); } }
if (lastIndex - fromIndex < 2) { return 0; } int indexWithMaxDist = -1; double maxDist = -1; double elevationFactor = maxDistance / elevationMaxDistance; double firstLat = points.getLat(fromIndex); double firstLon = points.getLon(fromIndex); double firstEle = points.getEle(fromIndex); double lastLat = points.getLat(lastIndex); double lastLon = points.getLon(lastIndex); double lastEle = points.getEle(lastIndex); for (int i = fromIndex + 1; i < lastIndex; i++) { double lat = points.getLat(i); if (Double.isNaN(lat)) { continue; } double lon = points.getLon(i); double ele = points.getEle(i); double dist = (points.is3D() && elevationMaxDistance < Double.MAX_VALUE && !Double.isNaN(firstEle) && !Double.isNaN(lastEle) && !Double.isNaN(ele)) ? calc.calcNormalizedEdgeDistance3D( lat, lon, ele * elevationFactor, firstLat, firstLon, firstEle * elevationFactor, lastLat, lastLon, lastEle * elevationFactor) : calc.calcNormalizedEdgeDistance(lat, lon, firstLat, firstLon, lastLat, lastLon); if (maxDist < dist) { indexWithMaxDist = i; maxDist = dist; } } if (indexWithMaxDist < 0) { throw new IllegalStateException("maximum not found in [" + fromIndex + "," + lastIndex + "]"); } int counter = 0; if (maxDist < normedMaxDist) { for (int i = fromIndex + 1; i < lastIndex; i++) { points.set(i, Double.NaN, Double.NaN, Double.NaN); counter++; } } else { counter = subSimplify(points, fromIndex, indexWithMaxDist); counter += subSimplify(points, indexWithMaxDist, lastIndex); } return counter;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/SimpleIntDeque.java
SimpleIntDeque
toString
class SimpleIntDeque { private int[] arr; private float growFactor; private int frontIndex; private int endIndexPlusOne; public SimpleIntDeque() { this(100, 2); } public SimpleIntDeque(int initSize) { this(initSize, 2); } public SimpleIntDeque(int initSize, float growFactor) { if ((int) (initSize * growFactor) <= initSize) { throw new RuntimeException("initial size or increasing grow-factor too low!"); } this.growFactor = growFactor; this.arr = new int[initSize]; } int getCapacity() { return arr.length; } public void setGrowFactor(float factor) { this.growFactor = factor; } public boolean isEmpty() { return frontIndex >= endIndexPlusOne; } public int pop() { int tmp = arr[frontIndex]; frontIndex++; // removing the empty space of the front if too much is unused int smallerSize = (int) (arr.length / growFactor); if (frontIndex > smallerSize) { endIndexPlusOne = getSize(); // ensure that there are at least 10 entries int[] newArr = new int[endIndexPlusOne + 10]; System.arraycopy(arr, frontIndex, newArr, 0, endIndexPlusOne); arr = newArr; frontIndex = 0; } return tmp; } public int getSize() { return endIndexPlusOne - frontIndex; } public void push(int v) { if (endIndexPlusOne >= arr.length) { arr = Arrays.copyOf(arr, (int) (arr.length * growFactor)); } arr[endIndexPlusOne] = v; endIndexPlusOne++; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); for (int i = frontIndex; i < endIndexPlusOne; i++) { if (i > frontIndex) { sb.append(", "); } sb.append(arr[i]); } return sb.toString();
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/StopWatch.java
StopWatch
getTimeString
class StopWatch { private long lastTime; private long elapsedNanos; private String name = ""; public StopWatch(String name) { this.name = name; } public StopWatch() { } public static StopWatch started() { return started(""); } public static StopWatch started(String name) { return new StopWatch(name).start(); } public StopWatch setName(String name) { this.name = name; return this; } public StopWatch start() { lastTime = System.nanoTime(); return this; } public StopWatch stop() { if (lastTime < 0) return this; elapsedNanos += System.nanoTime() - lastTime; lastTime = -1; return this; } public float getSeconds() { return elapsedNanos / 1e9f; } /** * 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) / 1e9f; } public long getMillis() { return elapsedNanos / 1_000_000; } /** * returns the elapsed time in ms but includes the fraction as well to get a precise value */ public double getMillisDouble() { return elapsedNanos / 1_000_000.0; } public long getNanos() { return elapsedNanos; } @Override public String toString() { String str = ""; if (!Helper.isEmpty(name)) { str += name + " "; } return str + "time:" + getSeconds() + "s"; } public String getTimeString() {<FILL_FUNCTION_BODY>} private boolean notStarted() { return lastTime == 0 && elapsedNanos == 0; } }
if (elapsedNanos < 1e3) { return elapsedNanos + "ns"; } else if (elapsedNanos < 1e6) { return String.format("%.2fµs", elapsedNanos / 1.e3); } else if (elapsedNanos < 1e9) { return String.format("%.2fms", elapsedNanos / 1.e6); } else { double seconds = elapsedNanos / 1.e9; if (seconds < 60) { return String.format("%.2fs", elapsedNanos / 1e9); } else if (seconds < 60 * 60) { return String.format("%dmin %ds", ((int) seconds / 60), (((int) seconds) % 60)); } else { return String.format("%dh %dmin", ((int) seconds / (60 * 60)), ((int) seconds) % (60 * 60) / 60); } }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/Unzipper.java
Unzipper
unzip
class Unzipper { public void unzip(String from, boolean remove) throws IOException { String to = Helper.pruneFileEnd(from); unzip(from, to, remove); } public boolean unzip(String fromStr, String toStr, boolean remove) throws IOException {<FILL_FUNCTION_BODY>} /** * @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 newFile = getVerifiedFile(toFolder, ze); FileOutputStream fos = new FileOutputStream(newFile); 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(); } } // 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; } }
File from = new File(fromStr); if (!from.exists() || fromStr.equals(toStr)) return false; unzip(new FileInputStream(from), new File(toStr), null); if (remove) Helper.removeDir(from); return true;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/AbstractPathDetailsBuilder.java
AbstractPathDetailsBuilder
startInterval
class AbstractPathDetailsBuilder implements PathDetailsBuilder { private final String name; private boolean isOpen = false; private PathDetail currentDetail; private final List<PathDetail> pathDetails = new ArrayList<>(); public AbstractPathDetailsBuilder(String name) { this.name = name; } /** * The value of the Path at this moment, that should be stored in the PathDetail when calling startInterval */ protected abstract Object getCurrentValue(); /** * It is only possible to open one interval at a time. Calling <code>startInterval</code> when * the interval is already open results in an Exception. * * @param firstIndex the index the PathDetail starts */ public void startInterval(int firstIndex) {<FILL_FUNCTION_BODY>} /** * Ending intervals multiple times is safe, we only write the interval if it was open and not empty. * Writes the interval to the pathDetails * * @param lastIndex the index the PathDetail ends */ public void endInterval(int lastIndex) { if (isOpen) { currentDetail.setLast(lastIndex); pathDetails.add(currentDetail); } isOpen = false; } public Map.Entry<String, List<PathDetail>> build() { return new MapEntry(getName(), pathDetails); } @Override public String getName() { return name; } @Override public String toString() { return getName(); } }
Object value = getCurrentValue(); if (isOpen) throw new IllegalStateException("PathDetailsBuilder is already in an open state with value: " + currentDetail.getValue() + " trying to open a new one with value: " + value); currentDetail = new PathDetail(value); currentDetail.setFirst(firstIndex); isOpen = true;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/AverageSpeedDetails.java
AverageSpeedDetails
isEdgeDifferentToLastEdge
class AverageSpeedDetails extends AbstractPathDetailsBuilder { private final Weighting weighting; private final double precision; private Double decimalValue; // will include the turn time penalty private int prevEdgeId = EdgeIterator.NO_EDGE; public AverageSpeedDetails(Weighting weighting) { this(weighting, 0.1); } /** * @param precision e.g. 0.1 to avoid creating too many path details, i.e. round the speed to the specified precision * before detecting a change. */ public AverageSpeedDetails(Weighting weighting, double precision) { super(AVERAGE_SPEED); this.weighting = weighting; this.precision = precision; } @Override protected Object getCurrentValue() { return decimalValue; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} }
// For very short edges we might not be able to calculate a proper value for speed. dividing by calcMillis can // even lead to an infinity speed. So, just ignore these edges, see #1848 and #2620 and #2636. final double distance = edge.getDistance(); long time = GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdgeId); if (distance < 0.01 || time < 1) { prevEdgeId = edge.getEdge(); if (decimalValue != null) return false; // in case this is the first edge we return decimalValue=null return true; } double speed = distance / time * 3600; prevEdgeId = edge.getEdge(); if (decimalValue == null || Math.abs(speed - decimalValue) >= precision) { this.decimalValue = Math.round(speed / precision) * precision; return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/BooleanDetails.java
BooleanDetails
isEdgeDifferentToLastEdge
class BooleanDetails extends AbstractPathDetailsBuilder { private final BooleanEncodedValue boolEnc; private Boolean boolValue; public BooleanDetails(String name, BooleanEncodedValue boolEnc) { super(name); this.boolEnc = boolEnc; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} @Override public Object getCurrentValue() { return this.boolValue; } }
boolean tmpVal = edge.get(boolEnc); if (boolValue == null || tmpVal != boolValue) { this.boolValue = tmpVal; return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/ConstantDetailsBuilder.java
ConstantDetailsBuilder
isEdgeDifferentToLastEdge
class ConstantDetailsBuilder extends AbstractPathDetailsBuilder { private final Object value; private boolean firstEdge = true; public ConstantDetailsBuilder(String name, Object value) { super(name); this.value = value; } @Override protected Object getCurrentValue() { return value; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} @Override public Map.Entry<String, List<PathDetail>> build() { if (firstEdge) // #2915 if there was no edge at all we need to add a single entry manually here return new MapEntry<>(getName(), new ArrayList<>(List.of(new PathDetail(value)))); return super.build(); } }
if (firstEdge) { firstEdge = false; return true; } else return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/DecimalDetails.java
DecimalDetails
isEdgeDifferentToLastEdge
class DecimalDetails extends AbstractPathDetailsBuilder { private final DecimalEncodedValue ev; private Double decimalValue; private final String infinityJsonValue; private final double precision; public DecimalDetails(String name, DecimalEncodedValue ev) { this(name, ev, null, 0.001); } /** * @param infinityJsonValue DecimalEncodedValue can return infinity as default value, but JSON cannot include this * https://stackoverflow.com/a/9218955/194609 so we need a special string to handle this or null. * @param precision e.g. 0.1 to avoid creating too many path details, i.e. round the speed to the specified precision * * before detecting a change. */ public DecimalDetails(String name, DecimalEncodedValue ev, String infinityJsonValue, double precision) { super(name); this.ev = ev; this.infinityJsonValue = infinityJsonValue; this.precision = precision; } @Override protected Object getCurrentValue() { if (Double.isInfinite(decimalValue)) return infinityJsonValue; return decimalValue; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} }
double tmpVal = edge.get(ev); if (decimalValue == null || Math.abs(tmpVal - decimalValue) >= precision) { this.decimalValue = Double.isInfinite(tmpVal) ? tmpVal : Math.round(tmpVal / precision) * precision; return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/EdgeIdDetails.java
EdgeIdDetails
edgeId
class EdgeIdDetails extends AbstractPathDetailsBuilder { private int edgeId = EdgeIterator.NO_EDGE; public EdgeIdDetails() { super(EDGE_ID); } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) { edgeId = edgeId(edge); return true; } private int edgeId(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} @Override public Object getCurrentValue() { return this.edgeId; } }
if (edge instanceof VirtualEdgeIteratorState) { return GHUtility.getEdgeFromEdgeKey(((VirtualEdgeIteratorState) edge).getOriginalEdgeKey()); } else { return edge.getEdge(); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/EdgeKeyDetails.java
EdgeKeyDetails
isEdgeDifferentToLastEdge
class EdgeKeyDetails extends AbstractPathDetailsBuilder { private int edgeKey = -1; public EdgeKeyDetails() { super(EDGE_KEY); } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} @Override public Object getCurrentValue() { return this.edgeKey; } }
int newKey = edge instanceof VirtualEdgeIteratorState ? ((VirtualEdgeIteratorState) edge).getOriginalEdgeKey() : edge.getEdgeKey(); if (newKey != edgeKey) { // do not duplicate path detail if going over via point (two virtual edges) edgeKey = newKey; return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/EnumDetails.java
EnumDetails
isEdgeDifferentToLastEdge
class EnumDetails<E extends Enum> extends AbstractPathDetailsBuilder { private final EnumEncodedValue<E> ev; private E objVal; public EnumDetails(String name, EnumEncodedValue<E> ev) { super(name); this.ev = ev; } @Override protected Object getCurrentValue() { return objVal.toString(); } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} }
E val = edge.get(ev); // we can use the reference equality here if (val != objVal) { this.objVal = val; return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/IntDetails.java
IntDetails
isEdgeDifferentToLastEdge
class IntDetails extends AbstractPathDetailsBuilder { private final IntEncodedValue ev; private Integer intVal; public IntDetails(String name, IntEncodedValue ev) { super(name); this.ev = ev; } @Override protected Object getCurrentValue() { return intVal; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} }
int val = edge.get(ev); if (intVal == null || val != intVal) { this.intVal = val; return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/IntersectionDetails.java
IntersectionDetails
edgeId
class IntersectionDetails extends AbstractPathDetailsBuilder { private int fromEdge = -1; private Map<String, Object> intersectionMap = null; private final EdgeExplorer crossingExplorer; private final NodeAccess nodeAccess; private final Weighting weighting; public IntersectionDetails(Graph graph, Weighting weighting) { super(INTERSECTION); crossingExplorer = graph.createEdgeExplorer(); nodeAccess = graph.getNodeAccess(); this.weighting = weighting; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) { int toEdge = edgeId(edge); if (toEdge != fromEdge) { // Important to create a new map and not to clean the old map! intersectionMap = new HashMap<>(); List<IntersectionValues> intersectingEdges = new ArrayList<>(); int baseNode = edge.getBaseNode(); EdgeIteratorState tmpEdge; double startLat = nodeAccess.getLat(baseNode); double startLon = nodeAccess.getLon(baseNode); EdgeIterator edgeIter = crossingExplorer.setBaseNode(baseNode); while (edgeIter.next()) { // We need to call detach to get the edgeId, as we need to check for VirtualEdgeIteratorState in #edgeId(), see discussion in #2590 tmpEdge = edgeIter.detach(false); IntersectionValues intersectionValues = new IntersectionValues(); intersectionValues.bearing = calculateBearing(startLat, startLon, tmpEdge); intersectionValues.in = edgeId(tmpEdge) == fromEdge; intersectionValues.out = edgeId(tmpEdge) == edgeId(edge); // The in edge is always false, this means that u-turns are not considered as possible turning option intersectionValues.entry = !intersectionValues.in && Double.isFinite(weighting.calcEdgeWeight(tmpEdge, false)); intersectingEdges.add(intersectionValues); } intersectingEdges = intersectingEdges.stream(). sorted((x, y) -> Integer.compare(x.bearing, y.bearing)).collect(Collectors.toList()); intersectionMap = IntersectionValues.createIntersection(intersectingEdges); fromEdge = toEdge; return true; } return false; } private int calculateBearing(double startLat, double startLon, EdgeIteratorState tmpEdge) { PointList wayGeo = tmpEdge.fetchWayGeometry(FetchMode.PILLAR_AND_ADJ); final double latitude = wayGeo.getLat(0); final double longitude = wayGeo.getLon(0); return (int) Math.round(AngleCalc.ANGLE_CALC.calcAzimuth(startLat, startLon, latitude, longitude)); } private int edgeId(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} @Override public Object getCurrentValue() { return this.intersectionMap; } }
if (edge instanceof VirtualEdgeIteratorState) { return GHUtility.getEdgeFromEdgeKey(((VirtualEdgeIteratorState) edge).getOriginalEdgeKey()); } else { return edge.getEdge(); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/IntersectionValues.java
IntersectionValues
createList
class IntersectionValues { public int bearing; public boolean entry; public boolean in; public boolean out; /** * create a List of IntersectionValues from a PathDetail */ public static List<IntersectionValues> createList(Map<String, Object> intersectionMap) {<FILL_FUNCTION_BODY>} /** * create a PathDetail from a List of IntersectionValues */ public static Map<String, Object> createIntersection(List<IntersectionValues> list) { Map<String, Object> intersection = new HashMap<>(); intersection.put("bearings", list.stream().map(x -> x.bearing).collect(Collectors.toList())); intersection.put("entries", list.stream().map(x -> x.entry).collect(Collectors.toList())); for (int m = 0; m < list.size(); m++) { IntersectionValues intersectionValues = list.get(m); if (intersectionValues.in) { intersection.put("in", m); } if (intersectionValues.out) { intersection.put("out", m); } } return intersection; } }
List<IntersectionValues> list = new ArrayList<>(); List<Integer> bearings = (List<Integer>) intersectionMap.get("bearings"); Integer in = (Integer) intersectionMap.get("in"); Integer out = (Integer) intersectionMap.get("out"); List<Boolean> entry = (List<Boolean>) intersectionMap.get("entries"); if (bearings.size() != entry.size()) { throw new IllegalStateException("Bearings and entry array sizes different"); } int numEntries = bearings.size(); for (int i = 0; i < numEntries; i++) { IntersectionValues iv = new IntersectionValues(); iv.bearing = bearings.get(i); iv.entry = entry.get(i); iv.in = (in == i); iv.out = (out == i); list.add(iv); } return list;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/KVStringDetails.java
KVStringDetails
isEdgeDifferentToLastEdge
class KVStringDetails extends AbstractPathDetailsBuilder { private String curString; private boolean initial = true; public KVStringDetails(String name) { super(name); } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} @Override public Object getCurrentValue() { return this.curString; } }
String value = (String) edge.getValue(getName()); if (initial) { curString = value; initial = false; return true; } else if (curString == null) { curString = value; // do not create separate details if value stays null return value != null; } else if (!curString.equals(value)) { curString = value; return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/PathDetailsBuilderFactory.java
PathDetailsBuilderFactory
createPathDetailsBuilders
class PathDetailsBuilderFactory { public List<PathDetailsBuilder> createPathDetailsBuilders(List<String> requestedPathDetails, Path path, EncodedValueLookup evl, Weighting weighting, Graph graph) {<FILL_FUNCTION_BODY>} }
List<PathDetailsBuilder> builders = new ArrayList<>(); if (requestedPathDetails.contains(LEG_TIME)) builders.add(new ConstantDetailsBuilder(LEG_TIME, path.getTime())); if (requestedPathDetails.contains(LEG_DISTANCE)) builders.add(new ConstantDetailsBuilder(LEG_DISTANCE, path.getDistance())); if (requestedPathDetails.contains(LEG_WEIGHT)) builders.add(new ConstantDetailsBuilder(LEG_WEIGHT, path.getWeight())); for (String key : requestedPathDetails) { if (key.endsWith("_conditional")) builders.add(new KVStringDetails(key)); } if (requestedPathDetails.contains(MOTORWAY_JUNCTION)) builders.add(new KVStringDetails(MOTORWAY_JUNCTION)); if (requestedPathDetails.contains(STREET_NAME)) builders.add(new KVStringDetails(STREET_NAME)); if (requestedPathDetails.contains(STREET_REF)) builders.add(new KVStringDetails(STREET_REF)); if (requestedPathDetails.contains(STREET_DESTINATION)) builders.add(new KVStringDetails(STREET_DESTINATION)); if (requestedPathDetails.contains(AVERAGE_SPEED)) builders.add(new AverageSpeedDetails(weighting)); if (requestedPathDetails.contains(EDGE_ID)) builders.add(new EdgeIdDetails()); if (requestedPathDetails.contains(EDGE_KEY)) builders.add(new EdgeKeyDetails()); if (requestedPathDetails.contains(TIME)) builders.add(new TimeDetails(weighting)); if (requestedPathDetails.contains(WEIGHT)) builders.add(new WeightDetails(weighting)); if (requestedPathDetails.contains(DISTANCE)) builders.add(new DistanceDetails()); if (requestedPathDetails.contains(INTERSECTION)) builders.add(new IntersectionDetails(graph, weighting)); for (String pathDetail : requestedPathDetails) { if (!evl.hasEncodedValue(pathDetail)) continue; // path details like "time" won't be found EncodedValue ev = evl.getEncodedValue(pathDetail, EncodedValue.class); if (ev instanceof DecimalEncodedValue) builders.add(new DecimalDetails(pathDetail, (DecimalEncodedValue) ev)); else if (ev instanceof BooleanEncodedValue) builders.add(new BooleanDetails(pathDetail, (BooleanEncodedValue) ev)); else if (ev instanceof EnumEncodedValue) builders.add(new EnumDetails<>(pathDetail, (EnumEncodedValue) ev)); else if (ev instanceof StringEncodedValue) builders.add(new StringDetails(pathDetail, (StringEncodedValue) ev)); else if (ev instanceof IntEncodedValue) builders.add(new IntDetails(pathDetail, (IntEncodedValue) ev)); else throw new IllegalArgumentException("unknown EncodedValue class " + ev.getClass().getName()); } if (requestedPathDetails.size() > builders.size()) { ArrayList<String> clonedArr = new ArrayList<>(requestedPathDetails); // avoid changing request parameter for (PathDetailsBuilder pdb : builders) clonedArr.remove(pdb.getName()); throw new IllegalArgumentException("Cannot find the path details: " + clonedArr); } else if (requestedPathDetails.size() < builders.size()) throw new IllegalStateException("It should not happen that there are more path details added " + builders + " than requested " + requestedPathDetails); return builders;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/PathDetailsFromEdges.java
PathDetailsFromEdges
calcDetails
class PathDetailsFromEdges implements Path.EdgeVisitor { private final List<PathDetailsBuilder> calculators; private int lastIndex = 0; public PathDetailsFromEdges(List<PathDetailsBuilder> calculators, int previousIndex) { this.calculators = calculators; this.lastIndex = previousIndex; } /** * 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) {<FILL_FUNCTION_BODY>} @Override public void next(EdgeIteratorState edge, int index, int prevEdgeId) { for (PathDetailsBuilder calc : calculators) { if (calc.isEdgeDifferentToLastEdge(edge)) { calc.endInterval(lastIndex); calc.startInterval(lastIndex); } } lastIndex += edge.fetchWayGeometry(FetchMode.PILLAR_AND_ADJ).size(); } @Override public void finish() { for (PathDetailsBuilder calc : calculators) { calc.endInterval(lastIndex); } } }
if (!path.isFound() || requestedPathDetails.isEmpty()) return Collections.emptyMap(); HashSet<String> uniquePD = new HashSet<>(requestedPathDetails.size()); Collection<String> res = requestedPathDetails.stream().filter(pd -> !uniquePD.add(pd)).collect(Collectors.toList()); if (!res.isEmpty()) throw new IllegalArgumentException("Do not use duplicate path details: " + res); 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> existing = pathDetails.put(entry.getKey(), entry.getValue()); if (existing != null) throw new IllegalStateException("Some PathDetailsBuilders use duplicate key: " + entry.getKey()); } return pathDetails;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/StringDetails.java
StringDetails
isEdgeDifferentToLastEdge
class StringDetails extends AbstractPathDetailsBuilder { private final StringEncodedValue ev; private String currentVal; public StringDetails(String name, StringEncodedValue ev) { super(name); this.ev = ev; } @Override protected Object getCurrentValue() { return currentVal; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} }
String val = edge.get(ev); // we can use the reference equality here if (!val.equals(currentVal)) { this.currentVal = val; return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/TimeDetails.java
TimeDetails
isEdgeDifferentToLastEdge
class TimeDetails extends AbstractPathDetailsBuilder { private final Weighting weighting; private int prevEdgeId = EdgeIterator.NO_EDGE; // will include the turn time penalty private long time = 0; public TimeDetails(Weighting weighting) { super(TIME); this.weighting = weighting; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} @Override public Object getCurrentValue() { return this.time; } }
time = GHUtility.calcMillisWithTurnMillis(weighting, edge, false, prevEdgeId); prevEdgeId = edge.getEdge(); return true;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/details/WeightDetails.java
WeightDetails
isEdgeDifferentToLastEdge
class WeightDetails extends AbstractPathDetailsBuilder { private final Weighting weighting; private int edgeId = EdgeIterator.NO_EDGE; private Double weight; public WeightDetails(Weighting weighting) { super(WEIGHT); this.weighting = weighting; } @Override public boolean isEdgeDifferentToLastEdge(EdgeIteratorState edge) {<FILL_FUNCTION_BODY>} @Override public Object getCurrentValue() { return this.weight; } }
if (edge.getEdge() != edgeId) { edgeId = edge.getEdge(); weight = GHUtility.calcWeightWithTurnWeight(weighting, edge, false, edgeId); return true; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/shapes/Circle.java
Circle
intersects
class Circle implements Shape { public final double radiusInMeter; private final double lat; private final double lon; private final double normedDist; private final BBox bbox; private DistanceCalc calc; public Circle(double lat, double lon, double radiusInMeter) { this(lat, lon, radiusInMeter, DistanceCalcEarth.DIST_EARTH); } public Circle(double lat, double lon, double radiusInMeter, DistanceCalc calc) { this.calc = calc; this.lat = lat; this.lon = lon; this.radiusInMeter = radiusInMeter; this.normedDist = calc.calcNormalizedDist(radiusInMeter); bbox = calc.createBBox(lat, lon, radiusInMeter); } public double getLat() { return lat; } public double getLon() { return lon; } @Override public boolean contains(double lat1, double lon1) { return normDist(lat1, lon1) <= normedDist; } @Override public BBox getBounds() { return bbox; } private double normDist(double lat1, double lon1) { return calc.calcNormalizedDist(lat, lon, lat1, lon1); } @Override public boolean intersects(PointList pointList) {<FILL_FUNCTION_BODY>} public boolean intersects(BBox b) { // test top intersects if (lat > b.maxLat) { if (lon < b.minLon) { return normDist(b.maxLat, b.minLon) <= normedDist; } if (lon > b.maxLon) { return normDist(b.maxLat, b.maxLon) <= normedDist; } return b.maxLat - bbox.minLat > 0; } // test bottom intersects if (lat < b.minLat) { if (lon < b.minLon) { return normDist(b.minLat, b.minLon) <= normedDist; } if (lon > b.maxLon) { return normDist(b.minLat, b.maxLon) <= normedDist; } return bbox.maxLat - b.minLat > 0; } // test middle intersects if (lon < b.minLon) { return bbox.maxLon - b.minLon > 0; } if (lon > b.maxLon) { return b.maxLon - bbox.minLon > 0; } return true; } public boolean contains(BBox b) { if (bbox.contains(b)) { return contains(b.maxLat, b.minLon) && contains(b.minLat, b.minLon) && contains(b.maxLat, b.maxLon) && contains(b.minLat, b.maxLon); } return false; } public boolean contains(Circle c) { double res = radiusInMeter - c.radiusInMeter; if (res < 0) { return false; } return calc.calcDist(lat, lon, c.lat, c.lon) <= res; } @Override public boolean equals(Object obj) { if (obj == null) return false; Circle b = (Circle) obj; // equals within a very small range return NumHelper.equalsEps(lat, b.lat) && NumHelper.equalsEps(lon, b.lon) && NumHelper.equalsEps(radiusInMeter, b.radiusInMeter); } @Override public int hashCode() { int hash = 3; hash = 17 * hash + (int) (Double.doubleToLongBits(this.lat) ^ (Double.doubleToLongBits(this.lat) >>> 32)); hash = 17 * hash + (int) (Double.doubleToLongBits(this.lon) ^ (Double.doubleToLongBits(this.lon) >>> 32)); hash = 17 * hash + (int) (Double.doubleToLongBits(this.radiusInMeter) ^ (Double.doubleToLongBits(this.radiusInMeter) >>> 32)); return hash; } @Override public String toString() { return lat + "," + lon + ", radius:" + radiusInMeter; } }
// similar code to LocationIndexTree.checkAdjacent int len = pointList.size(); if (len == 0) throw new IllegalArgumentException("PointList must not be empty"); double tmpLat = pointList.getLat(0); double tmpLon = pointList.getLon(0); if (len == 1) return calc.calcNormalizedDist(lat, lon, tmpLat, tmpLon) <= normedDist; for (int pointIndex = 1; pointIndex < len; pointIndex++) { double wayLat = pointList.getLat(pointIndex); double wayLon = pointList.getLon(pointIndex); if (calc.validEdgeDistance(lat, lon, tmpLat, tmpLon, wayLat, wayLon)) { if (calc.calcNormalizedEdgeDistance(lat, lon, tmpLat, tmpLon, wayLat, wayLon) <= normedDist) return true; } else { if (calc.calcNormalizedDist(lat, lon, tmpLat, tmpLon) <= normedDist || pointIndex + 1 == len && calc.calcNormalizedDist(lat, lon, wayLat, wayLon) <= normedDist) return true; } tmpLat = wayLat; tmpLon = wayLon; } return false;
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/util/shapes/Polygon.java
Polygon
toString
class Polygon implements Shape { private static final GeometryFactory factory = new GeometryFactory(); public final PreparedGeometry prepPolygon; public final boolean rectangle; public final Envelope envelope; public final BBox bbox; public Polygon(PreparedPolygon prepPolygon) { this.prepPolygon = prepPolygon; this.rectangle = prepPolygon.getGeometry().isRectangle(); this.envelope = prepPolygon.getGeometry().getEnvelopeInternal(); this.bbox = BBox.fromEnvelope(envelope); } public Polygon(double[] lats, double[] lons) { if (lats.length != lons.length) throw new IllegalArgumentException("Points must be of equal length but was " + lats.length + " vs. " + lons.length); if (lats.length == 0) throw new IllegalArgumentException("Points must not be empty"); Coordinate[] coordinates = new Coordinate[lats.length + 1]; for (int i = 0; i < lats.length; i++) { coordinates[i] = new Coordinate(lons[i], lats[i]); } coordinates[lats.length] = coordinates[0]; this.prepPolygon = new PreparedPolygon(factory.createPolygon(new PackedCoordinateSequence.Double(coordinates, 2))); this.rectangle = prepPolygon.getGeometry().isRectangle(); this.envelope = prepPolygon.getGeometry().getEnvelopeInternal(); this.bbox = BBox.fromEnvelope(envelope); } public static Polygon create(org.locationtech.jts.geom.Polygon polygon) { return new Polygon(new PreparedPolygon(polygon)); } public boolean intersects(PointList pointList) { return prepPolygon.intersects(pointList.getCachedLineString(false)); } /** * Does the point in polygon check. * * @param lat Latitude of the point to be checked * @param lon Longitude of the point to be checked * @return true if point is inside polygon */ public boolean contains(double lat, double lon) { return prepPolygon.contains(factory.createPoint(new Coordinate(lon, lat))); } @Override public BBox getBounds() { return bbox; } public double getMinLat() { return envelope.getMinY(); } public double getMinLon() { return envelope.getMinX(); } public double getMaxLat() { return envelope.getMaxY(); } public double getMaxLon() { return envelope.getMaxX(); } public boolean isRectangle() { return rectangle; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "polygon (" + prepPolygon.getGeometry().getNumPoints() + " points," + prepPolygon.getGeometry().getNumGeometries() + " geometries)";
graphhopper_graphhopper
graphhopper/example/src/main/java/com/graphhopper/example/HeadingExample.java
HeadingExample
without_heading
class HeadingExample { public static void main(String[] args) { String relDir = args.length == 1 ? args[0] : ""; GraphHopper hopper = createGraphHopperInstance(relDir + "core/files/andorra.osm.pbf"); without_heading(hopper); with_heading_start(hopper); with_heading_start_stop(hopper); with_heading_stop(hopper); with_heading_start_stop_lower_penalty(hopper); } /** * See {@link RoutingExample#createGraphHopperInstance} for more comments on creating the GraphHopper instance. */ static GraphHopper createGraphHopperInstance(String ghLoc) { GraphHopper hopper = new GraphHopper(); hopper.setOSMFile(ghLoc); hopper.setGraphHopperLocation("target/heading-graph-cache"); hopper.setEncodedValuesString("car_access, road_access, car_average_speed"); hopper.setProfiles(new Profile("car"). setCustomModel(new CustomModel(). addToSpeed(If("true", LIMIT, "car_average_speed")). addToPriority(If("!car_access", MULTIPLY, "0")). addToPriority(If("road_access == DESTINATION", MULTIPLY, "0.1")))); hopper.getCHPreparationHandler().setCHProfiles(new CHProfile("car")); hopper.importOrLoad(); return hopper; } static void without_heading(GraphHopper hopper) {<FILL_FUNCTION_BODY>} static void with_heading_start(GraphHopper hopper) { GHRequest request = new GHRequest(new GHPoint(42.566757, 1.597751), new GHPoint(42.567396, 1.597807)). setHeadings(Arrays.asList(270d)). // important: if CH is enabled on the server-side we need to disable it for each request that uses heading, // because heading is not supported by CH putHint(Parameters.CH.DISABLE, true). setProfile("car"); GHResponse response = hopper.route(request); if (response.hasErrors()) throw new RuntimeException(response.getErrors().toString()); assert Math.round(response.getBest().getDistance()) == 264; } static void with_heading_start_stop(GraphHopper hopper) { GHRequest request = new GHRequest(new GHPoint(42.566757, 1.597751), new GHPoint(42.567396, 1.597807)). setHeadings(Arrays.asList(270d, 180d)). putHint(Parameters.CH.DISABLE, true). setProfile("car"); GHResponse response = hopper.route(request); if (response.hasErrors()) throw new RuntimeException(response.getErrors().toString()); assert Math.round(response.getBest().getDistance()) == 434; } static void with_heading_stop(GraphHopper hopper) { GHRequest request = new GHRequest(new GHPoint(42.566757, 1.597751), new GHPoint(42.567396, 1.597807)). setHeadings(Arrays.asList(Double.NaN, 180d)). putHint(Parameters.CH.DISABLE, true). setProfile("car"); GHResponse response = hopper.route(request); if (response.hasErrors()) throw new RuntimeException(response.getErrors().toString()); assert Math.round(response.getBest().getDistance()) == 201; } static void with_heading_start_stop_lower_penalty(GraphHopper hopper) { GHRequest request = new GHRequest(new GHPoint(42.566757, 1.597751), new GHPoint(42.567396, 1.597807)). setHeadings(Arrays.asList(270d, 180d)). putHint(Parameters.Routing.HEADING_PENALTY, 10). putHint(Parameters.CH.DISABLE, true). setProfile("car"); GHResponse response = hopper.route(request); if (response.hasErrors()) throw new RuntimeException(response.getErrors().toString()); // same distance as without_heading assert Math.round(response.getBest().getDistance()) == 84; } }
GHRequest request = new GHRequest(new GHPoint(42.566757, 1.597751), new GHPoint(42.567396, 1.597807)). setProfile("car"); GHResponse response = hopper.route(request); if (response.hasErrors()) throw new RuntimeException(response.getErrors().toString()); assert Math.round(response.getBest().getDistance()) == 84;
graphhopper_graphhopper
graphhopper/example/src/main/java/com/graphhopper/example/IsochroneExample.java
IsochroneExample
main
class IsochroneExample { public static void main(String[] args) {<FILL_FUNCTION_BODY>} /** * See {@link RoutingExample#createGraphHopperInstance} for more comments on creating the GraphHopper instance. */ static GraphHopper createGraphHopperInstance(String ghLoc) { GraphHopper hopper = new GraphHopper(); hopper.setOSMFile(ghLoc); hopper.setGraphHopperLocation("target/isochrone-graph-cache"); hopper.setProfiles(new Profile("car").setCustomModel(GHUtility.loadCustomModelFromJar("car.json"))); hopper.importOrLoad(); return hopper; } }
String relDir = args.length == 1 ? args[0] : ""; GraphHopper hopper = createGraphHopperInstance(relDir + "core/files/andorra.osm.pbf"); // get encoder from GraphHopper instance EncodingManager encodingManager = hopper.getEncodingManager(); // snap some GPS coordinates to the routing graph and build a query graph Weighting weighting = hopper.createWeighting(hopper.getProfile("car"), new PMap()); Snap snap = hopper.getLocationIndex().findClosest(42.508679, 1.532078, new DefaultSnapFilter(weighting, encodingManager.getBooleanEncodedValue(Subnetwork.key("car")))); QueryGraph queryGraph = QueryGraph.create(hopper.getBaseGraph(), snap); // run the isochrone calculation ShortestPathTree tree = new ShortestPathTree(queryGraph, weighting, false, TraversalMode.NODE_BASED); // find all nodes that are within a radius of 120s tree.setTimeLimit(120_000); AtomicInteger counter = new AtomicInteger(0); // you need to specify a callback to define what should be done tree.search(snap.getClosestNode(), label -> { // see IsoLabel.java for more properties // System.out.println("node: " + label.node + ", time: " + label.time + ", distance: " + label.distance); counter.incrementAndGet(); }); assert counter.get() > 200;
graphhopper_graphhopper
graphhopper/example/src/main/java/com/graphhopper/example/LocationIndexExample.java
LocationIndexExample
graphhopperLocationIndex
class LocationIndexExample { public static void main(String[] args) { String relDir = args.length == 1 ? args[0] : ""; graphhopperLocationIndex(relDir); lowLevelLocationIndex(); } public static void graphhopperLocationIndex(String relDir) {<FILL_FUNCTION_BODY>} public static void lowLevelLocationIndex() { // If you don't use the GraphHopper class you have to use the low level API: BaseGraph graph = new BaseGraph.Builder(1).create(); graph.edge(0, 1).setKeyValues(KVStorage.KeyValue.createKV("name", "test edge")); graph.getNodeAccess().setNode(0, 12, 42); graph.getNodeAccess().setNode(1, 12.01, 42.01); LocationIndexTree index = new LocationIndexTree(graph.getBaseGraph(), graph.getDirectory()); index.setResolution(300); index.setMaxRegionSearch(4); if (!index.loadExisting()) index.prepareIndex(); Snap snap = index.findClosest(12, 42, EdgeFilter.ALL_EDGES); EdgeIteratorState edge = snap.getClosestEdge(); assert edge.getValue("name").equals("test edge"); } }
GraphHopper hopper = new GraphHopper(); hopper.setEncodedValuesString("car_access, car_average_speed"); hopper.setProfiles(new Profile("car").setCustomModel(GHUtility.loadCustomModelFromJar("car.json"))); hopper.setOSMFile(relDir + "core/files/andorra.osm.pbf"); hopper.setGraphHopperLocation("./target/locationindex-graph-cache"); hopper.importOrLoad(); LocationIndex index = hopper.getLocationIndex(); // now you can fetch the closest edge via: Snap snap = index.findClosest(42.508552, 1.532936, EdgeFilter.ALL_EDGES); EdgeIteratorState edge = snap.getClosestEdge(); assert edge.getName().equals("Avinguda Meritxell");
graphhopper_graphhopper
graphhopper/example/src/main/java/com/graphhopper/example/LowLevelAPIExample.java
LowLevelAPIExample
createAndSaveGraph
class LowLevelAPIExample { public static void main(String[] args) { createAndSaveGraph(); useContractionHierarchiesToMakeQueriesFaster(); } private static final String graphLocation = "target/lowlevel-graph"; public static void createAndSaveGraph() {<FILL_FUNCTION_BODY>} public static void useContractionHierarchiesToMakeQueriesFaster() { // Creating and saving the graph BooleanEncodedValue accessEnc = VehicleAccess.create("car"); DecimalEncodedValue speedEnc = VehicleSpeed.create("car", 7, 2, false); EncodingManager em = EncodingManager.start().add(accessEnc).add(speedEnc).build(); BaseGraph graph = new BaseGraph.Builder(em) .setDir(new RAMDirectory(graphLocation, true)) .create(); graph.flush(); Weighting weighting = CustomModelParser.createWeighting(em, TurnCostProvider.NO_TURN_COST_PROVIDER, new CustomModel().addToPriority(If("!" + accessEnc.getName(), MULTIPLY, "0")).addToSpeed(If("true", LIMIT, speedEnc.getName()))); CHConfig chConfig = CHConfig.nodeBased("my_profile", weighting); // Set node coordinates and build location index NodeAccess na = graph.getNodeAccess(); graph.edge(0, 1).set(accessEnc, true).set(speedEnc, 10).setDistance(1020); na.setNode(0, 15.15, 20.20); na.setNode(1, 15.25, 20.21); // Prepare the graph for fast querying ... graph.freeze(); PrepareContractionHierarchies pch = PrepareContractionHierarchies.fromGraph(graph, chConfig); PrepareContractionHierarchies.Result pchRes = pch.doWork(); RoutingCHGraph chGraph = RoutingCHGraphImpl.fromGraph(graph, pchRes.getCHStorage(), pchRes.getCHConfig()); // create location index LocationIndexTree index = new LocationIndexTree(graph, graph.getDirectory()); index.prepareIndex(); // calculate a path with location index Snap fromSnap = index.findClosest(15.15, 20.20, EdgeFilter.ALL_EDGES); Snap toSnap = index.findClosest(15.25, 20.21, EdgeFilter.ALL_EDGES); QueryGraph queryGraph = QueryGraph.create(graph, fromSnap, toSnap); EdgeToEdgeRoutingAlgorithm algo = new CHRoutingAlgorithmFactory(chGraph, queryGraph).createAlgo(new PMap()); Path path = algo.calcPath(fromSnap.getClosestNode(), toSnap.getClosestNode()); assert Helper.round(path.getDistance(), -2) == 1000; } }
{ BooleanEncodedValue accessEnc = VehicleAccess.create("car"); DecimalEncodedValue speedEnc = VehicleSpeed.create("car", 7, 2, false); EncodingManager em = EncodingManager.start().add(accessEnc).add(speedEnc).build(); BaseGraph graph = new BaseGraph.Builder(em).setDir(new RAMDirectory(graphLocation, true)).create(); // Make a weighted edge between two nodes and set average speed to 50km/h EdgeIteratorState edge = graph.edge(0, 1).setDistance(1234).set(speedEnc, 50); // Set node coordinates and build location index NodeAccess na = graph.getNodeAccess(); graph.edge(0, 1).set(accessEnc, true).set(speedEnc, 10).setDistance(1530); na.setNode(0, 15.15, 20.20); na.setNode(1, 15.25, 20.21); LocationIndexTree index = new LocationIndexTree(graph, graph.getDirectory()); index.prepareIndex(); // Flush the graph and location index to disk graph.flush(); index.flush(); graph.close(); index.close(); } { // Load the graph ... can be also in a different code location // note that the EncodingManager must be the same BooleanEncodedValue accessEnc = VehicleAccess.create("car"); DecimalEncodedValue speedEnc = VehicleSpeed.create("car", 7, 2, false); EncodingManager em = EncodingManager.start().add(accessEnc).add(speedEnc).build(); BaseGraph graph = new BaseGraph.Builder(em).setDir(new RAMDirectory(graphLocation, true)).build(); graph.loadExisting(); // Load the location index LocationIndexTree index = new LocationIndexTree(graph.getBaseGraph(), graph.getDirectory()); if (!index.loadExisting()) throw new IllegalStateException("location index cannot be loaded!"); // calculate with location index Snap fromSnap = index.findClosest(15.15, 20.20, EdgeFilter.ALL_EDGES); Snap toSnap = index.findClosest(15.25, 20.21, EdgeFilter.ALL_EDGES); QueryGraph queryGraph = QueryGraph.create(graph, fromSnap, toSnap); Weighting weighting = CustomModelParser.createWeighting(em, TurnCostProvider.NO_TURN_COST_PROVIDER, new CustomModel().addToPriority(If("!" + accessEnc.getName(), MULTIPLY, "0")).addToSpeed(If("true", LIMIT, speedEnc.getName()))); Path path = new Dijkstra(queryGraph, weighting, TraversalMode.NODE_BASED).calcPath(fromSnap.getClosestNode(), toSnap.getClosestNode()); assert Helper.round(path.getDistance(), -2) == 1500; // calculate without location index (get the fromId and toId nodes from other code parts) path = new Dijkstra(graph, weighting, TraversalMode.NODE_BASED).calcPath(0, 1); assert Helper.round(path.getDistance(), -2) == 1500; }
graphhopper_graphhopper
graphhopper/example/src/main/java/com/graphhopper/example/RoutingExample.java
RoutingExample
createGraphHopperInstance
class RoutingExample { public static void main(String[] args) { String relDir = args.length == 1 ? args[0] : ""; GraphHopper hopper = createGraphHopperInstance(relDir + "core/files/andorra.osm.pbf"); routing(hopper); speedModeVersusFlexibleMode(hopper); alternativeRoute(hopper); customizableRouting(relDir + "core/files/andorra.osm.pbf"); // release resources to properly shutdown or start a new instance hopper.close(); } static GraphHopper createGraphHopperInstance(String ghLoc) {<FILL_FUNCTION_BODY>} public static void routing(GraphHopper hopper) { // simple configuration of the request object GHRequest req = new GHRequest(42.508552, 1.532936, 42.507508, 1.528773). // note that we have to specify which profile we are using even when there is only one like here setProfile("car"). // define the language for the turn instructions setLocale(Locale.US); GHResponse rsp = hopper.route(req); // handle errors if (rsp.hasErrors()) throw new RuntimeException(rsp.getErrors().toString()); // use the best path, see the GHResponse class for more possibilities. ResponsePath path = rsp.getBest(); // points, distance in meters and time in millis of the full path PointList pointList = path.getPoints(); double distance = path.getDistance(); long timeInMs = path.getTime(); Translation tr = hopper.getTranslationMap().getWithFallBack(Locale.UK); InstructionList il = path.getInstructions(); // iterate over all turn instructions for (Instruction instruction : il) { // System.out.println("distance " + instruction.getDistance() + " for instruction: " + instruction.getTurnDescription(tr)); } assert il.size() == 6; assert Helper.round(path.getDistance(), -2) == 600; } public static void speedModeVersusFlexibleMode(GraphHopper hopper) { GHRequest req = new GHRequest(42.508552, 1.532936, 42.507508, 1.528773). setProfile("car").setAlgorithm(Parameters.Algorithms.ASTAR_BI).putHint(Parameters.CH.DISABLE, true); GHResponse res = hopper.route(req); if (res.hasErrors()) throw new RuntimeException(res.getErrors().toString()); assert Helper.round(res.getBest().getDistance(), -2) == 600; } public static void alternativeRoute(GraphHopper hopper) { // calculate alternative routes between two points (supported with and without CH) GHRequest req = new GHRequest().setProfile("car"). addPoint(new GHPoint(42.502904, 1.514714)).addPoint(new GHPoint(42.508774, 1.537094)). setAlgorithm(Parameters.Algorithms.ALT_ROUTE); req.getHints().putObject(Parameters.Algorithms.AltRoute.MAX_PATHS, 3); GHResponse res = hopper.route(req); if (res.hasErrors()) throw new RuntimeException(res.getErrors().toString()); assert res.getAll().size() == 2; assert Helper.round(res.getBest().getDistance(), -2) == 2200; } /** * To customize profiles in the config.yml file you can use a json or yml file or embed it directly. See this list: * web/src/test/resources/com/graphhopper/application/resources and https://www.graphhopper.com/?s=customizable+routing */ public static void customizableRouting(String ghLoc) { GraphHopper hopper = new GraphHopper(); hopper.setOSMFile(ghLoc); hopper.setGraphHopperLocation("target/routing-custom-graph-cache"); hopper.setEncodedValuesString("car_access, car_average_speed"); hopper.setProfiles(new Profile("car_custom").setCustomModel(GHUtility.loadCustomModelFromJar("car.json"))); // The hybrid mode uses the "landmark algorithm" and is up to 15x faster than the flexible mode (Dijkstra). // Still it is slower than the speed mode ("contraction hierarchies algorithm") ... hopper.getLMPreparationHandler().setLMProfiles(new LMProfile("car_custom")); hopper.importOrLoad(); // ... but for the hybrid mode we can customize the route calculation even at request time: // 1. a request with default preferences GHRequest req = new GHRequest().setProfile("car_custom"). addPoint(new GHPoint(42.506472, 1.522475)).addPoint(new GHPoint(42.513108, 1.536005)); GHResponse res = hopper.route(req); if (res.hasErrors()) throw new RuntimeException(res.getErrors().toString()); assert Math.round(res.getBest().getTime() / 1000d) == 94; // 2. now avoid the secondary road and reduce the maximum speed, see docs/core/custom-models.md for an in-depth explanation // and also the blog posts https://www.graphhopper.com/?s=customizable+routing CustomModel model = new CustomModel(); model.addToPriority(If("road_class == SECONDARY", MULTIPLY, "0.5")); // unconditional limit to 20km/h model.addToSpeed(If("true", LIMIT, "30")); req.setCustomModel(model); res = hopper.route(req); if (res.hasErrors()) throw new RuntimeException(res.getErrors().toString()); assert Math.round(res.getBest().getTime() / 1000d) == 184; } }
GraphHopper hopper = new GraphHopper(); hopper.setOSMFile(ghLoc); // specify where to store graphhopper files hopper.setGraphHopperLocation("target/routing-graph-cache"); // add all encoded values that are used in the custom model, these are also available as path details or for client-side custom models hopper.setEncodedValuesString("car_access, car_average_speed"); // see docs/core/profiles.md to learn more about profiles hopper.setProfiles(new Profile("car").setCustomModel(GHUtility.loadCustomModelFromJar("car.json"))); // this enables speed mode for the profile we called car hopper.getCHPreparationHandler().setCHProfiles(new CHProfile("car")); // now this can take minutes if it imports or a few seconds for loading of course this is dependent on the area you import hopper.importOrLoad(); return hopper;
graphhopper_graphhopper
graphhopper/example/src/main/java/com/graphhopper/example/RoutingExampleTC.java
RoutingExampleTC
routeWithTurnCostsAndCurbsidesAndOtherUTurnCosts
class RoutingExampleTC { public static void main(String[] args) { String relDir = args.length == 1 ? args[0] : ""; GraphHopper hopper = createGraphHopperInstance(relDir + "core/files/andorra.osm.pbf"); routeWithTurnCosts(hopper); routeWithTurnCostsAndCurbsides(hopper); routeWithTurnCostsAndCurbsidesAndOtherUTurnCosts(hopper); } public static void routeWithTurnCosts(GraphHopper hopper) { GHRequest req = new GHRequest(42.50822, 1.533966, 42.506899, 1.525372). setProfile("car"); route(hopper, req, 1038, 63_000); } public static void routeWithTurnCostsAndCurbsides(GraphHopper hopper) { GHRequest req = new GHRequest(42.50822, 1.533966, 42.506899, 1.525372). setCurbsides(Arrays.asList(CURBSIDE_ANY, CURBSIDE_RIGHT)). setProfile("car"); route(hopper, req, 1370, 128_000); } public static void routeWithTurnCostsAndCurbsidesAndOtherUTurnCosts(GraphHopper hopper) {<FILL_FUNCTION_BODY>} private static void route(GraphHopper hopper, GHRequest req, int expectedDistance, int expectedTime) { GHResponse rsp = hopper.route(req); // handle errors if (rsp.hasErrors()) // if you get: Impossible curbside constraint: 'curbside=right' // you either specify 'curbside=any' or Parameters.Routing.FORCE_CURBSIDE=false to ignore this situation throw new RuntimeException(rsp.getErrors().toString()); ResponsePath path = rsp.getBest(); assert Math.abs(expectedDistance - path.getDistance()) < 1 : "unexpected distance : " + path.getDistance() + " vs. " + expectedDistance; assert Math.abs(expectedTime - path.getTime()) < 1000 : "unexpected time : " + path.getTime() + " vs. " + expectedTime; } // see RoutingExample for more details static GraphHopper createGraphHopperInstance(String ghLoc) { GraphHopper hopper = new GraphHopper(); hopper.setOSMFile(ghLoc); hopper.setGraphHopperLocation("target/routing-tc-graph-cache"); // add all encoded values that are used in the custom model, these are also available as path details or for client-side custom models hopper.setEncodedValuesString("car_access, car_average_speed"); Profile profile = new Profile("car").setCustomModel(GHUtility.loadCustomModelFromJar("car.json")) // enabling turn costs means OSM turn restriction constraints like 'no_left_turn' will be taken into account for the specified access restrictions // we can also set u_turn_costs (in seconds). i.e. we will consider u-turns at all junctions with a 40s time penalty .setTurnCostsConfig(new TurnCostsConfig(List.of("motorcar", "motor_vehicle"), 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; } }
GHRequest req = new GHRequest(42.50822, 1.533966, 42.506899, 1.525372) .setCurbsides(Arrays.asList(CURBSIDE_ANY, CURBSIDE_RIGHT)) // to change u-turn costs per request we have to disable CH. otherwise the u-turn costs we set per request // will be ignored and those set for our profile will be used. .putHint(Parameters.CH.DISABLE, true) .setProfile("car"); route(hopper, req.putHint(Parameters.Routing.U_TURN_COSTS, 10), 1370, 98_700); route(hopper, req.putHint(Parameters.Routing.U_TURN_COSTS, 15), 1370, 103_700);
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/Distributions.java
Distributions
normalDistribution
class Distributions { static double normalDistribution(double sigma, double x) {<FILL_FUNCTION_BODY>} /** * Use this function instead of Math.log(normalDistribution(sigma, x)) to avoid an * arithmetic underflow for very small probabilities. */ public static double logNormalDistribution(double sigma, double x) { return Math.log(1.0 / (sqrt(2.0 * PI) * sigma)) + (-0.5 * pow(x / sigma, 2)); } /** * @param beta =1/lambda with lambda being the standard exponential distribution rate parameter */ static double exponentialDistribution(double beta, double x) { return 1.0 / beta * exp(-x / beta); } /** * Use this function instead of Math.log(exponentialDistribution(beta, x)) to avoid an * arithmetic underflow for very small probabilities. * * @param beta =1/lambda with lambda being the standard exponential distribution rate parameter */ static double logExponentialDistribution(double beta, double x) { return log(1.0 / beta) - (x / beta); } }
return 1.0 / (sqrt(2.0 * PI) * sigma) * exp(-0.5 * pow(x / sigma, 2));
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/EdgeMatch.java
EdgeMatch
toString
class EdgeMatch { private final EdgeIteratorState edgeState; private final List<State> states; public EdgeMatch(EdgeIteratorState edgeState, List<State> state) { this.edgeState = edgeState; if (edgeState == null) { throw new IllegalStateException("Cannot fetch null EdgeState"); } this.states = state; if (this.states == null) { throw new IllegalStateException("state list cannot be null"); } } public EdgeIteratorState getEdgeState() { return edgeState; } public List<State> getStates() { return states; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "edge:" + edgeState + ", states:" + states;
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/HmmProbabilities.java
HmmProbabilities
transitionLogProbability
class HmmProbabilities { private final double sigma; private final double beta; /** * @param sigma standard deviation of the normal distribution [m] used for * modeling the GPS error * @param beta beta parameter of the exponential distribution used for modeling * transition probabilities */ public HmmProbabilities(double sigma, double beta) { this.sigma = sigma; this.beta = beta; } /** * Returns the logarithmic emission probability density. * * @param distance Absolute distance [m] between GPS measurement and map * matching candidate. */ public double emissionLogProbability(double distance) { return Distributions.logNormalDistribution(sigma, distance); } /** * Returns the logarithmic transition probability density for the given * transition parameters. * * @param routeLength Length of the shortest route [m] between two * consecutive map matching candidates. * @param linearDistance Linear distance [m] between two consecutive GPS * measurements. */ public double transitionLogProbability(double routeLength, double linearDistance) {<FILL_FUNCTION_BODY>} }
// Transition metric taken from Newson & Krumm. double transitionMetric = Math.abs(linearDistance - routeLength); return Distributions.logExponentialDistribution(beta, transitionMetric);
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/MapMatching.java
MapMatching
computeViterbiSequence
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) { 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) {<FILL_FUNCTION_BODY>} 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 (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/MatchResult.java
MatchResult
toString
class MatchResult { private List<EdgeMatch> edgeMatches; private Path mergedPath; private Weighting weighting; private Graph graph; private double matchLength; private long matchMillis; private double gpxEntriesLength; private long gpxEntriesMillis; public MatchResult(List<EdgeMatch> edgeMatches) { setEdgeMatches(edgeMatches); } public void setEdgeMatches(List<EdgeMatch> edgeMatches) { if (edgeMatches == null) { throw new IllegalStateException("edgeMatches cannot be null"); } this.edgeMatches = edgeMatches; } public void setGPXEntriesLength(double gpxEntriesLength) { this.gpxEntriesLength = gpxEntriesLength; } public void setGPXEntriesMillis(long gpxEntriesMillis) { this.gpxEntriesMillis = gpxEntriesMillis; } public void setMatchLength(double matchLength) { this.matchLength = matchLength; } public void setMatchMillis(long matchMillis) { this.matchMillis = matchMillis; } public void setMergedPath(Path mergedPath) { this.mergedPath = mergedPath; } /** * All possible assigned edges. */ public List<EdgeMatch> getEdgeMatches() { return edgeMatches; } /** * Length of the original GPX track in meters */ public double getGpxEntriesLength() { return gpxEntriesLength; } /** * Length of the map-matched route in meters */ public double getMatchLength() { return matchLength; } /** * Duration of the map-matched route in milliseconds */ public long getMatchMillis() { return matchMillis; } public Path getMergedPath() { return mergedPath; } @Override public String toString() {<FILL_FUNCTION_BODY>} public Weighting getWeighting() { return weighting; } public void setWeighting(Weighting weighting) { this.weighting = weighting; } public Graph getGraph() { return graph; } public void setGraph(Graph graph) { this.graph = graph; } }
return "length:" + matchLength + ", seconds:" + matchMillis / 1000f + ", matches:" + edgeMatches.toString();
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/Observation.java
Observation
equals
class Observation { private GHPoint point; private double accumulatedLinearDistanceToPrevious; public Observation(GHPoint p) { this.point = p; } public GHPoint getPoint() { return point; } public double getAccumulatedLinearDistanceToPrevious() { return accumulatedLinearDistanceToPrevious; } public void setAccumulatedLinearDistanceToPrevious(double accumulatedLinearDistanceToPrevious) { this.accumulatedLinearDistanceToPrevious = accumulatedLinearDistanceToPrevious; } @Override public String toString() { return "Observation{" + "point=" + point + '}'; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(point); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Observation that = (Observation) o; return Objects.equals(point, that.point);
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/SequenceState.java
SequenceState
toString
class SequenceState<S, O, D> { public final S state; /** * Null if HMM was started with initial state probabilities and state is the initial state. */ public final O observation; /** * Null if transition descriptor was not provided. */ public final D transitionDescriptor; public SequenceState(S state, O observation, D transitionDescriptor) { this.state = state; this.observation = observation; this.transitionDescriptor = transitionDescriptor; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(state, observation, transitionDescriptor); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SequenceState<?, ?, ?> other = (SequenceState<?, ?, ?>) obj; return Objects.equals(state, other.state) && Objects.equals(observation, other.observation) && Objects.equals(transitionDescriptor, other.transitionDescriptor); } }
return "SequenceState [state=" + state + ", observation=" + observation + ", transitionDescriptor=" + transitionDescriptor + "]";
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/State.java
State
toString
class State { private final Observation entry; private final Snap snap; private final boolean isDirected; private final EdgeIteratorState incomingVirtualEdge; private final EdgeIteratorState outgoingVirtualEdge; /** * Creates an undirected candidate for a real node. */ public State(Observation entry, Snap snap) { this.entry = entry; this.snap = snap; this.isDirected = false; this.incomingVirtualEdge = null; this.outgoingVirtualEdge = null; } /** * Creates a directed candidate for a virtual node. */ public State(Observation entry, Snap snap, VirtualEdgeIteratorState incomingVirtualEdge, VirtualEdgeIteratorState outgoingVirtualEdge) { this.entry = entry; this.snap = snap; this.isDirected = true; this.incomingVirtualEdge = incomingVirtualEdge; this.outgoingVirtualEdge = outgoingVirtualEdge; } public Observation getEntry() { return entry; } public Snap getSnap() { return snap; } /** * Returns whether this State is directed. This is true if the snapped point * is a virtual node, otherwise the snapped node is a real (tower) node and false is returned. */ public boolean isOnDirectedEdge() { return isDirected; } /** * Returns the virtual edge that should be used by incoming paths. * * @throws IllegalStateException if this State is not directed. */ public EdgeIteratorState getIncomingVirtualEdge() { if (!isDirected) { throw new IllegalStateException( "This method may only be called for directed GPXExtensions"); } return incomingVirtualEdge; } /** * Returns the virtual edge that should be used by outgoing paths. * * @throws IllegalStateException if this State is not directed. */ public EdgeIteratorState getOutgoingVirtualEdge() { if (!isDirected) { throw new IllegalStateException( "This method may only be called for directed GPXExtensions"); } return outgoingVirtualEdge; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "State{" + "closest node=" + snap.getClosestNode() + " at " + snap.getSnappedPoint().getLat() + "," + snap.getSnappedPoint().getLon() + ", incomingEdge=" + incomingVirtualEdge + ", outgoingEdge=" + outgoingVirtualEdge + '}';
graphhopper_graphhopper
graphhopper/map-matching/src/main/java/com/graphhopper/matching/Transition.java
Transition
equals
class Transition<S> { public final S fromCandidate; public final S toCandidate; public Transition(S fromCandidate, S toCandidate) { this.fromCandidate = fromCandidate; this.toCandidate = toCandidate; } @Override public int hashCode() { return Objects.hash(fromCandidate, toCandidate); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "Transition [fromCandidate=" + fromCandidate + ", toCandidate=" + toCandidate + "]"; } }
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") Transition<S> other = (Transition<S>) obj; return Objects.equals(fromCandidate, other.fromCandidate) && Objects.equals(toCandidate, other.toCandidate);
graphhopper_graphhopper
graphhopper/navigation/src/main/java/com/graphhopper/navigation/DistanceConfig.java
DistanceConfig
getVoiceInstructionsForDistance
class DistanceConfig { final List<VoiceInstructionConfig> voiceInstructions; public DistanceConfig(DistanceUtils.Unit unit, TranslationMap translationMap, Locale locale) { if (unit == DistanceUtils.Unit.METRIC) { voiceInstructions = Arrays.asList( new InitialVoiceInstructionConfig(FOR_HIGHER_DISTANCE_PLURAL.metric, translationMap, locale, 4250, 250, unit), new FixedDistanceVoiceInstructionConfig(IN_HIGHER_DISTANCE_PLURAL.metric, translationMap, locale, 2000, 2), new FixedDistanceVoiceInstructionConfig(IN_HIGHER_DISTANCE_SINGULAR.metric, translationMap, locale, 1000, 1), new ConditionalDistanceVoiceInstructionConfig(IN_LOWER_DISTANCE_PLURAL.metric, translationMap, locale, new int[]{400, 200}, new int[]{400, 200}) ); } else { voiceInstructions = Arrays.asList( new InitialVoiceInstructionConfig(FOR_HIGHER_DISTANCE_PLURAL.metric, translationMap, locale, 4250, 250, unit), new FixedDistanceVoiceInstructionConfig(IN_HIGHER_DISTANCE_PLURAL.imperial, translationMap, locale, 3220, 2), new FixedDistanceVoiceInstructionConfig(IN_HIGHER_DISTANCE_SINGULAR.imperial, translationMap, locale, 1610, 1), new ConditionalDistanceVoiceInstructionConfig(IN_LOWER_DISTANCE_PLURAL.imperial, translationMap, locale, new int[]{400, 200}, new int[]{1300, 600}) ); } } public List<VoiceInstructionConfig.VoiceInstructionValue> getVoiceInstructionsForDistance(double distance, String turnDescription, String thenVoiceInstruction) {<FILL_FUNCTION_BODY>} }
List<VoiceInstructionConfig.VoiceInstructionValue> instructionsConfigs = new ArrayList<>(voiceInstructions.size()); for (VoiceInstructionConfig voiceConfig : voiceInstructions) { VoiceInstructionConfig.VoiceInstructionValue confi = voiceConfig.getConfigForDistance(distance, turnDescription, thenVoiceInstruction); if (confi != null) { instructionsConfigs.add(confi); } } return instructionsConfigs;
graphhopper_graphhopper
graphhopper/navigation/src/main/java/com/graphhopper/navigation/VoiceInstructionConfig.java
ConditionalDistanceVoiceInstructionConfig
getFittingInstructionIndex
class ConditionalDistanceVoiceInstructionConfig extends VoiceInstructionConfig { private final int[] distanceAlongGeometry; // distances in meter in which the instruction should be spoken private final int[] distanceVoiceValue; // distances in required unit. f.e: 1km, 300m or 2mi public ConditionalDistanceVoiceInstructionConfig(String key, TranslationMap translationMap, Locale locale, int[] distanceAlongGeometry, int[] distanceVoiceValue) { super(key, translationMap, locale); this.distanceAlongGeometry = distanceAlongGeometry; this.distanceVoiceValue = distanceVoiceValue; if (distanceAlongGeometry.length != distanceVoiceValue.length) { throw new IllegalArgumentException("distanceAlongGeometry and distanceVoiceValue are not same size"); } } private int getFittingInstructionIndex(double distanceMeter) {<FILL_FUNCTION_BODY>} @Override public VoiceInstructionValue getConfigForDistance(double distance, String turnDescription, String thenVoiceInstruction) { int instructionIndex = getFittingInstructionIndex(distance); if (instructionIndex < 0) { return null; } String totalDescription = translationMap.getWithFallBack(locale).tr("navigate." + translationKey, distanceVoiceValue[instructionIndex]) + " " + turnDescription + thenVoiceInstruction; int spokenDistance = distanceAlongGeometry[instructionIndex]; return new VoiceInstructionValue(spokenDistance, totalDescription); } }
for (int i = 0; i < distanceAlongGeometry.length; i++) { if (distanceMeter >= distanceAlongGeometry[i]) { return i; } } return -1;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/error/GTFSError.java
GTFSError
compareTo
class GTFSError implements Comparable<GTFSError>, Serializable { public final String file; // TODO GTFSTable enum? Or simply use class objects. public final long line; public final String field; public final String affectedEntityId; public final String errorType; public GTFSError(String file, long line, String field) { this(file, line, field, null); } public GTFSError(String file, long line, String field, String affectedEntityId) { this.file = file; this.line = line; this.field = field; this.affectedEntityId = affectedEntityId; this.errorType = this.getClass().getSimpleName(); } public String getMessage() { return "no message"; } public String getMessageWithContext() { StringBuilder sb = new StringBuilder(); sb.append(file); sb.append(' '); if (line >= 0) { sb.append("line "); sb.append(line); } else { sb.append("(no line)"); } if (field != null) { sb.append(", field '"); sb.append(field); sb.append('\''); } sb.append(": "); sb.append(getMessage()); return sb.toString(); } /** must be comparable to put into mapdb */ public int compareTo (GTFSError o) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "GTFSError: " + getMessageWithContext(); } }
if (this.file == null && o.file != null) return -1; else if (this.file != null && o.file == null) return 1; int file = this.file == null && o.file == null ? 0 : String.CASE_INSENSITIVE_ORDER.compare(this.file, o.file); if (file != 0) return file; int errorType = String.CASE_INSENSITIVE_ORDER.compare(this.errorType, o.errorType); if (errorType != 0) return errorType; int affectedEntityId = this.affectedEntityId == null && o.affectedEntityId == null ? 0 : String.CASE_INSENSITIVE_ORDER.compare(this.affectedEntityId, o.affectedEntityId); if (affectedEntityId != 0) return affectedEntityId; else return Long.compare(this.line, o.line);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/error/ReferentialIntegrityError.java
ReferentialIntegrityError
compareTo
class ReferentialIntegrityError extends GTFSError implements Serializable { public static final long serialVersionUID = 1L; // TODO: maybe also store the entity ID of the entity which contained the bad reference, in addition to the row number public final String badReference; public ReferentialIntegrityError(String tableName, long row, String field, String badReference) { super(tableName, row, field); this.badReference = badReference; } /** must be comparable to put into mapdb */ @Override public int compareTo (GTFSError o) {<FILL_FUNCTION_BODY>} @Override public String getMessage() { return String.format("Invalid reference %s", badReference); } }
int compare = super.compareTo(o); if (compare != 0) return compare; return this.badReference.compareTo((((ReferentialIntegrityError) o).badReference));
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Agency.java
Agency
loadOneRow
class Agency extends Entity { private static final long serialVersionUID = -2825890165823575940L; public String agency_id; public String agency_name; public URL agency_url; public String agency_timezone; public String agency_lang; public String agency_phone; public URL agency_fare_url; public URL agency_branding_url; public String feed_id; public static class Loader extends Entity.Loader<Agency> { public Loader(GTFSFeed feed) { super(feed, "agency"); } @Override protected boolean isRequired() { return true; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
Agency a = new Agency(); a.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index a.agency_id = getStringField("agency_id", false); // can only be absent if there is a single agency -- requires a special validator. a.agency_name = getStringField("agency_name", true); a.agency_url = getUrlField("agency_url", true); a.agency_lang = getStringField("agency_lang", false); a.agency_phone = getStringField("agency_phone", false); a.agency_timezone = getStringField("agency_timezone", true); a.agency_fare_url = getUrlField("agency_fare_url", false); a.agency_branding_url = getUrlField("agency_branding_url", false); a.feed = feed; a.feed_id = feed.feedId; // TODO clooge due to not being able to have null keys in mapdb if (a.agency_id == null) a.agency_id = "NONE"; feed.agency.put(a.agency_id, a);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Calendar.java
Calendar
loadOneRow
class Calendar extends Entity implements Serializable { private static final long serialVersionUID = 6634236680822635875L; public int monday; public int tuesday; public int wednesday; public int thursday; public int friday; public int saturday; public int sunday; public int start_date; public int end_date; public String feed_id; public String service_id; public static class Loader extends Entity.Loader<Calendar> { private final Map<String, Service> services; /** * Create a loader. The map parameter should be an in-memory map that will be modified. We can't write directly * to MapDB because we modify services as we load calendar dates, and this creates concurrentmodificationexceptions. */ public Loader(GTFSFeed feed, Map<String, Service> services) { super(feed, "calendar"); this.services = services; } @Override protected boolean isRequired() { return true; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
/* Calendars and Fares are special: they are stored as joined tables rather than simple maps. */ String service_id = getStringField("service_id", true); // TODO service_id can reference either calendar or calendar_dates. Service service = services.computeIfAbsent(service_id, Service::new); if (service.calendar != null) { feed.errors.add(new DuplicateKeyError(tableName, row, "service_id")); } else { Calendar c = new Calendar(); c.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index c.service_id = service.service_id; c.monday = getIntField("monday", true, 0, 1); c.tuesday = getIntField("tuesday", true, 0, 1); c.wednesday = getIntField("wednesday", true, 0, 1); c.thursday = getIntField("thursday", true, 0, 1); c.friday = getIntField("friday", true, 0, 1); c.saturday = getIntField("saturday", true, 0, 1); c.sunday = getIntField("sunday", true, 0, 1); // TODO check valid dates c.start_date = getIntField("start_date", true, 18500101, 22001231); c.end_date = getIntField("end_date", true, 18500101, 22001231); c.feed = feed; c.feed_id = feed.feedId; service.calendar = c; }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/CalendarDate.java
CalendarDate
loadOneRow
class CalendarDate extends Entity implements Cloneable, Serializable { private static final long serialVersionUID = 6936614582249119431L; public String service_id; public LocalDate date; public int exception_type; public CalendarDate clone () { try { return (CalendarDate) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static class Loader extends Entity.Loader<CalendarDate> { private final Map<String, Service> services; /** * Create a loader. The map parameter should be an in-memory map that will be modified. We can't write directly * to MapDB because we modify services as we load calendar dates, and this creates concurrentmodificationexceptions. */ public Loader(GTFSFeed feed, Map<String, Service> services) { super(feed, "calendar_dates"); this.services = services; } @Override protected boolean isRequired() { return false; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
/* Calendars and Fares are special: they are stored as joined tables rather than simple maps. */ String service_id = getStringField("service_id", true); Service service = services.computeIfAbsent(service_id, Service::new); LocalDate date = getDateField("date", true); if (service.calendar_dates.containsKey(date)) { feed.errors.add(new DuplicateKeyError(tableName, row, "(service_id, date)")); } else { CalendarDate cd = new CalendarDate(); cd.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index cd.service_id = service_id; cd.date = date; cd.exception_type = getIntField("exception_type", true, 1, 2); cd.feed = feed; service.calendar_dates.put(date, cd); }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/FareAttribute.java
FareAttribute
loadOneRow
class FareAttribute extends Entity { private static final long serialVersionUID = 2157859372072056891L; public String fare_id; public double price; public String currency_type; public int payment_method; public int transfers; public int transfer_duration; public String feed_id; public static class Loader extends Entity.Loader<FareAttribute> { private final Map<String, Fare> fares; public Loader(GTFSFeed feed, Map<String, Fare> fares) { super(feed, "fare_attributes"); this.fares = fares; } @Override protected boolean isRequired() { return false; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
/* Calendars and Fares are special: they are stored as joined tables rather than simple maps. */ String fareId = getStringField("fare_id", true); Fare fare = fares.computeIfAbsent(fareId, Fare::new); if (fare.fare_attribute != null) { feed.errors.add(new DuplicateKeyError(tableName, row, "fare_id")); } else { FareAttribute fa = new FareAttribute(); fa.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index fa.fare_id = fareId; fa.price = getDoubleField("price", true, 0, Integer.MAX_VALUE); fa.currency_type = getStringField("currency_type", true); fa.payment_method = getIntField("payment_method", true, 0, 1); fa.transfers = getIntField("transfers", false, 0, Integer.MAX_VALUE, Integer.MAX_VALUE); fa.transfer_duration = getIntField("transfer_duration", false, 0, 24*60*60, 24*60*60); fa.feed = feed; fa.feed_id = feed.feedId; fare.fare_attribute = fa; }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/FareRule.java
FareRule
loadOneRow
class FareRule extends Entity { private static final long serialVersionUID = 3209660216692732272L; public String fare_id; public String route_id; public String origin_id; public String destination_id; public String contains_id; public static class Loader extends Entity.Loader<FareRule> { private final Map<String, Fare> fares; public Loader(GTFSFeed feed, Map<String, Fare> fares) { super(feed, "fare_rules"); this.fares = fares; } @Override protected boolean isRequired() { return false; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
/* Calendars and Fares are special: they are stored as joined tables rather than simple maps. */ String fareId = getStringField("fare_id", true); /* Referential integrity check for fare id */ if (!fares.containsKey(fareId)) { this.feed.errors.add(new ReferentialIntegrityError(tableName, row, "fare_id", fareId)); } Fare fare = fares.computeIfAbsent(fareId, Fare::new); FareRule fr = new FareRule(); fr.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index fr.fare_id = fare.fare_id; fr.route_id = getStringField("route_id", false); fr.origin_id = getStringField("origin_id", false); fr.destination_id = getStringField("destination_id", false); fr.contains_id = getStringField("contains_id", false); fr.feed = feed; fare.fare_rules.add(fr);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/FeedInfo.java
FeedInfo
loadOneRow
class FeedInfo extends Entity implements Cloneable { private static final long serialVersionUID = 8718856987299076452L; public String feed_id = "NONE"; public String feed_publisher_name; public URL feed_publisher_url; public String feed_lang; public LocalDate feed_start_date; public LocalDate feed_end_date; public String feed_version; public FeedInfo clone () { try { return (FeedInfo) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static class Loader extends Entity.Loader<FeedInfo> { public Loader(GTFSFeed feed) { super(feed, "feed_info"); } @Override protected boolean isRequired() { return false; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
FeedInfo fi = new FeedInfo(); fi.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index fi.feed_id = getStringField("feed_id", false); fi.feed_publisher_name = getStringField("feed_publisher_name", true); fi.feed_publisher_url = getUrlField("feed_publisher_url", true); fi.feed_lang = getStringField("feed_lang", true); fi.feed_start_date = getDateField("feed_start_date", false); fi.feed_end_date = getDateField("feed_end_date", false); fi.feed_version = getStringField("feed_version", false); fi.feed = feed; if (feed.feedInfo.isEmpty()) { feed.feedInfo.put("NONE", fi); feed.feedId = fi.feed_id; } else { feed.errors.add(new GeneralError(tableName, row, null, "FeedInfo contains more than one record.")); }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Frequency.java
Frequency
loadOneRow
class Frequency extends Entity implements Comparable<Frequency> { /** * Frequency entries have no ID in GTFS so we define one based on the fields in the frequency entry. * * It is possible to have two identical frequency entries in the GTFS, which under our understanding of the situation * would mean that two sets of vehicles were randomly running the same trip at the same headway, but uncorrelated * with each other, which is almost certain to be an error. */ public String getId() { StringBuilder sb = new StringBuilder(); sb.append(trip_id); sb.append('_'); sb.append(convertToGtfsTime(start_time)); sb.append("_to_"); sb.append(convertToGtfsTime(end_time)); sb.append("_every_"); sb.append(String.format(Locale.getDefault(), "%dm%02ds", headway_secs / 60, headway_secs % 60)); if (exact_times == 1) sb.append("_exact"); return sb.toString(); } private static final long serialVersionUID = -7182161664471704133L; public String trip_id; public int start_time; public int end_time; public int headway_secs; public int exact_times; /** must have a comparator since they go in a navigable set that is serialized */ @Override public int compareTo(Frequency o) { return this.start_time - o.start_time; } public static class Loader extends Entity.Loader<Frequency> { public Loader(GTFSFeed feed) { super(feed, "frequencies"); } @Override protected boolean isRequired() { return false; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
Frequency f = new Frequency(); Trip trip = getRefField("trip_id", true, feed.trips); f.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index f.trip_id = trip.trip_id; f.start_time = getTimeField("start_time", true); f.end_time = getTimeField("end_time", true); f.headway_secs = getIntField("headway_secs", true, 1, 24 * 60 * 60); f.exact_times = getIntField("exact_times", false, 0, 1); f.feed = feed; feed.frequencies.add(Fun.t2(f.trip_id, f));
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Route.java
Route
loadOneRow
class Route extends Entity { // implements Entity.Factory<Route> private static final long serialVersionUID = -819444896818029068L; //Used for converting extended route types to simple route types //based on codes found here: https://developers.google.com/transit/gtfs/reference/extended-route-types public static final Map<Integer, Integer> EXTENTED_ROUTE_TYPE_MAPPING = new HashMap<>(); static { EXTENTED_ROUTE_TYPE_MAPPING.put(100, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(101, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(102, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(103, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(105, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(106, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(107, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(108, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(109, 2); EXTENTED_ROUTE_TYPE_MAPPING.put(200, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(201, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(202, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(204, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(208, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(400, 1); EXTENTED_ROUTE_TYPE_MAPPING.put(401, 1); EXTENTED_ROUTE_TYPE_MAPPING.put(402, 1); EXTENTED_ROUTE_TYPE_MAPPING.put(405, 1); EXTENTED_ROUTE_TYPE_MAPPING.put(700, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(701, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(702, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(704, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(715, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(717, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(800, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(900, 0); EXTENTED_ROUTE_TYPE_MAPPING.put(1000, 4); EXTENTED_ROUTE_TYPE_MAPPING.put(1300, 6); EXTENTED_ROUTE_TYPE_MAPPING.put(1400, 7); EXTENTED_ROUTE_TYPE_MAPPING.put(1501, 3); EXTENTED_ROUTE_TYPE_MAPPING.put(1700, 3); } public String route_id; public String agency_id; public String route_short_name; public String route_long_name; public String route_desc; public int route_type; public URL route_url; public String route_color; public String route_text_color; public URL route_branding_url; public String feed_id; public static class Loader extends Entity.Loader<Route> { public Loader(GTFSFeed feed) { super(feed, "routes"); } @Override protected boolean isRequired() { return true; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
Route r = new Route(); r.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index r.route_id = getStringField("route_id", true); Agency agency = getRefField("agency_id", false, feed.agency); // if there is only one agency, associate with it automatically if (agency == null && feed.agency.size() == 1) { agency = feed.agency.values().iterator().next(); } // If we still haven't got an agency, it's because we have a bad reference, or because there is no agency if (agency != null) { r.agency_id = agency.agency_id; } r.route_short_name = getStringField("route_short_name", false); // one or the other required, needs a special validator r.route_long_name = getStringField("route_long_name", false); r.route_desc = getStringField("route_desc", false); r.route_type = getIntField("route_type", true, 0, 7, 0, EXTENTED_ROUTE_TYPE_MAPPING); r.route_url = getUrlField("route_url", false); r.route_color = getStringField("route_color", false); r.route_text_color = getStringField("route_text_color", false); r.route_branding_url = getUrlField("route_branding_url", false); r.feed = feed; r.feed_id = feed.feedId; feed.routes.put(r.route_id, r);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Service.java
Service
activeOn
class Service implements Serializable { private static final long serialVersionUID = 7966238549509747091L; public String service_id; public Calendar calendar; public Map<LocalDate, CalendarDate> calendar_dates = Maps.newHashMap(); public Service(String service_id) { this.service_id = service_id; } /** * @param service_id the service_id to assign to the newly created copy. * @param daysToRemove the days of the week on which to deactivate service in the copy. * @return a copy of this Service with any service on the specified days of the week deactivated. */ public Service removeDays(String service_id, EnumSet<DayOfWeek> daysToRemove) { Service service = new Service(service_id); // First, duplicate any Calendar in this Service, minus the specified days of the week. if (this.calendar != null) { Calendar calendar = new Calendar(); // TODO calendar.getDaysOfWeek/setDaysOfWeek which allow simplifying this section and activeOn below. calendar.monday = daysToRemove.contains(MONDAY) ? 0 : this.calendar.monday; calendar.tuesday = daysToRemove.contains(TUESDAY) ? 0 : this.calendar.tuesday; calendar.wednesday = daysToRemove.contains(WEDNESDAY) ? 0 : this.calendar.wednesday; calendar.thursday = daysToRemove.contains(THURSDAY) ? 0 : this.calendar.thursday; calendar.friday = daysToRemove.contains(FRIDAY) ? 0 : this.calendar.friday; calendar.saturday = daysToRemove.contains(SATURDAY) ? 0 : this.calendar.saturday; calendar.sunday = daysToRemove.contains(SUNDAY) ? 0 : this.calendar.sunday; // The new calendar should cover exactly the same time range as the existing one. calendar.start_date = this.calendar.start_date; calendar.end_date = this.calendar.end_date; // Create the bidirectional reference between Calendar and Service. service.calendar = calendar; } // Copy over all exceptions whose dates fall on days of the week that are retained. this.calendar_dates.forEach((date, exception) -> { DayOfWeek dow = date.getDayOfWeek(); if (!daysToRemove.contains(dow)) { CalendarDate newException = exception.clone(); service.calendar_dates.put(date, newException); } }); return service; } /** * @return whether this Service is ever active at all, either from calendar or calendar_dates. */ public boolean hasAnyService() { // Look for any service defined in calendar (on days of the week). boolean hasAnyService = calendar != null && ( calendar.monday == 1 || calendar.tuesday == 1 || calendar.wednesday == 1 || calendar.thursday == 1 || calendar.friday == 1 || calendar.saturday == 1 || calendar.sunday == 1 ); // Also look for any exceptions of type 1 (added service). hasAnyService |= calendar_dates.values().stream().anyMatch(cd -> cd.exception_type == 1); return hasAnyService; } /** * Is this service active on the specified date? */ public boolean activeOn (LocalDate date) {<FILL_FUNCTION_BODY>} /** * Checks for overlapping days of week between two service calendars * @param s1 * @param s2 * @return true if both calendars simultaneously operate on at least one day of the week */ public static boolean checkOverlap (Service s1, Service s2) { if (s1.calendar == null || s2.calendar == null) { return false; } // overlap exists if at least one day of week is shared by two calendars boolean overlappingDays = s1.calendar.monday == 1 && s2.calendar.monday == 1 || s1.calendar.tuesday == 1 && s2.calendar.tuesday == 1 || s1.calendar.wednesday == 1 && s2.calendar.wednesday == 1 || s1.calendar.thursday == 1 && s2.calendar.thursday == 1 || s1.calendar.friday == 1 && s2.calendar.friday == 1 || s1.calendar.saturday == 1 && s2.calendar.saturday == 1 || s1.calendar.sunday == 1 && s2.calendar.sunday == 1; return overlappingDays; } }
// first check for exceptions CalendarDate exception = calendar_dates.get(date); if (exception != null) return exception.exception_type == 1; else if (calendar == null) return false; else { int gtfsDate = date.getYear() * 10000 + date.getMonthValue() * 100 + date.getDayOfMonth(); boolean withinValidityRange = calendar.end_date >= gtfsDate && calendar.start_date <= gtfsDate; if (!withinValidityRange) return false; switch (date.getDayOfWeek()) { case MONDAY: return calendar.monday == 1; case TUESDAY: return calendar.tuesday == 1; case WEDNESDAY: return calendar.wednesday == 1; case THURSDAY: return calendar.thursday == 1; case FRIDAY: return calendar.friday == 1; case SATURDAY: return calendar.saturday == 1; case SUNDAY: return calendar.sunday == 1; default: throw new IllegalArgumentException("unknown day of week constant!"); } }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/ShapePoint.java
ShapePoint
loadOneRow
class ShapePoint extends Entity { private static final long serialVersionUID = 6751814959971086070L; public final String shape_id; public final double shape_pt_lat; public final double shape_pt_lon; public final int shape_pt_sequence; public final double shape_dist_traveled; // Similar to stoptime, we have to have a constructor, because fields are final so as to be immutable for storage in MapDB. public ShapePoint(String shape_id, double shape_pt_lat, double shape_pt_lon, int shape_pt_sequence, double shape_dist_traveled) { this.shape_id = shape_id; this.shape_pt_lat = shape_pt_lat; this.shape_pt_lon = shape_pt_lon; this.shape_pt_sequence = shape_pt_sequence; this.shape_dist_traveled = shape_dist_traveled; } public static class Loader extends Entity.Loader<ShapePoint> { public Loader(GTFSFeed feed) { super(feed, "shapes"); } @Override protected boolean isRequired() { return false; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
String shape_id = getStringField("shape_id", true); double shape_pt_lat = getDoubleField("shape_pt_lat", true, -90D, 90D); double shape_pt_lon = getDoubleField("shape_pt_lon", true, -180D, 180D); int shape_pt_sequence = getIntField("shape_pt_sequence", true, 0, Integer.MAX_VALUE); double shape_dist_traveled = getDoubleField("shape_dist_traveled", false, 0D, Double.MAX_VALUE); ShapePoint s = new ShapePoint(shape_id, shape_pt_lat, shape_pt_lon, shape_pt_sequence, shape_dist_traveled); s.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index s.feed = null; // since we're putting this into MapDB, we don't want circular serialization feed.shape_points.put(new Tuple2<String, Integer>(s.shape_id, s.shape_pt_sequence), s);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Stop.java
Stop
toString
class Stop extends Entity { private static final long serialVersionUID = 464065335273514677L; public String stop_id; public String stop_code; public String stop_name; public String stop_desc; public double stop_lat; public double stop_lon; public String zone_id; public URL stop_url; public int location_type; public String parent_station; public String stop_timezone; // TODO should be int public String wheelchair_boarding; public String feed_id; public static 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/conveyal/gtfs/model/StopTime.java
StopTime
loadOneRow
class StopTime extends Entity implements Cloneable, Serializable { private static final long serialVersionUID = -8883780047901081832L; /* StopTime cannot directly reference Trips or Stops because they would be serialized into the MapDB. */ public String trip_id; public int arrival_time = INT_MISSING; public int departure_time = INT_MISSING; public String stop_id; public int stop_sequence; public String stop_headsign; public int pickup_type; public int drop_off_type; public double shape_dist_traveled; public int timepoint = INT_MISSING; public static class Loader extends Entity.Loader<StopTime> { public Loader(GTFSFeed feed) { super(feed, "stop_times"); } @Override protected boolean isRequired() { return true; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } @Override public StopTime clone () { try { return (StopTime) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } }
StopTime st = new StopTime(); st.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index st.trip_id = getStringField("trip_id", true); // TODO: arrival_time and departure time are not required, but if one is present the other should be // also, if this is the first or last stop, they are both required st.arrival_time = getTimeField("arrival_time", false); st.departure_time = getTimeField("departure_time", false); st.stop_id = getStringField("stop_id", true); st.stop_sequence = getIntField("stop_sequence", true, 0, Integer.MAX_VALUE); st.stop_headsign = getStringField("stop_headsign", false); st.pickup_type = getIntField("pickup_type", false, 0, 3); // TODO add ranges as parameters st.drop_off_type = getIntField("drop_off_type", false, 0, 3); st.shape_dist_traveled = getDoubleField("shape_dist_traveled", false, 0D, Double.MAX_VALUE); // FIXME using both 0 and NaN for "missing", define DOUBLE_MISSING st.timepoint = getIntField("timepoint", false, 0, 1, INT_MISSING); st.feed = null; // this could circular-serialize the whole feed feed.stop_times.put(new Fun.Tuple2(st.trip_id, st.stop_sequence), st); getRefField("trip_id", true, feed.trips); getRefField("stop_id", true, feed.stops);