idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
31,400
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 ( 3 ) ; double tmpLat = fullPL . getLatitude ( wayIndex ) ; double tmpLon = fullPL . getLongitude ( wayIndex ) ; double tmpEle = fullPL . getElevation ( wayIndex ) ; if ( snappedPosition != Position . EDGE ) { snappedPoint = new GHPoint3D ( tmpLat , tmpLon , tmpEle ) ; return ; } double queryLat = getQueryPoint ( ) . lat , queryLon = getQueryPoint ( ) . lon ; double adjLat = fullPL . getLatitude ( wayIndex + 1 ) , adjLon = fullPL . getLongitude ( wayIndex + 1 ) ; if ( distCalc . validEdgeDistance ( queryLat , queryLon , tmpLat , tmpLon , adjLat , adjLon ) ) { GHPoint tmpPoint = distCalc . calcCrossingPointToEdge ( queryLat , queryLon , tmpLat , tmpLon , adjLat , adjLon ) ; double adjEle = fullPL . getElevation ( wayIndex + 1 ) ; snappedPoint = new GHPoint3D ( tmpPoint . lat , tmpPoint . lon , ( tmpEle + adjEle ) / 2 ) ; } else snappedPoint = new GHPoint3D ( tmpLat , tmpLon , tmpEle ) ; }
Calculates the closet point on the edge from the query point .
31,401
public QueryGraph lookup ( QueryResult fromRes , QueryResult toRes ) { List < QueryResult > results = new ArrayList < > ( 2 ) ; results . add ( fromRes ) ; results . add ( toRes ) ; lookup ( results ) ; return this ; }
Convenient method to initialize this QueryGraph with the two specified query results .
31,402
private void addVirtualEdges ( IntObjectMap < VirtualEdgeIterator > node2EdgeMap , EdgeFilter filter , boolean base , int node , int virtNode ) { VirtualEdgeIterator existingIter = node2EdgeMap . get ( node ) ; if ( existingIter == null ) { existingIter = new VirtualEdgeIterator ( 10 ) ; node2EdgeMap . put ( node , existingIter ) ; } EdgeIteratorState edge = base ? virtualEdges . get ( virtNode * 4 + VE_BASE ) : virtualEdges . get ( virtNode * 4 + VE_ADJ_REV ) ; if ( filter . accept ( edge ) ) existingIter . add ( edge ) ; }
Creates a fake edge iterator pointing to multiple edge states .
31,403
public final double similarity ( final String s1 , final String s2 ) { int [ ] mtp = matches ( s1 , s2 ) ; float m = mtp [ 0 ] ; if ( m == 0 ) { return 0f ; } double j = ( ( m / s1 . length ( ) + m / s2 . length ( ) + ( m - mtp [ 1 ] ) / m ) ) / THREE ; double jw = j ; if ( j > getThreshold ( ) ) { jw = j + Math . min ( JW_COEF , 1.0 / mtp [ THREE ] ) * mtp [ 2 ] * ( 1 - j ) ; } return jw ; }
Compute JW similarity .
31,404
public String calcDirection ( Instruction nextI ) { double azimuth = calcAzimuth ( nextI ) ; if ( Double . isNaN ( azimuth ) ) return "" ; return AC . azimuth2compassPoint ( azimuth ) ; }
Return the direction like NE based on the first tracksegment of the instruction . If Instruction does not contain enough coordinate points an empty string will be returned .
31,405
public double calcAzimuth ( Instruction nextI ) { double nextLat ; double nextLon ; if ( points . getSize ( ) >= 2 ) { nextLat = points . getLatitude ( 1 ) ; nextLon = points . getLongitude ( 1 ) ; } else if ( nextI != null && points . getSize ( ) == 1 ) { nextLat = nextI . points . getLatitude ( 0 ) ; nextLon = nextI . points . getLongitude ( 0 ) ; } else { return Double . NaN ; } double lat = points . getLatitude ( 0 ) ; double lon = points . getLongitude ( 0 ) ; return AC . calcAzimuth ( lat , lon , nextLat , nextLon ) ; }
Return the azimuth in degree based on the first tracksegment of this instruction . If this instruction contains less than 2 points then NaN will be returned or the specified instruction will be used if that is the finish instruction .
31,406
public Path extract ( ) { if ( sptEntry == null || edgeTo == null ) return this ; if ( sptEntry . adjNode != edgeTo . adjNode ) throw new IllegalStateException ( "Locations of the 'to'- and 'from'-Edge have to be the same. " + toString ( ) + ", fromEntry:" + sptEntry + ", toEntry:" + edgeTo ) ; extractSW . start ( ) ; if ( switchFromAndToSPTEntry ) { SPTEntry ee = sptEntry ; sptEntry = edgeTo ; edgeTo = ee ; } SPTEntry currEdge = sptEntry ; boolean nextEdgeValid = EdgeIterator . Edge . isValid ( currEdge . edge ) ; int nextEdge ; while ( nextEdgeValid ) { nextEdgeValid = EdgeIterator . Edge . isValid ( currEdge . parent . edge ) ; nextEdge = nextEdgeValid ? currEdge . parent . edge : EdgeIterator . NO_EDGE ; processEdge ( currEdge . edge , currEdge . adjNode , nextEdge ) ; currEdge = currEdge . parent ; } setFromNode ( currEdge . adjNode ) ; reverseOrder ( ) ; currEdge = edgeTo ; int prevEdge = EdgeIterator . Edge . isValid ( sptEntry . edge ) ? sptEntry . edge : EdgeIterator . NO_EDGE ; int tmpEdge = currEdge . edge ; while ( EdgeIterator . Edge . isValid ( tmpEdge ) ) { currEdge = currEdge . parent ; processEdge ( tmpEdge , currEdge . adjNode , prevEdge ) ; prevEdge = tmpEdge ; tmpEdge = currEdge . edge ; } setEndNode ( currEdge . adjNode ) ; extractSW . stop ( ) ; return setFound ( true ) ; }
Extracts path from two shortest - path - tree
31,407
public void loadFromFile ( ZipFile zip , String fid ) throws IOException { if ( this . loaded ) throw new UnsupportedOperationException ( "Attempt to load GTFS into existing database" ) ; checksum = zip . stream ( ) . mapToLong ( ZipEntry :: getCrc ) . reduce ( ( l1 , l2 ) -> l1 ^ l2 ) . getAsLong ( ) ; db . getAtomicLong ( "checksum" ) . set ( checksum ) ; new FeedInfo . Loader ( this ) . loadTable ( zip ) ; if ( fid != null ) { feedId = fid ; LOG . info ( "Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}." , feedId ) ; } else if ( feedId == null || feedId . isEmpty ( ) ) { feedId = new File ( zip . getName ( ) ) . getName ( ) . replaceAll ( "\\.zip$" , "" ) ; LOG . info ( "Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}." , feedId ) ; } else { LOG . info ( "Feed ID is '{}'." , feedId ) ; } db . getAtomicString ( "feed_id" ) . set ( feedId ) ; new Agency . Loader ( this ) . loadTable ( zip ) ; if ( agency . isEmpty ( ) ) { errors . add ( new GeneralError ( "agency" , 0 , "agency_id" , "Need at least one agency." ) ) ; } Map < String , Service > serviceTable = new HashMap < > ( ) ; new Calendar . Loader ( this , serviceTable ) . loadTable ( zip ) ; new CalendarDate . Loader ( this , serviceTable ) . loadTable ( zip ) ; this . services . putAll ( serviceTable ) ; serviceTable = null ; Map < String , Fare > fares = new HashMap < > ( ) ; new FareAttribute . Loader ( this , fares ) . loadTable ( zip ) ; new FareRule . Loader ( this , fares ) . loadTable ( zip ) ; this . fares . putAll ( fares ) ; fares = null ; new Route . Loader ( this ) . loadTable ( zip ) ; new ShapePoint . Loader ( this ) . loadTable ( zip ) ; new Stop . Loader ( this ) . loadTable ( zip ) ; new Transfer . Loader ( this ) . loadTable ( zip ) ; new Trip . Loader ( this ) . loadTable ( zip ) ; new Frequency . Loader ( this ) . loadTable ( zip ) ; new StopTime . Loader ( this ) . loadTable ( zip ) ; loaded = true ; }
The order in which we load the tables is important for two reasons . 1 . We must load feed_info first so we know the feed ID before loading any other entities . This could be relaxed by having entities point to the feed object rather than its ID String . 2 . Referenced entities must be loaded before any entities that reference them . This is because we check referential integrity while the files are being loaded . This is done on the fly during loading because it allows us to associate a line number with errors in objects that don t have any other clear identifier .
31,408
public Iterable < StopTime > getOrderedStopTimesForTrip ( String trip_id ) { Map < Fun . Tuple2 , StopTime > tripStopTimes = stop_times . subMap ( Fun . t2 ( trip_id , null ) , Fun . t2 ( trip_id , Fun . HI ) ) ; return tripStopTimes . values ( ) ; }
For the given trip ID fetch all the stop times in order of increasing stop_sequence . This is an efficient iteration over a tree map .
31,409
public Shape getShape ( String shape_id ) { Shape shape = new Shape ( this , shape_id ) ; return shape . shape_dist_traveled . length > 0 ? shape : null ; }
Get the shape for the given shape ID
31,410
public Iterable < StopTime > getInterpolatedStopTimesForTrip ( String trip_id ) throws FirstAndLastStopsDoNotHaveTimes { StopTime [ ] stopTimes = StreamSupport . stream ( getOrderedStopTimesForTrip ( trip_id ) . spliterator ( ) , false ) . map ( st -> st . clone ( ) ) . toArray ( i -> new StopTime [ i ] ) ; if ( stopTimes . length == 0 ) return Collections . emptyList ( ) ; for ( StopTime st : stopTimes ) { if ( st . arrival_time != Entity . INT_MISSING && st . departure_time == Entity . INT_MISSING ) { st . departure_time = st . arrival_time ; } if ( st . arrival_time == Entity . INT_MISSING && st . departure_time != Entity . INT_MISSING ) { st . arrival_time = st . departure_time ; } } if ( stopTimes [ 0 ] . departure_time == Entity . INT_MISSING || stopTimes [ stopTimes . length - 1 ] . departure_time == Entity . INT_MISSING ) { throw new FirstAndLastStopsDoNotHaveTimes ( ) ; } int startOfInterpolatedBlock = - 1 ; for ( int stopTime = 0 ; stopTime < stopTimes . length ; stopTime ++ ) { if ( stopTimes [ stopTime ] . departure_time == Entity . INT_MISSING && startOfInterpolatedBlock == - 1 ) { startOfInterpolatedBlock = stopTime ; } else if ( stopTimes [ stopTime ] . departure_time != Entity . INT_MISSING && startOfInterpolatedBlock != - 1 ) { throw new RuntimeException ( "Missing stop times not supported." ) ; } } return Arrays . asList ( stopTimes ) ; }
For the given trip ID fetch all the stop times in order and interpolate stop - to - stop travel times .
31,411
public long applyChanges ( EncodingManager em , Collection < JsonFeature > features ) { if ( em == null ) throw new NullPointerException ( "EncodingManager cannot be null to change existing graph" ) ; long updates = 0 ; for ( JsonFeature jsonFeature : features ) { if ( ! jsonFeature . hasProperties ( ) ) throw new IllegalArgumentException ( "One feature has no properties, please specify properties e.g. speed or access" ) ; List < String > encodersAsStr = ( List ) jsonFeature . getProperty ( "vehicles" ) ; if ( encodersAsStr == null ) { for ( FlagEncoder encoder : em . fetchEdgeEncoders ( ) ) { updates += applyChange ( jsonFeature , encoder ) ; } } else { for ( String encoderStr : encodersAsStr ) { updates += applyChange ( jsonFeature , em . getEncoder ( encoderStr ) ) ; } } } return updates ; }
This method applies changes to the graph specified by the json features .
31,412
public static BBox createInverse ( boolean elevation ) { if ( elevation ) { return new BBox ( Double . MAX_VALUE , - Double . MAX_VALUE , Double . MAX_VALUE , - Double . MAX_VALUE , Double . MAX_VALUE , - Double . MAX_VALUE , true ) ; } else { return new BBox ( Double . MAX_VALUE , - Double . MAX_VALUE , Double . MAX_VALUE , - Double . MAX_VALUE , Double . NaN , Double . NaN , false ) ; } }
Prefills BBox with minimum values so that it can increase .
31,413
public BBox calculateIntersection ( BBox bBox ) { if ( ! this . intersects ( bBox ) ) return null ; double minLon = Math . max ( this . minLon , bBox . minLon ) ; double maxLon = Math . min ( this . maxLon , bBox . maxLon ) ; double minLat = Math . max ( this . minLat , bBox . minLat ) ; double maxLat = Math . min ( this . maxLat , bBox . maxLat ) ; return new BBox ( minLon , maxLon , minLat , maxLat ) ; }
Calculates the intersecting BBox between this and the specified BBox
31,414
public static BBox parseTwoPoints ( String objectAsString ) { String [ ] splittedObject = objectAsString . split ( "," ) ; if ( splittedObject . length != 4 ) throw new IllegalArgumentException ( "BBox should have 4 parts but was " + objectAsString ) ; double minLat = Double . parseDouble ( splittedObject [ 0 ] ) ; double minLon = Double . parseDouble ( splittedObject [ 1 ] ) ; double maxLat = Double . parseDouble ( splittedObject [ 2 ] ) ; double maxLon = Double . parseDouble ( splittedObject [ 3 ] ) ; if ( minLat > maxLat ) { double tmp = minLat ; minLat = maxLat ; maxLat = tmp ; } if ( minLon > maxLon ) { double tmp = minLon ; minLon = maxLon ; maxLon = tmp ; } return new BBox ( minLon , maxLon , minLat , maxLat ) ; }
This method creates a BBox out of a string in format lat1 lon1 lat2 lon2
31,415
public static BBox parseBBoxString ( String objectAsString ) { String [ ] splittedObject = objectAsString . split ( "," ) ; if ( splittedObject . length != 4 ) throw new IllegalArgumentException ( "BBox should have 4 parts but was " + objectAsString ) ; double minLon = Double . parseDouble ( splittedObject [ 0 ] ) ; double maxLon = Double . parseDouble ( splittedObject [ 1 ] ) ; double minLat = Double . parseDouble ( splittedObject [ 2 ] ) ; double maxLat = Double . parseDouble ( splittedObject [ 3 ] ) ; return new BBox ( minLon , maxLon , minLat , maxLat ) ; }
This method creates a BBox out of a string in format lon1 lon2 lat1 lat2
31,416
private int addShortcuts ( Collection < Shortcut > shortcuts ) { int tmpNewShortcuts = 0 ; NEXT_SC : for ( Shortcut sc : shortcuts ) { boolean updatedInGraph = false ; CHEdgeIterator iter = outEdgeExplorer . setBaseNode ( sc . from ) ; while ( iter . next ( ) ) { if ( iter . isShortcut ( ) && iter . getAdjNode ( ) == sc . to ) { int status = iter . getMergeStatus ( sc . flags ) ; if ( status == 0 ) continue ; if ( sc . weight >= prepareWeighting . calcWeight ( iter , false , EdgeIterator . NO_EDGE ) ) { if ( status == 2 ) break ; continue NEXT_SC ; } if ( iter . getEdge ( ) == sc . skippedEdge1 || iter . getEdge ( ) == sc . skippedEdge2 ) { throw new IllegalStateException ( "Shortcut cannot update itself! " + iter . getEdge ( ) + ", skipEdge1:" + sc . skippedEdge1 + ", skipEdge2:" + sc . skippedEdge2 + ", edge " + iter + ":" + getCoords ( iter , prepareGraph ) + ", sc:" + sc + ", skippedEdge1: " + getCoords ( prepareGraph . getEdgeIteratorState ( sc . skippedEdge1 , sc . from ) , prepareGraph ) + ", skippedEdge2: " + getCoords ( prepareGraph . getEdgeIteratorState ( sc . skippedEdge2 , sc . to ) , prepareGraph ) + ", neighbors:" + GHUtility . getNeighbors ( iter ) ) ; } iter . setFlagsAndWeight ( sc . flags , sc . weight ) ; iter . setDistance ( sc . dist ) ; iter . setSkippedEdges ( sc . skippedEdge1 , sc . skippedEdge2 ) ; setOrigEdgeCount ( iter . getEdge ( ) , sc . originalEdges ) ; updatedInGraph = true ; break ; } } if ( ! updatedInGraph ) { int scId = prepareGraph . shortcut ( sc . from , sc . to , sc . flags , sc . weight , sc . dist , sc . skippedEdge1 , sc . skippedEdge2 ) ; setOrigEdgeCount ( scId , sc . originalEdges ) ; tmpNewShortcuts ++ ; } } return tmpNewShortcuts ; }
Adds the given shortcuts to the graph .
31,417
private static final String human ( long n ) { if ( n >= 1000000 ) return String . format ( Locale . getDefault ( ) , "%.1fM" , n / 1000000.0 ) ; if ( n >= 1000 ) return String . format ( Locale . getDefault ( ) , "%.1fk" , n / 1000.0 ) ; else return String . format ( Locale . getDefault ( ) , "%d" , n ) ; }
shared code between reading and writing
31,418
private void writeSummary ( String summaryLocation , String propLocation ) { logger . info ( "writing summary to " + summaryLocation ) ; String [ ] properties = { "graph.nodes" , "graph.edges" , "graph.import_time" , CH . PREPARE + "time" , CH . PREPARE + "node.shortcuts" , CH . PREPARE + "edge.shortcuts" , Landmark . PREPARE + "time" , "routing.distance_mean" , "routing.mean" , "routing.visited_nodes_mean" , "routingCH.distance_mean" , "routingCH.mean" , "routingCH.visited_nodes_mean" , "routingCH_no_instr.mean" , "routingCH_edge.distance_mean" , "routingCH_edge.mean" , "routingCH_edge.visited_nodes_mean" , "routingCH_edge_no_instr.mean" , "routingLM8.distance_mean" , "routingLM8.mean" , "routingLM8.visited_nodes_mean" , "measurement.seed" , "measurement.gitinfo" , "measurement.timestamp" } ; File f = new File ( summaryLocation ) ; boolean writeHeader = ! f . exists ( ) ; try ( FileWriter writer = new FileWriter ( f , true ) ) { if ( writeHeader ) writer . write ( getSummaryHeader ( properties ) ) ; writer . write ( getSummaryLogLine ( properties , propLocation ) ) ; } catch ( IOException e ) { logger . error ( "Could not write summary to file '{}'" , summaryLocation , e ) ; } }
Writes a selection of measurement results to a single line in a file . Each run of the measurement class will append a new line .
31,419
public static void warmUp ( GraphHopper graphHopper , int iterations ) { GraphHopperStorage ghStorage = graphHopper . getGraphHopperStorage ( ) ; if ( ghStorage == null ) throw new IllegalArgumentException ( "The storage of GraphHopper must not be empty" ) ; try { if ( ghStorage . isCHPossible ( ) ) warmUpCHSubNetwork ( graphHopper , iterations ) ; else warmUpNonCHSubNetwork ( graphHopper , iterations ) ; } catch ( Exception ex ) { LOGGER . warn ( "Problem while sending warm up queries" , ex ) ; } }
Do the warm up for the specified GraphHopper instance .
31,420
public static EncodingManager create ( FlagEncoderFactory factory , String ghLoc ) { Directory dir = new RAMDirectory ( ghLoc , true ) ; StorableProperties properties = new StorableProperties ( dir ) ; if ( ! properties . loadExisting ( ) ) throw new IllegalStateException ( "Cannot load properties to fetch EncodingManager configuration at: " + dir . getLocation ( ) ) ; properties . checkVersions ( false ) ; String acceptStr = properties . get ( "graph.flag_encoders" ) ; if ( acceptStr . isEmpty ( ) ) throw new IllegalStateException ( "EncodingManager was not configured. And no one was found in the graph: " + dir . getLocation ( ) ) ; int bytesForFlags = 4 ; try { bytesForFlags = Integer . parseInt ( properties . get ( "graph.bytes_for_flags" ) ) ; } catch ( NumberFormatException ex ) { } return createBuilder ( factory , acceptStr , bytesForFlags ) . build ( ) ; }
Create the EncodingManager from the provided GraphHopper location . Throws an IllegalStateException if it fails . Used if no EncodingManager specified on load .
31,421
public boolean acceptWay ( ReaderWay way , AcceptWay acceptWay ) { if ( ! acceptWay . isEmpty ( ) ) throw new IllegalArgumentException ( "AcceptWay must be empty" ) ; for ( AbstractFlagEncoder encoder : edgeEncoders ) { acceptWay . put ( encoder . toString ( ) , encoder . getAccess ( way ) ) ; } return acceptWay . hasAccepted ( ) ; }
Determine whether a way is routable for one of the added encoders .
31,422
public IntsRef handleWayTags ( ReaderWay way , AcceptWay acceptWay , long relationFlags ) { IntsRef edgeFlags = createEdgeFlags ( ) ; Access access = acceptWay . getAccess ( ) ; for ( TagParser parser : sharedEncodedValueMap . values ( ) ) { parser . handleWayTags ( edgeFlags , way , access , relationFlags ) ; } for ( AbstractFlagEncoder encoder : edgeEncoders ) { encoder . handleWayTags ( edgeFlags , way , acceptWay . get ( encoder . toString ( ) ) , relationFlags & encoder . getRelBitMask ( ) ) ; } return edgeFlags ; }
Processes way properties of different kind to determine speed and direction . Properties are directly encoded in 8 bytes .
31,423
public static boolean isFileMapped ( ByteBuffer bb ) { if ( bb instanceof MappedByteBuffer ) { try { ( ( MappedByteBuffer ) bb ) . isLoaded ( ) ; return true ; } catch ( UnsupportedOperationException ex ) { } } return false ; }
Determines if the specified ByteBuffer is one which maps to a file!
31,424
public static final double keepIn ( double value , double min , double max ) { return Math . max ( min , Math . min ( value , max ) ) ; }
This methods returns the value or min if too small or max if too big .
31,425
public static double round ( double value , int exponent ) { double factor = Math . pow ( 10 , exponent ) ; return Math . round ( value * factor ) / factor ; }
Round the value to the specified exponent
31,426
public static DateFormat createFormatter ( String str ) { DateFormat df = new SimpleDateFormat ( str , Locale . UK ) ; df . setTimeZone ( UTC ) ; return df ; }
Creates a SimpleDateFormat with the UK locale .
31,427
public boolean hasErrors ( ) { if ( ! errors . isEmpty ( ) ) return true ; for ( PathWrapper ar : pathWrappers ) { if ( ar . hasErrors ( ) ) return true ; } return false ; }
This method returns true if one of the paths has an error or if the response itself is erroneous .
31,428
public List < Throwable > getErrors ( ) { List < Throwable > list = new ArrayList < > ( ) ; list . addAll ( errors ) ; for ( PathWrapper ar : pathWrappers ) { list . addAll ( ar . getErrors ( ) ) ; } return list ; }
This method returns all the explicitly added errors and the errors of all paths .
31,429
public TranslationMap doImport ( File folder ) { try { for ( String locale : LOCALES ) { TranslationHashMap trMap = new TranslationHashMap ( getLocale ( locale ) ) ; trMap . doImport ( new FileInputStream ( new File ( folder , locale + ".txt" ) ) ) ; add ( trMap ) ; } postImportHook ( ) ; return this ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } }
This loads the translation files from the specified folder .
31,430
public TranslationMap doImport ( ) { try { for ( String locale : LOCALES ) { TranslationHashMap trMap = new TranslationHashMap ( getLocale ( locale ) ) ; trMap . doImport ( TranslationMap . class . getResourceAsStream ( locale + ".txt" ) ) ; add ( trMap ) ; } postImportHook ( ) ; return this ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } }
This loads the translation files from classpath .
31,431
public Translation getWithFallBack ( Locale locale ) { Translation tr = get ( locale . toString ( ) ) ; if ( tr == null ) { tr = get ( locale . getLanguage ( ) ) ; if ( tr == null ) tr = get ( "en" ) ; } return tr ; }
Returns the Translation object for the specified locale and falls back to English if the locale was not found .
31,432
public Translation get ( String locale ) { locale = locale . replace ( "-" , "_" ) ; Translation tr = translations . get ( locale ) ; if ( locale . contains ( "_" ) && tr == null ) tr = translations . get ( locale . substring ( 0 , 2 ) ) ; return tr ; }
Returns the Translation object for the specified locale and returns null if not found .
31,433
private void postImportHook ( ) { Map < String , String > enMap = get ( "en" ) . asMap ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( Translation tr : translations . values ( ) ) { Map < String , String > trMap = tr . asMap ( ) ; for ( Entry < String , String > enEntry : enMap . entrySet ( ) ) { String value = trMap . get ( enEntry . getKey ( ) ) ; if ( isEmpty ( value ) ) { trMap . put ( enEntry . getKey ( ) , enEntry . getValue ( ) ) ; continue ; } int expectedCount = countOccurence ( enEntry . getValue ( ) , "\\%" ) ; if ( expectedCount != countOccurence ( value , "\\%" ) ) { sb . append ( tr . getLocale ( ) ) . append ( " - error in " ) . append ( enEntry . getKey ( ) ) . append ( "->" ) . append ( value ) . append ( "\n" ) ; } else { Object [ ] strs = new String [ expectedCount ] ; Arrays . fill ( strs , "tmp" ) ; try { String . format ( Locale . ROOT , value , strs ) ; } catch ( Exception ex ) { sb . append ( tr . getLocale ( ) ) . append ( " - error " ) . append ( ex . getMessage ( ) ) . append ( "in " ) . append ( enEntry . getKey ( ) ) . append ( "->" ) . append ( value ) . append ( "\n" ) ; } } } } if ( sb . length ( ) > 0 ) { System . out . println ( sb ) ; throw new IllegalStateException ( sb . toString ( ) ) ; } }
This method does some checks and fills missing translation from en
31,434
public static DAType getPreferredInt ( DAType type ) { if ( type . isInMemory ( ) ) return type . isStoring ( ) ? RAM_INT_STORE : RAM_INT ; return type ; }
This method returns RAM_INT if the specified type is in - memory .
31,435
private int distToInt ( double distance ) { if ( distance < 0 ) throw new IllegalArgumentException ( "Distance cannot be negative: " + distance ) ; if ( distance > MAX_DIST ) { distance = MAX_DIST ; } int integ = ( int ) Math . round ( distance * INT_DIST_FACTOR ) ; assert integ >= 0 : "distance out of range" ; return integ ; }
Translates double distance to integer in order to save it in a DataAccess object
31,436
final int internalEdgeAdd ( int newEdgeId , int nodeA , int nodeB ) { writeEdge ( newEdgeId , nodeA , nodeB , EdgeIterator . NO_EDGE , EdgeIterator . NO_EDGE ) ; long edgePointer = toPointer ( newEdgeId ) ; int edge = getEdgeRef ( nodeA ) ; if ( edge > EdgeIterator . NO_EDGE ) edges . setInt ( E_LINKA + edgePointer , edge ) ; setEdgeRef ( nodeA , newEdgeId ) ; if ( nodeA != nodeB ) { edge = getEdgeRef ( nodeB ) ; if ( edge > EdgeIterator . NO_EDGE ) edges . setInt ( E_LINKB + edgePointer , edge ) ; setEdgeRef ( nodeB , newEdgeId ) ; } return newEdgeId ; }
Writes a new edge to the array of edges and adds it to the linked list of edges at nodeA and nodeB
31,437
final long writeEdge ( int edgeId , int nodeA , int nodeB , int nextEdgeA , int nextEdgeB ) { if ( edgeId < 0 || edgeId == EdgeIterator . NO_EDGE ) throw new IllegalStateException ( "Cannot write edge with illegal ID:" + edgeId + "; nodeA:" + nodeA + ", nodeB:" + nodeB ) ; long edgePointer = toPointer ( edgeId ) ; edges . setInt ( edgePointer + E_NODEA , nodeA ) ; edges . setInt ( edgePointer + E_NODEB , nodeB ) ; edges . setInt ( edgePointer + E_LINKA , nextEdgeA ) ; edges . setInt ( edgePointer + E_LINKB , nextEdgeB ) ; return edgePointer ; }
Writes plain edge information to the edges index
31,438
final long internalEdgeDisconnect ( int edgeToRemove , long edgeToUpdatePointer , int baseNode ) { long edgeToRemovePointer = toPointer ( edgeToRemove ) ; int nextEdgeId = getNodeA ( edgeToRemovePointer ) == baseNode ? getLinkA ( edgeToRemovePointer ) : getLinkB ( edgeToRemovePointer ) ; if ( edgeToUpdatePointer < 0 ) { setEdgeRef ( baseNode , nextEdgeId ) ; } else { long link = getNodeA ( edgeToUpdatePointer ) == baseNode ? edgeToUpdatePointer + E_LINKA : edgeToUpdatePointer + E_LINKB ; edges . setInt ( link , nextEdgeId ) ; } return edgeToRemovePointer ; }
This method disconnects the specified edge from the list of edges of the specified node . It does not release the freed space to be reused .
31,439
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 ; }
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 .
31,440
public final long fromBitString2Long ( String str ) { if ( str . length ( ) > 64 ) throw new UnsupportedOperationException ( "Strings needs to fit into a 'long' but length was " + str . length ( ) ) ; long res = 0 ; int strLen = str . length ( ) ; for ( int charIndex = 0 ; charIndex < strLen ; charIndex ++ ) { res <<= 1 ; if ( str . charAt ( charIndex ) != '0' ) res |= 1 ; } res <<= ( 64 - strLen ) ; return res ; }
The only purpose of this method is to test reverse . toBitString is the reverse and both are independent of the endianness .
31,441
protected double slightlyModifyDistance ( double distance ) { double distanceModification = random . nextDouble ( ) * .1 * distance ; if ( random . nextBoolean ( ) ) distanceModification = - distanceModification ; return distance + distanceModification ; }
Modifies the Distance up to + - 10%
31,442
public GraphHopper setGraphHopperLocation ( String ghLocation ) { ensureNotLoaded ( ) ; if ( ghLocation == null ) throw new IllegalArgumentException ( "graphhopper location cannot be null" ) ; this . ghLocation = ghLocation ; return this ; }
Sets the graphhopper folder .
31,443
private GraphHopper process ( String graphHopperLocation ) { setGraphHopperLocation ( graphHopperLocation ) ; GHLock lock = null ; try { if ( ghStorage . getDirectory ( ) . getDefaultType ( ) . isStoring ( ) ) { lockFactory . setLockDir ( new File ( graphHopperLocation ) ) ; lock = lockFactory . create ( fileLockName , true ) ; if ( ! lock . tryLock ( ) ) throw new RuntimeException ( "To avoid multiple writers we need to obtain a write lock but it failed. In " + graphHopperLocation , lock . getObtainFailedReason ( ) ) ; } try { DataReader reader = importData ( ) ; DateFormat f = createFormatter ( ) ; ghStorage . getProperties ( ) . put ( "datareader.import.date" , f . format ( new Date ( ) ) ) ; if ( reader . getDataDate ( ) != null ) ghStorage . getProperties ( ) . put ( "datareader.data.date" , f . format ( reader . getDataDate ( ) ) ) ; } catch ( IOException ex ) { throw new RuntimeException ( "Cannot read file " + getDataReaderFile ( ) , ex ) ; } cleanUp ( ) ; postProcessing ( ) ; flush ( ) ; } finally { if ( lock != null ) lock . release ( ) ; } return this ; }
Creates the graph from OSM data .
31,444
public boolean load ( String graphHopperFolder ) { if ( isEmpty ( graphHopperFolder ) ) throw new IllegalStateException ( "GraphHopperLocation is not specified. Call setGraphHopperLocation or init before" ) ; if ( fullyLoaded ) throw new IllegalStateException ( "graph is already successfully loaded" ) ; File tmpFileOrFolder = new File ( graphHopperFolder ) ; if ( ! tmpFileOrFolder . isDirectory ( ) && tmpFileOrFolder . exists ( ) ) { throw new IllegalArgumentException ( "GraphHopperLocation cannot be an existing file. Has to be either non-existing or a folder." ) ; } else { File compressed = new File ( graphHopperFolder + ".ghz" ) ; if ( compressed . exists ( ) && ! compressed . isDirectory ( ) ) { try { new Unzipper ( ) . unzip ( compressed . getAbsolutePath ( ) , graphHopperFolder , removeZipped ) ; } catch ( IOException ex ) { throw new RuntimeException ( "Couldn't extract file " + compressed . getAbsolutePath ( ) + " to " + graphHopperFolder , ex ) ; } } } setGraphHopperLocation ( graphHopperFolder ) ; if ( encodingManager == null ) setEncodingManager ( EncodingManager . create ( flagEncoderFactory , ghLocation ) ) ; if ( ! allowWrites && dataAccessType . isMMap ( ) ) dataAccessType = DAType . MMAP_RO ; GHDirectory dir = new GHDirectory ( ghLocation , dataAccessType ) ; GraphExtension ext = encodingManager . needsTurnCostsSupport ( ) ? new TurnCostExtension ( ) : new GraphExtension . NoOpExtension ( ) ; if ( lmFactoryDecorator . isEnabled ( ) ) initLMAlgoFactoryDecorator ( ) ; if ( chFactoryDecorator . isEnabled ( ) ) { initCHAlgoFactoryDecorator ( ) ; ghStorage = new GraphHopperStorage ( chFactoryDecorator . getNodeBasedWeightings ( ) , chFactoryDecorator . getEdgeBasedWeightings ( ) , dir , encodingManager , hasElevation ( ) , ext ) ; } else { ghStorage = new GraphHopperStorage ( dir , encodingManager , hasElevation ( ) , ext ) ; } ghStorage . setSegmentSize ( defaultSegmentSize ) ; if ( ! new File ( graphHopperFolder ) . exists ( ) ) return false ; GHLock lock = null ; try { if ( ghStorage . getDirectory ( ) . getDefaultType ( ) . isStoring ( ) && isAllowWrites ( ) ) { lockFactory . setLockDir ( new File ( ghLocation ) ) ; lock = lockFactory . create ( fileLockName , false ) ; if ( ! lock . tryLock ( ) ) throw new RuntimeException ( "To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation , lock . getObtainFailedReason ( ) ) ; } if ( ! ghStorage . loadExisting ( ) ) return false ; postProcessing ( ) ; fullyLoaded = true ; return true ; } finally { if ( lock != null ) lock . release ( ) ; } }
Opens existing graph folder .
31,445
public void postProcessing ( ) { if ( sortGraph ) { if ( ghStorage . isCHPossible ( ) && isCHPrepared ( ) ) throw new IllegalArgumentException ( "Sorting a prepared CHGraph is not possible yet. See #12" ) ; GraphHopperStorage newGraph = GHUtility . newStorage ( ghStorage ) ; GHUtility . sortDFS ( ghStorage , newGraph ) ; logger . info ( "graph sorted (" + getMemInfo ( ) + ")" ) ; ghStorage = newGraph ; } if ( hasElevation ( ) ) { interpolateBridgesAndOrTunnels ( ) ; } initLocationIndex ( ) ; if ( chFactoryDecorator . isEnabled ( ) ) chFactoryDecorator . createPreparations ( ghStorage ) ; if ( ! isCHPrepared ( ) ) prepareCH ( ) ; if ( lmFactoryDecorator . isEnabled ( ) ) lmFactoryDecorator . createPreparations ( ghStorage , locationIndex ) ; loadOrPrepareLM ( ) ; }
Does the preparation and creates the location index
31,446
public Weighting createWeighting ( HintsMap hintsMap , FlagEncoder encoder , Graph graph ) { String weightingStr = toLowerCase ( hintsMap . getWeighting ( ) ) ; Weighting weighting = null ; if ( encoder . supports ( GenericWeighting . class ) ) { weighting = new GenericWeighting ( ( DataFlagEncoder ) encoder , hintsMap ) ; } else if ( "shortest" . equalsIgnoreCase ( weightingStr ) ) { weighting = new ShortestWeighting ( encoder ) ; } else if ( "fastest" . equalsIgnoreCase ( weightingStr ) || weightingStr . isEmpty ( ) ) { if ( encoder . supports ( PriorityWeighting . class ) ) weighting = new PriorityWeighting ( encoder , hintsMap ) ; else weighting = new FastestWeighting ( encoder , hintsMap ) ; } else if ( "curvature" . equalsIgnoreCase ( weightingStr ) ) { if ( encoder . supports ( CurvatureWeighting . class ) ) weighting = new CurvatureWeighting ( encoder , hintsMap ) ; } else if ( "short_fastest" . equalsIgnoreCase ( weightingStr ) ) { weighting = new ShortFastestWeighting ( encoder , hintsMap ) ; } if ( weighting == null ) throw new IllegalArgumentException ( "weighting " + weightingStr + " not supported" ) ; if ( hintsMap . has ( Routing . BLOCK_AREA ) ) { String blockAreaStr = hintsMap . get ( Parameters . Routing . BLOCK_AREA , "" ) ; GraphEdgeIdFinder . BlockArea blockArea = new GraphEdgeIdFinder ( graph , locationIndex ) . parseBlockArea ( blockAreaStr , DefaultEdgeFilter . allEdges ( encoder ) , hintsMap . getDouble ( "block_area.edge_id_max_area" , 1000 * 1000 ) ) ; return new BlockAreaWeighting ( weighting , blockArea ) ; } return weighting ; }
Based on the hintsMap and the specified encoder a Weighting instance can be created . Note that all URL parameters are available in the hintsMap as String if you use the web module .
31,447
public Weighting createTurnWeighting ( Graph graph , Weighting weighting , TraversalMode tMode ) { FlagEncoder encoder = weighting . getFlagEncoder ( ) ; if ( encoder . supports ( TurnWeighting . class ) && ! tMode . equals ( TraversalMode . NODE_BASED ) ) return new TurnWeighting ( weighting , ( TurnCostExtension ) graph . getExtension ( ) ) ; return weighting ; }
Potentially wraps the specified weighting into a TurnWeighting instance .
31,448
protected void cleanUp ( ) { int prevNodeCount = ghStorage . getNodes ( ) ; PrepareRoutingSubnetworks preparation = new PrepareRoutingSubnetworks ( ghStorage , encodingManager . fetchEdgeEncoders ( ) ) ; preparation . setMinNetworkSize ( minNetworkSize ) ; preparation . setMinOneWayNetworkSize ( minOneWayNetworkSize ) ; preparation . doWork ( ) ; int currNodeCount = ghStorage . getNodes ( ) ; logger . info ( "edges: " + Helper . nf ( ghStorage . getAllEdges ( ) . length ( ) ) + ", nodes " + Helper . nf ( currNodeCount ) + ", there were " + Helper . nf ( preparation . getMaxSubnetworks ( ) ) + " subnetworks. removed them => " + Helper . nf ( prevNodeCount - currNodeCount ) + " less nodes" ) ; }
Internal method to clean up the graph .
31,449
public void clean ( ) { if ( getGraphHopperLocation ( ) . isEmpty ( ) ) throw new IllegalStateException ( "Cannot clean GraphHopper without specified graphHopperLocation" ) ; File folder = new File ( getGraphHopperLocation ( ) ) ; removeDir ( folder ) ; }
Removes the on - disc routing files . Call only after calling close or before importOrLoad or load
31,450
public LandmarkStorage setLandmarkSuggestions ( List < LandmarkSuggestion > landmarkSuggestions ) { if ( landmarkSuggestions == null ) throw new IllegalArgumentException ( "landmark suggestions cannot be null" ) ; this . landmarkSuggestions = landmarkSuggestions ; return this ; }
This method forces the landmark preparation to skip the landmark search and uses the specified landmark list instead . Useful for manual tuning of larger areas to safe import time or improve quality .
31,451
protected IntHashSet findBorderEdgeIds ( SpatialRuleLookup ruleLookup ) { AllEdgesIterator allEdgesIterator = graph . getAllEdges ( ) ; NodeAccess nodeAccess = graph . getNodeAccess ( ) ; IntHashSet inaccessible = new IntHashSet ( ) ; while ( allEdgesIterator . next ( ) ) { int adjNode = allEdgesIterator . getAdjNode ( ) ; SpatialRule ruleAdj = ruleLookup . lookupRule ( nodeAccess . getLatitude ( adjNode ) , nodeAccess . getLongitude ( adjNode ) ) ; int baseNode = allEdgesIterator . getBaseNode ( ) ; SpatialRule ruleBase = ruleLookup . lookupRule ( nodeAccess . getLatitude ( baseNode ) , nodeAccess . getLongitude ( baseNode ) ) ; if ( ruleAdj != ruleBase ) { inaccessible . add ( allEdgesIterator . getEdge ( ) ) ; } } return inaccessible ; }
This method makes edges crossing the specified border inaccessible to split a bigger area into smaller subnetworks . This is important for the world wide use case to limit the maximum distance and also to detect unreasonable routes faster .
31,452
boolean initActiveLandmarks ( int fromNode , int toNode , int [ ] activeLandmarkIndices , int [ ] activeFroms , int [ ] activeTos , boolean reverse ) { if ( fromNode < 0 || toNode < 0 ) throw new IllegalStateException ( "from " + fromNode + " and to " + toNode + " nodes have to be 0 or positive to init landmarks" ) ; int subnetworkFrom = subnetworkStorage . getSubnetwork ( fromNode ) ; int subnetworkTo = subnetworkStorage . getSubnetwork ( toNode ) ; if ( subnetworkFrom <= UNCLEAR_SUBNETWORK || subnetworkTo <= UNCLEAR_SUBNETWORK ) return false ; if ( subnetworkFrom != subnetworkTo ) { throw new ConnectionNotFoundException ( "Connection between locations not found. Different subnetworks " + subnetworkFrom + " vs. " + subnetworkTo , new HashMap < String , Object > ( ) ) ; } int [ ] tmpIDs = landmarkIDs . get ( subnetworkFrom ) ; List < Map . Entry < Integer , Integer > > list = new ArrayList < > ( tmpIDs . length ) ; for ( int lmIndex = 0 ; lmIndex < tmpIDs . length ; lmIndex ++ ) { int fromWeight = getFromWeight ( lmIndex , toNode ) - getFromWeight ( lmIndex , fromNode ) ; int toWeight = getToWeight ( lmIndex , fromNode ) - getToWeight ( lmIndex , toNode ) ; list . add ( new MapEntry < > ( reverse ? Math . max ( - fromWeight , - toWeight ) : Math . max ( fromWeight , toWeight ) , lmIndex ) ) ; } Collections . sort ( list , SORT_BY_WEIGHT ) ; if ( activeLandmarkIndices [ 0 ] >= 0 ) { IntHashSet set = new IntHashSet ( activeLandmarkIndices . length ) ; set . addAll ( activeLandmarkIndices ) ; int existingLandmarkCounter = 0 ; final int COUNT = Math . min ( activeLandmarkIndices . length - 2 , 2 ) ; for ( int i = 0 ; i < activeLandmarkIndices . length ; i ++ ) { if ( i >= activeLandmarkIndices . length - COUNT + existingLandmarkCounter ) { break ; } else { activeLandmarkIndices [ i ] = list . get ( i ) . getValue ( ) ; if ( set . contains ( activeLandmarkIndices [ i ] ) ) existingLandmarkCounter ++ ; } } } else { for ( int i = 0 ; i < activeLandmarkIndices . length ; i ++ ) { activeLandmarkIndices [ i ] = list . get ( i ) . getValue ( ) ; } } for ( int i = 0 ; i < activeLandmarkIndices . length ; i ++ ) { int lmIndex = activeLandmarkIndices [ i ] ; activeFroms [ i ] = getFromWeight ( lmIndex , toNode ) ; activeTos [ i ] = getToWeight ( lmIndex , toNode ) ; } return true ; }
From all available landmarks pick just a few active ones
31,453
public double calcNormalizedDist ( double fromY , double fromX , double toY , double toX ) { double dX = fromX - toX ; double dY = fromY - toY ; return dX * dX + dY * dY ; }
Calculates in normalized meter
31,454
public void setPreparationThreads ( int preparationThreads ) { this . preparationThreads = preparationThreads ; this . threadPool = java . util . concurrent . Executors . newFixedThreadPool ( preparationThreads ) ; }
This method changes the number of threads used for preparation on import . Default is 1 . Make sure that you have enough memory when increasing this number!
31,455
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 ] ) ; } }
Writes some internal data into the beginning of the specified file .
31,456
public static Builder start ( AlgorithmOptions opts ) { Builder b = new Builder ( ) ; if ( opts . algorithm != null ) b . algorithm ( opts . getAlgorithm ( ) ) ; if ( opts . traversalMode != null ) b . traversalMode ( opts . getTraversalMode ( ) ) ; if ( opts . weighting != null ) b . weighting ( opts . getWeighting ( ) ) ; if ( opts . maxVisitedNodes >= 0 ) b . maxVisitedNodes ( opts . maxVisitedNodes ) ; if ( ! opts . hints . isEmpty ( ) ) b . hints ( opts . hints ) ; return b ; }
This method clones the specified AlgorithmOption object with the possibility for further changes .
31,457
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 ; }
Before it saves this value it creates a string out of it .
31,458
public boolean activeOn ( LocalDate date ) { 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!" ) ; } } }
Is this service active on the specified date?
31,459
public static boolean checkOverlap ( Service s1 , Service s2 ) { if ( s1 . calendar == null || s2 . calendar == null ) { return false ; } 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 ; }
Checks for overlapping days of week between two service calendars
31,460
public PointList copy ( int from , int end ) { if ( from > end ) throw new IllegalArgumentException ( "from must be smaller or equal to end" ) ; if ( from < 0 || end > getSize ( ) ) throw new IllegalArgumentException ( "Illegal interval: " + from + ", " + end + ", size:" + getSize ( ) ) ; PointList thisPL = this ; if ( this instanceof ShallowImmutablePointList ) { ShallowImmutablePointList spl = ( ShallowImmutablePointList ) this ; thisPL = spl . wrappedPointList ; from = spl . fromOffset + from ; end = spl . fromOffset + end ; } int len = end - from ; PointList copyPL = new PointList ( len , is3D ( ) ) ; copyPL . size = len ; copyPL . isImmutable = isImmutable ( ) ; System . arraycopy ( thisPL . latitudes , from , copyPL . latitudes , 0 , len ) ; System . arraycopy ( thisPL . longitudes , from , copyPL . longitudes , 0 , len ) ; if ( is3D ( ) ) System . arraycopy ( thisPL . elevations , from , copyPL . elevations , 0 , len ) ; return copyPL ; }
This method does a deep copy of this object for the specified range .
31,461
public PointList shallowCopy ( final int from , final int end , boolean makeImmutable ) { if ( makeImmutable ) this . makeImmutable ( ) ; return new ShallowImmutablePointList ( from , end , this ) ; }
Create a shallow copy of this Pointlist from from to end excluding end .
31,462
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 ; } } return this . length - other . length ; }
Signed int order comparison
31,463
public void addEdges ( Collection < EdgeIteratorState > edges ) { for ( EdgeIteratorState edge : edges ) { visitedEdges . add ( edge . getEdge ( ) ) ; } }
This method adds the specified path to this weighting which should be penalized in the calcWeight method .
31,464
public Path extract ( ) { if ( isFound ( ) ) throw new IllegalStateException ( "Extract can only be called once" ) ; extractSW . start ( ) ; SPTEntry currEdge = sptEntry ; setEndNode ( currEdge . adjNode ) ; boolean nextEdgeValid = EdgeIterator . Edge . isValid ( currEdge . edge ) ; int nextEdge ; while ( nextEdgeValid ) { nextEdgeValid = EdgeIterator . Edge . isValid ( currEdge . parent . edge ) ; nextEdge = nextEdgeValid ? currEdge . parent . edge : EdgeIterator . NO_EDGE ; processEdge ( currEdge . edge , currEdge . adjNode , nextEdge ) ; currEdge = currEdge . parent ; } setFromNode ( currEdge . adjNode ) ; reverseOrder ( ) ; extractSW . stop ( ) ; return setFound ( true ) ; }
Extracts the Path from the shortest - path - tree determined by sptEntry .
31,465
protected void processEdge ( int edgeId , int adjNode , int prevEdgeId ) { EdgeIteratorState iter = graph . getEdgeIteratorState ( edgeId , adjNode ) ; distance += iter . getDistance ( ) ; time += weighting . calcMillis ( iter , false , prevEdgeId ) ; addEdge ( edgeId ) ; }
Calculates the distance and time of the specified edgeId . Also it adds the edgeId to the path list .
31,466
public List < EdgeIteratorState > calcEdges ( ) { final List < EdgeIteratorState > edges = new ArrayList < > ( edgeIds . size ( ) ) ; if ( edgeIds . isEmpty ( ) ) return edges ; forEveryEdge ( new EdgeVisitor ( ) { public void next ( EdgeIteratorState eb , int index , int prevEdgeId ) { edges . add ( eb ) ; } public void finish ( ) { } } ) ; return edges ; }
Returns the list of all edges .
31,467
public Map < String , List < PathDetail > > calcDetails ( List < String > requestedPathDetails , PathDetailsBuilderFactory pathBuilderFactory , int previousIndex ) { if ( ! isFound ( ) || requestedPathDetails . isEmpty ( ) ) return Collections . emptyMap ( ) ; List < PathDetailsBuilder > pathBuilders = pathBuilderFactory . createPathDetailsBuilders ( requestedPathDetails , encoder , weighting ) ; if ( pathBuilders . isEmpty ( ) ) return Collections . emptyMap ( ) ; 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 ; }
Calculates the PathDetails for this Path . This method will return fast if there are no calculators .
31,468
public boolean hasTag ( String key , String ... values ) { Object value = properties . get ( key ) ; if ( value == null ) return false ; if ( values . length == 0 ) return true ; for ( String val : values ) { if ( val . equals ( value ) ) return true ; } return false ; }
Check that a given tag has one of the specified values . If no values are given just checks for presence of the tag
31,469
public final boolean hasTag ( String key , Set < String > values ) { return values . contains ( getTag ( key , "" ) ) ; }
Check that a given tag has one of the specified values .
31,470
public boolean hasTag ( List < String > keyList , Set < String > values ) { for ( String key : keyList ) { if ( values . contains ( getTag ( key , "" ) ) ) return true ; } return false ; }
Check a number of tags in the given order for the any of the given values . Used to parse hierarchical access restrictions
31,471
public String getFirstPriorityTag ( List < String > restrictions ) { for ( String str : restrictions ) { if ( hasTag ( str ) ) return getTag ( str ) ; } return "" ; }
Returns the first existing tag of the specified list where the order is important .
31,472
public void createEncodedValues ( List < EncodedValue > registerNewEncodedValue , String prefix , int index ) { registerNewEncodedValue . add ( accessEnc = new SimpleBooleanEncodedValue ( prefix + "access" , true ) ) ; roundaboutEnc = getBooleanEncodedValue ( EncodingManager . ROUNDABOUT ) ; encoderBit = 1L << index ; }
Defines bits used for edge flags used for access speed etc .
31,473
protected void flagsDefault ( IntsRef edgeFlags , boolean forward , boolean backward ) { if ( forward ) speedEncoder . setDecimal ( false , edgeFlags , speedDefault ) ; if ( backward ) speedEncoder . setDecimal ( true , edgeFlags , speedDefault ) ; accessEnc . setBool ( false , edgeFlags , forward ) ; accessEnc . setBool ( true , edgeFlags , backward ) ; }
Sets default flags with specified access .
31,474
protected double getFerrySpeed ( ReaderWay way ) { long duration = 0 ; try { duration = Long . parseLong ( way . getTag ( "duration:seconds" ) ) ; } catch ( Exception ex ) { } double durationInHours = duration / 60d / 60d ; Number estimatedLength = way . getTag ( "estimated_distance" , null ) ; if ( durationInHours > 0 ) try { if ( estimatedLength != null ) { double estimatedLengthInKm = estimatedLength . doubleValue ( ) / 1000 ; double calculatedTripSpeed = estimatedLengthInKm / durationInHours / 1.4 ; if ( calculatedTripSpeed > 0.01d ) { if ( calculatedTripSpeed > getMaxSpeed ( ) ) { return getMaxSpeed ( ) ; } if ( Math . round ( calculatedTripSpeed ) < speedFactor / 2 ) { return speedFactor / 2 ; } return Math . round ( calculatedTripSpeed ) ; } else { long lastId = way . getNodes ( ) . isEmpty ( ) ? - 1 : way . getNodes ( ) . get ( way . getNodes ( ) . size ( ) - 1 ) ; long firstId = way . getNodes ( ) . isEmpty ( ) ? - 1 : way . getNodes ( ) . get ( 0 ) ; if ( firstId != lastId ) logger . warn ( "Unrealistic long duration ignored in way with way ID=" + way . getId ( ) + " : Duration tag value=" + way . getTag ( "duration" ) + " (=" + Math . round ( duration / 60d ) + " minutes)" ) ; durationInHours = 0 ; } } } catch ( Exception ex ) { } if ( durationInHours == 0 ) { if ( estimatedLength != null && estimatedLength . doubleValue ( ) <= 300 ) return speedFactor / 2 ; return UNKNOWN_DURATION_FERRY_SPEED ; } else if ( durationInHours > 1 ) { return LONG_TRIP_FERRY_SPEED ; } else { return SHORT_TRIP_FERRY_SPEED ; } }
Special handling for ferry ways .
31,475
protected void setSpeed ( boolean reverse , IntsRef edgeFlags , double speed ) { if ( speed < 0 || Double . isNaN ( speed ) ) throw new IllegalArgumentException ( "Speed cannot be negative or NaN: " + speed + ", flags:" + BitUtil . LITTLE . toBitString ( edgeFlags ) ) ; if ( speed < speedFactor / 2 ) { speedEncoder . setDecimal ( reverse , edgeFlags , 0 ) ; accessEnc . setBool ( reverse , edgeFlags , false ) ; return ; } if ( speed > getMaxSpeed ( ) ) speed = getMaxSpeed ( ) ; speedEncoder . setDecimal ( reverse , edgeFlags , speed ) ; }
Most use cases do not require this method . Will still keep it accessible so that one can disable it until the averageSpeedEncodedValue is moved out of the FlagEncoder .
31,476
public LMAlgoFactoryDecorator setWeightingsAsStrings ( List < String > weightingList ) { if ( weightingList . isEmpty ( ) ) throw new IllegalArgumentException ( "It is not allowed to pass an emtpy weightingList" ) ; weightingsAsStrings . clear ( ) ; for ( String strWeighting : weightingList ) { strWeighting = toLowerCase ( strWeighting ) ; strWeighting = strWeighting . trim ( ) ; addWeighting ( strWeighting ) ; } return this ; }
Enables the use of contraction hierarchies to reduce query times . Enabled by default .
31,477
public void createPreparations ( GraphHopperStorage ghStorage , LocationIndex locationIndex ) { if ( ! isEnabled ( ) || ! preparations . isEmpty ( ) ) return ; if ( weightings . isEmpty ( ) ) throw new IllegalStateException ( "No landmark weightings found" ) ; List < LandmarkSuggestion > lmSuggestions = new ArrayList < > ( lmSuggestionsLocations . size ( ) ) ; if ( ! lmSuggestionsLocations . isEmpty ( ) ) { try { for ( String loc : lmSuggestionsLocations ) { lmSuggestions . add ( LandmarkSuggestion . readLandmarks ( loc , locationIndex ) ) ; } } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } } for ( Weighting weighting : getWeightings ( ) ) { Double maximumWeight = maximumWeights . get ( weighting . getName ( ) ) ; if ( maximumWeight == null ) throw new IllegalStateException ( "maximumWeight cannot be null. Default should be just negative. " + "Couldn't find " + weighting . getName ( ) + " in " + maximumWeights ) ; PrepareLandmarks tmpPrepareLM = new PrepareLandmarks ( ghStorage . getDirectory ( ) , ghStorage , weighting , landmarkCount , activeLandmarkCount ) . setLandmarkSuggestions ( lmSuggestions ) . setMaximumWeight ( maximumWeight ) . setLogDetails ( logDetails ) ; if ( minNodes > 1 ) tmpPrepareLM . setMinimumNodes ( minNodes ) ; addPreparation ( tmpPrepareLM ) ; } }
This method creates the landmark storages ready for landmark creation .
31,478
public CHGraph chGraphCreate ( Weighting singleCHWeighting ) { return setCHGraph ( singleCHWeighting ) . create ( ) . getGraph ( CHGraph . class , singleCHWeighting ) ; }
Creates a CHGraph
31,479
public void setTimeLimit ( double limit ) { exploreType = TIME ; this . limit = limit * 1000 ; this . finishLimit = this . limit + Math . max ( this . limit * 0.14 , 200_000 ) ; }
Time limit in seconds
31,480
public void setDistanceLimit ( double limit ) { exploreType = DISTANCE ; this . limit = limit ; this . finishLimit = limit + Math . max ( limit * 0.14 , 2_000 ) ; }
Distance limit in meter
31,481
public static void calcPoints ( final double lat1 , final double lon1 , final double lat2 , final double lon2 , final PointEmitter emitter , final double offsetLat , final double offsetLon , final double deltaLat , final double deltaLon ) { int y1 = ( int ) ( ( lat1 - offsetLat ) / deltaLat ) ; int x1 = ( int ) ( ( lon1 - offsetLon ) / deltaLon ) ; int y2 = ( int ) ( ( lat2 - offsetLat ) / deltaLat ) ; int x2 = ( int ) ( ( lon2 - offsetLon ) / deltaLon ) ; bresenham ( y1 , x1 , y2 , x2 , new PointEmitter ( ) { public void set ( double lat , double lon ) { emitter . set ( ( lat + .1 ) * deltaLat + offsetLat , ( lon + .1 ) * deltaLon + offsetLon ) ; } } ) ; }
Calls the Bresenham algorithm but make it working for double values
31,482
private boolean loopShortcutNecessary ( int node , int firstOrigEdge , int lastOrigEdge , double loopWeight ) { EdgeIterator inIter = loopAvoidanceInEdgeExplorer . setBaseNode ( node ) ; while ( inIter . next ( ) ) { EdgeIterator outIter = loopAvoidanceOutEdgeExplorer . setBaseNode ( node ) ; double inTurnCost = getTurnCost ( inIter . getEdge ( ) , node , firstOrigEdge ) ; while ( outIter . next ( ) ) { double totalLoopCost = inTurnCost + loopWeight + getTurnCost ( lastOrigEdge , node , outIter . getEdge ( ) ) ; double directTurnCost = getTurnCost ( inIter . getEdge ( ) , node , outIter . getEdge ( ) ) ; if ( totalLoopCost < directTurnCost ) { return true ; } } } LOGGER . trace ( "Loop avoidance -> no shortcut" ) ; return false ; }
A given potential loop shortcut is only necessary if there is at least one pair of original in - & out - edges for which taking the loop is cheaper than doing the direct turn . However this is almost always the case because doing a u - turn at any of the incoming edges is forbidden i . e . he costs of the direct turn will be infinite .
31,483
public int initSearch ( int centerNode , int sourceNode , int sourceEdge ) { reset ( ) ; this . sourceEdge = sourceEdge ; this . sourceNode = sourceNode ; this . centerNode = centerNode ; setInitialEntries ( sourceNode , sourceEdge , centerNode ) ; if ( numPathsToCenter < 1 ) { reset ( ) ; return 0 ; } currentBatchStats . numSearches ++ ; currentBatchStats . maxNumSettledEdges += maxSettledEdges ; totalStats . numSearches ++ ; totalStats . maxNumSettledEdges += maxSettledEdges ; return dijkstraHeap . getSize ( ) ; }
Deletes the shortest path tree that has been found so far and initializes a new witness path search for a given node to be contracted and search edge .
31,484
public static List < String > getProblems ( Graph g ) { List < String > problems = new ArrayList < > ( ) ; int nodes = g . getNodes ( ) ; int nodeIndex = 0 ; NodeAccess na = g . getNodeAccess ( ) ; try { EdgeExplorer explorer = g . createEdgeExplorer ( ) ; for ( ; nodeIndex < nodes ; nodeIndex ++ ) { double lat = na . getLatitude ( nodeIndex ) ; if ( lat > 90 || lat < - 90 ) problems . add ( "latitude is not within its bounds " + lat ) ; double lon = na . getLongitude ( nodeIndex ) ; if ( lon > 180 || lon < - 180 ) problems . add ( "longitude is not within its bounds " + lon ) ; EdgeIterator iter = explorer . setBaseNode ( nodeIndex ) ; while ( iter . next ( ) ) { if ( iter . getAdjNode ( ) >= nodes ) { problems . add ( "edge of " + nodeIndex + " has a node " + iter . getAdjNode ( ) + " greater or equal to getNodes" ) ; } if ( iter . getAdjNode ( ) < 0 ) { problems . add ( "edge of " + nodeIndex + " has a negative node " + iter . getAdjNode ( ) ) ; } } } } catch ( Exception ex ) { throw new RuntimeException ( "problem with node " + nodeIndex , ex ) ; } return problems ; }
This method could throw an exception if problems like index out of bounds etc
31,485
public static GraphHopperStorage newStorage ( GraphHopperStorage store ) { Directory outdir = guessDirectory ( store ) ; boolean is3D = store . getNodeAccess ( ) . is3D ( ) ; return new GraphHopperStorage ( store . getNodeBasedCHWeightings ( ) , store . getEdgeBasedCHWeightings ( ) , outdir , store . getEncodingManager ( ) , is3D , store . getExtension ( ) ) . create ( store . getNodes ( ) ) ; }
Create a new storage from the specified one without copying the data .
31,486
public static int createEdgeKey ( int nodeA , int nodeB , int edgeId , boolean reverse ) { edgeId = edgeId << 1 ; if ( reverse ) return ( nodeA > nodeB ) ? edgeId : edgeId + 1 ; return ( nodeA > nodeB ) ? edgeId + 1 : edgeId ; }
Creates unique positive number for specified edgeId taking into account the direction defined by nodeA nodeB and reverse .
31,487
public static int getEdgeKey ( Graph graph , int edgeId , int node , boolean reverse ) { EdgeIteratorState edgeIteratorState = graph . getEdgeIteratorState ( edgeId , node ) ; return GHUtility . createEdgeKey ( edgeIteratorState . getBaseNode ( ) , edgeIteratorState . getAdjNode ( ) , edgeId , reverse ) ; }
Returns the edge key for a given edge id and adjacent node . This is needed in a few places where the base node is not known .
31,488
public double getMaxSpeed ( String highwayTag , double _default ) { switch ( highwayTag ) { case "motorway" : return Integer . MAX_VALUE ; case "trunk" : return Integer . MAX_VALUE ; case "residential" : return 100 ; case "living_street" : return 4 ; default : return super . getMaxSpeed ( highwayTag , _default ) ; } }
Germany contains roads with no speed limit . For these roads this method will return Integer . MAX_VALUE . Your implementation should be able to handle these cases .
31,489
private InstructionList updateInstructionsWithContext ( InstructionList instructions ) { Instruction instruction ; Instruction nextInstruction ; for ( int i = 0 ; i < instructions . size ( ) - 1 ; i ++ ) { instruction = instructions . get ( i ) ; if ( i == 0 && ! Double . isNaN ( favoredHeading ) && instruction . extraInfo . containsKey ( "heading" ) ) { double heading = ( double ) instruction . extraInfo . get ( "heading" ) ; double diff = Math . abs ( heading - favoredHeading ) % 360 ; if ( diff > 170 && diff < 190 ) { instruction . setSign ( Instruction . U_TURN_UNKNOWN ) ; } } if ( instruction . getSign ( ) == Instruction . REACHED_VIA ) { nextInstruction = instructions . get ( i + 1 ) ; if ( nextInstruction . getSign ( ) != Instruction . CONTINUE_ON_STREET || ! instruction . extraInfo . containsKey ( "last_heading" ) || ! nextInstruction . extraInfo . containsKey ( "heading" ) ) { continue ; } double lastHeading = ( double ) instruction . extraInfo . get ( "last_heading" ) ; double heading = ( double ) nextInstruction . extraInfo . get ( "heading" ) ; double diff = Math . abs ( lastHeading - heading ) % 360 ; if ( diff > 179 && diff < 181 ) { nextInstruction . setSign ( Instruction . U_TURN_UNKNOWN ) ; } } } return instructions ; }
This method iterates over all instructions and uses the available context to improve the instructions . If the requests contains a heading this method can transform the first continue to a u - turn if the heading points into the opposite direction of the route . At a waypoint it can transform the continue to a u - turn if the route involves turning .
31,490
int subSimplify ( PointList points , int fromIndex , int lastIndex ) { if ( lastIndex - fromIndex < 2 ) { return 0 ; } int indexWithMaxDist = - 1 ; double maxDist = - 1 ; double firstLat = points . getLatitude ( fromIndex ) ; double firstLon = points . getLongitude ( fromIndex ) ; double lastLat = points . getLatitude ( lastIndex ) ; double lastLon = points . getLongitude ( lastIndex ) ; for ( int i = fromIndex + 1 ; i < lastIndex ; i ++ ) { double lat = points . getLatitude ( i ) ; if ( Double . isNaN ( lat ) ) { continue ; } double lon = points . getLongitude ( i ) ; double dist = 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 ; }
keep the points of fromIndex and lastIndex
31,491
List < IntArrayList > findSubnetworks ( PrepEdgeFilter filter ) { final BooleanEncodedValue accessEnc = filter . getAccessEnc ( ) ; final EdgeExplorer explorer = ghStorage . createEdgeExplorer ( filter ) ; int locs = ghStorage . getNodes ( ) ; List < IntArrayList > list = new ArrayList < > ( 100 ) ; final GHBitSet bs = new GHBitSetImpl ( locs ) ; for ( int start = 0 ; start < locs ; start ++ ) { if ( bs . contains ( start ) ) continue ; final IntArrayList intList = new IntArrayList ( 20 ) ; list . add ( intList ) ; new BreadthFirstSearch ( ) { int tmpCounter = 0 ; protected GHBitSet createBitSet ( ) { return bs ; } protected final boolean goFurther ( int nodeId ) { if ( tmpCounter > maxEdgesPerNode . get ( ) ) maxEdgesPerNode . set ( tmpCounter ) ; tmpCounter = 0 ; intList . add ( nodeId ) ; return true ; } protected final boolean checkAdjacent ( EdgeIteratorState edge ) { if ( edge . get ( accessEnc ) || edge . getReverse ( accessEnc ) ) { tmpCounter ++ ; return true ; } return false ; } } . start ( explorer , start ) ; intList . trimToSize ( ) ; } return list ; }
This method finds the double linked components according to the specified filter .
31,492
int keepLargeNetworks ( PrepEdgeFilter filter , List < IntArrayList > components ) { if ( components . size ( ) <= 1 ) return 0 ; int maxCount = - 1 ; IntIndexedContainer oldComponent = null ; int allRemoved = 0 ; BooleanEncodedValue accessEnc = filter . getAccessEnc ( ) ; EdgeExplorer explorer = ghStorage . createEdgeExplorer ( filter ) ; for ( IntArrayList component : components ) { if ( maxCount < 0 ) { maxCount = component . size ( ) ; oldComponent = component ; continue ; } int removedEdges ; if ( maxCount < component . size ( ) ) { removedEdges = removeEdges ( explorer , accessEnc , oldComponent , minNetworkSize ) ; maxCount = component . size ( ) ; oldComponent = component ; } else { removedEdges = removeEdges ( explorer , accessEnc , component , minNetworkSize ) ; } allRemoved += removedEdges ; } if ( allRemoved > ghStorage . getAllEdges ( ) . length ( ) / 2 ) throw new IllegalStateException ( "Too many total edges were removed: " + allRemoved + ", all edges:" + ghStorage . getAllEdges ( ) . length ( ) ) ; return allRemoved ; }
Deletes all but the largest subnetworks .
31,493
int removeEdges ( final PrepEdgeFilter bothFilter , List < IntArrayList > components , int min ) { EdgeExplorer explorer = ghStorage . createEdgeExplorer ( bothFilter ) ; int removedEdges = 0 ; for ( IntArrayList component : components ) { removedEdges += removeEdges ( explorer , bothFilter . getAccessEnc ( ) , component , min ) ; } return removedEdges ; }
This method removes the access to edges available from the nodes contained in the components . But only if a components size is smaller then the specified min value .
31,494
void markNodesRemovedIfUnreachable ( ) { EdgeExplorer edgeExplorer = ghStorage . createEdgeExplorer ( ) ; for ( int nodeIndex = 0 ; nodeIndex < ghStorage . getNodes ( ) ; nodeIndex ++ ) { if ( detectNodeRemovedForAllEncoders ( edgeExplorer , nodeIndex ) ) ghStorage . markNodeRemoved ( nodeIndex ) ; } }
Removes nodes if all edges are not accessible . I . e . removes zero degree nodes .
31,495
boolean detectNodeRemovedForAllEncoders ( EdgeExplorer edgeExplorerAllEdges , int nodeIndex ) { EdgeIterator iter = edgeExplorerAllEdges . setBaseNode ( nodeIndex ) ; while ( iter . next ( ) ) { for ( BooleanEncodedValue accessEnc : accessEncList ) { if ( iter . get ( accessEnc ) || iter . getReverse ( accessEnc ) ) return false ; } } return true ; }
This method checks if the node is removed or inaccessible for ALL encoders .
31,496
public static byte [ ] decompress ( byte [ ] value ) throws DataFormatException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( value . length ) ; Inflater decompressor = new Inflater ( ) ; try { decompressor . setInput ( value ) ; final byte [ ] buf = new byte [ 1024 ] ; while ( ! decompressor . finished ( ) ) { int count = decompressor . inflate ( buf ) ; bos . write ( buf , 0 , count ) ; } } finally { decompressor . end ( ) ; } return bos . toByteArray ( ) ; }
Decompress the byte array previously returned by compress
31,497
public void addTurnInfo ( int fromEdge , int viaNode , int toEdge , long turnFlags ) { if ( turnFlags == EMPTY_FLAGS ) return ; mergeOrOverwriteTurnInfo ( fromEdge , viaNode , toEdge , turnFlags , true ) ; }
Add an entry which is a turn restriction or cost information via the turnFlags . Overwrite existing information if it is the same edges and node .
31,498
public void mergeOrOverwriteTurnInfo ( int fromEdge , int viaNode , int toEdge , long turnFlags , boolean merge ) { int newEntryIndex = turnCostsCount ; ensureTurnCostIndex ( newEntryIndex ) ; boolean oldEntryFound = false ; long newFlags = turnFlags ; int next = NO_TURN_ENTRY ; int previousEntryIndex = nodeAccess . getAdditionalNodeField ( viaNode ) ; if ( previousEntryIndex == NO_TURN_ENTRY ) { nodeAccess . setAdditionalNodeField ( viaNode , newEntryIndex ) ; } else { int i = 0 ; next = turnCosts . getInt ( ( long ) previousEntryIndex * turnCostsEntryBytes + TC_NEXT ) ; long existingFlags = 0 ; while ( true ) { long costsIdx = ( long ) previousEntryIndex * turnCostsEntryBytes ; if ( fromEdge == turnCosts . getInt ( costsIdx + TC_FROM ) && toEdge == turnCosts . getInt ( costsIdx + TC_TO ) ) { oldEntryFound = true ; existingFlags = turnCosts . getInt ( costsIdx + TC_FLAGS ) ; break ; } else if ( next == NO_TURN_ENTRY ) { break ; } previousEntryIndex = next ; if ( i ++ > 1000 ) { throw new IllegalStateException ( "Something unexpected happened. A node probably will not have 1000+ relations." ) ; } next = turnCosts . getInt ( ( long ) next * turnCostsEntryBytes + TC_NEXT ) ; } if ( ! oldEntryFound ) { turnCosts . setInt ( ( long ) previousEntryIndex * turnCostsEntryBytes + TC_NEXT , newEntryIndex ) ; } else if ( merge ) { newFlags = existingFlags | newFlags ; } else { } } long costsBase ; if ( ! oldEntryFound ) { costsBase = ( long ) newEntryIndex * turnCostsEntryBytes ; turnCostsCount ++ ; } else { costsBase = ( long ) previousEntryIndex * turnCostsEntryBytes ; } turnCosts . setInt ( costsBase + TC_FROM , fromEdge ) ; turnCosts . setInt ( costsBase + TC_TO , toEdge ) ; turnCosts . setInt ( costsBase + TC_FLAGS , ( int ) newFlags ) ; turnCosts . setInt ( costsBase + TC_NEXT , next ) ; }
Add a new turn cost entry or clear an existing . See tests for usage examples .
31,499
public BBox calcBBox2D ( ) { check ( "calcRouteBBox" ) ; BBox bounds = BBox . createInverse ( false ) ; for ( int i = 0 ; i < pointList . getSize ( ) ; i ++ ) { bounds . update ( pointList . getLatitude ( i ) , pointList . getLongitude ( i ) ) ; } return bounds ; }
Calculates the 2D bounding box of this route