idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
31,900
public static int fastHashInsertOnly ( final WritableMemory wmem , final int lgArrLongs , final long hash , final int memOffsetBytes ) { final int arrayMask = ( 1 << lgArrLongs ) - 1 ; // current Size -1 final int stride = getStride ( hash , lgArrLongs ) ; int curProbe = ( int ) ( hash & arrayMask ) ; // search for duplicate or zero final int loopIndex = curProbe ; do { final int curProbeOffsetBytes = ( curProbe << 3 ) + memOffsetBytes ; final long curArrayHash = wmem . getLong ( curProbeOffsetBytes ) ; if ( curArrayHash == EMPTY ) { wmem . putLong ( curProbeOffsetBytes , hash ) ; return curProbe ; } curProbe = ( curProbe + stride ) & arrayMask ; } while ( curProbe != loopIndex ) ; throw new SketchesArgumentException ( "No empty slot in table!" ) ; }
This is a classical Knuth - style Open Addressing Double Hash insert scheme but inserts values directly into a Memory . This method assumes that the input hash is not a duplicate . Useful for rebuilding tables to avoid unnecessary comparisons . Returns the index of insertion which is always positive or zero . Throws an exception if table has no empty slot .
223
67
31,901
@ SuppressFBWarnings ( value = "VO_VOLATILE_INCREMENT" , justification = "False Positive" ) private void advanceEpoch ( ) { awaitBgPropagationTermination ( ) ; startEagerPropagation ( ) ; ConcurrentPropagationService . resetExecutorService ( Thread . currentThread ( ) . getId ( ) ) ; //noinspection NonAtomicOperationOnVolatileField // this increment of a volatile field is done within the scope of the propagation // synchronization and hence is done by a single thread // Ignore a FindBugs warning epoch_ ++ ; endPropagation ( null , true ) ; initBgPropagationService ( ) ; }
Advances the epoch while there is no background propagation This ensures a propagation invoked before the reset cannot affect the sketch after the reset is completed .
151
28
31,902
static HeapUpdateDoublesSketch newInstance ( final int k ) { final HeapUpdateDoublesSketch hqs = new HeapUpdateDoublesSketch ( k ) ; final int baseBufAlloc = 2 * Math . min ( DoublesSketch . MIN_K , k ) ; //the min is important hqs . n_ = 0 ; hqs . combinedBuffer_ = new double [ baseBufAlloc ] ; hqs . baseBufferCount_ = 0 ; hqs . bitPattern_ = 0 ; hqs . minValue_ = Double . NaN ; hqs . maxValue_ = Double . NaN ; return hqs ; }
Obtains a new on - heap instance of a DoublesSketch .
147
16
31,903
private void srcMemoryToCombinedBuffer ( final Memory srcMem , final int serVer , final boolean srcIsCompact , final int combBufCap ) { final int preLongs = 2 ; final int extra = ( serVer == 1 ) ? 3 : 2 ; // space for min and max values, buf alloc (SerVer 1) final int preBytes = ( preLongs + extra ) << 3 ; final int bbCnt = baseBufferCount_ ; final int k = getK ( ) ; final long n = getN ( ) ; final double [ ] combinedBuffer = new double [ combBufCap ] ; //always non-compact //Load min, max putMinValue ( srcMem . getDouble ( MIN_DOUBLE ) ) ; putMaxValue ( srcMem . getDouble ( MAX_DOUBLE ) ) ; if ( srcIsCompact ) { //Load base buffer srcMem . getDoubleArray ( preBytes , combinedBuffer , 0 , bbCnt ) ; //Load levels from compact srcMem long bitPattern = bitPattern_ ; if ( bitPattern != 0 ) { long memOffset = preBytes + ( bbCnt << 3 ) ; int combBufOffset = 2 * k ; while ( bitPattern != 0L ) { if ( ( bitPattern & 1L ) > 0L ) { srcMem . getDoubleArray ( memOffset , combinedBuffer , combBufOffset , k ) ; memOffset += ( k << 3 ) ; //bytes, increment compactly } combBufOffset += k ; //doubles, increment every level bitPattern >>>= 1 ; } } } else { //srcMem not compact final int levels = Util . computeNumLevelsNeeded ( k , n ) ; final int totItems = ( levels == 0 ) ? bbCnt : ( 2 + levels ) * k ; srcMem . getDoubleArray ( preBytes , combinedBuffer , 0 , totItems ) ; } putCombinedBuffer ( combinedBuffer ) ; }
Loads the Combined Buffer min and max from the given source Memory . The resulting Combined Buffer is always in non - compact form and must be pre - allocated .
426
32
31,904
static void checkHeapMemCapacity ( final int k , final long n , final boolean compact , final int serVer , final long memCapBytes ) { final int metaPre = Family . QUANTILES . getMaxPreLongs ( ) + ( ( serVer == 1 ) ? 3 : 2 ) ; final int retainedItems = computeRetainedItems ( k , n ) ; final int reqBufBytes ; if ( compact ) { reqBufBytes = ( metaPre + retainedItems ) << 3 ; } else { //not compact final int totLevels = Util . computeNumLevelsNeeded ( k , n ) ; reqBufBytes = ( totLevels == 0 ) ? ( metaPre + retainedItems ) << 3 : ( metaPre + ( ( 2 + totLevels ) * k ) ) << 3 ; } if ( memCapBytes < reqBufBytes ) { throw new SketchesArgumentException ( "Possible corruption: Memory capacity too small: " + memCapBytes + " < " + reqBufBytes ) ; } }
Checks the validity of the heap memory capacity assuming n k and the compact state .
227
17
31,905
static int getNumCoupons ( final Memory mem ) { final Format format = getFormat ( mem ) ; final HiField hiField = HiField . NUM_COUPONS ; final long offset = getHiFieldOffset ( format , hiField ) ; return mem . getInt ( offset ) ; }
PREAMBLE HI_FIELD GETS
63
8
31,906
static void putEmptyMerged ( final WritableMemory wmem , final int lgK , final short seedHash ) { final Format format = Format . EMPTY_MERGED ; final byte preInts = getDefinedPreInts ( format ) ; final byte fiCol = ( byte ) 0 ; final byte flags = ( byte ) ( ( format . ordinal ( ) << 2 ) | COMPRESSED_FLAG_MASK ) ; checkCapacity ( wmem . getCapacity ( ) , 8 ) ; putFirst8 ( wmem , preInts , ( byte ) lgK , fiCol , flags , seedHash ) ; }
PUT INTO MEMORY
138
4
31,907
static void checkLoPreamble ( final Memory mem ) { rtAssertEquals ( getSerVer ( mem ) , SER_VER & 0XFF ) ; final Format fmt = getFormat ( mem ) ; final int preIntsDef = getDefinedPreInts ( fmt ) & 0XFF ; rtAssertEquals ( getPreInts ( mem ) , preIntsDef ) ; final Family fam = getFamily ( mem ) ; rtAssert ( fam == Family . CPC ) ; final int lgK = getLgK ( mem ) ; rtAssert ( ( lgK >= 4 ) && ( lgK <= 26 ) ) ; final int fiCol = getFiCol ( mem ) ; rtAssert ( ( fiCol <= 63 ) && ( fiCol >= 0 ) ) ; }
basic checks of SerVer Format preInts Family fiCol lgK .
179
16
31,908
static final void validateValues ( final float [ ] values ) { for ( int i = 0 ; i < values . length ; i ++ ) { if ( Float . isNaN ( values [ i ] ) ) { throw new SketchesArgumentException ( "Values must not be NaN" ) ; } if ( ( i < ( values . length - 1 ) ) && ( values [ i ] >= values [ i + 1 ] ) ) { throw new SketchesArgumentException ( "Values must be unique and monotonically increasing" ) ; } } }
Checks the sequential validity of the given array of float values . They must be unique monotonically increasing and not NaN .
119
26
31,909
static CompactSketch compact ( final long [ ] cache , final boolean empty , final short seedHash , final int curCount , final long thetaLong ) { if ( ( curCount == 1 ) && ( thetaLong == Long . MAX_VALUE ) ) { return new SingleItemSketch ( cache [ 0 ] , seedHash ) ; } return new HeapCompactUnorderedSketch ( cache , empty , seedHash , curCount , thetaLong ) ; }
Constructs this sketch from correct valid arguments .
102
9
31,910
static DirectUpdateDoublesSketch newInstance ( final int k , final WritableMemory dstMem ) { // must be able to hold at least an empty sketch final long memCap = dstMem . getCapacity ( ) ; checkDirectMemCapacity ( k , 0 , memCap ) ; //initialize dstMem dstMem . putLong ( 0 , 0L ) ; //clear pre0 insertPreLongs ( dstMem , 2 ) ; insertSerVer ( dstMem , DoublesSketch . DOUBLES_SER_VER ) ; insertFamilyID ( dstMem , Family . QUANTILES . getID ( ) ) ; insertFlags ( dstMem , EMPTY_FLAG_MASK ) ; insertK ( dstMem , k ) ; if ( memCap >= COMBINED_BUFFER ) { insertN ( dstMem , 0L ) ; insertMinDouble ( dstMem , Double . NaN ) ; insertMaxDouble ( dstMem , Double . NaN ) ; } final DirectUpdateDoublesSketch dds = new DirectUpdateDoublesSketch ( k ) ; dds . mem_ = dstMem ; return dds ; }
Obtains a new Direct instance of a DoublesSketch which may be off - heap .
249
20
31,911
private WritableMemory growCombinedMemBuffer ( final int itemSpaceNeeded ) { final long memBytes = mem_ . getCapacity ( ) ; final int needBytes = ( itemSpaceNeeded << 3 ) + COMBINED_BUFFER ; //+ preamble + min & max assert needBytes > memBytes ; memReqSvr = ( memReqSvr == null ) ? mem_ . getMemoryRequestServer ( ) : memReqSvr ; final WritableMemory newMem = memReqSvr . request ( needBytes ) ; mem_ . copyTo ( 0 , newMem , 0 , memBytes ) ; memReqSvr . requestClose ( mem_ , newMem ) ; return newMem ; }
Direct supporting methods
159
3
31,912
public static < T > VarOptItemsSketch < T > newInstance ( final int k , final ResizeFactor rf ) { return new VarOptItemsSketch <> ( k , rf ) ; }
Construct a varopt sampling sketch with up to k samples using the specified resize factor .
47
17
31,913
static < T > VarOptItemsSketch < T > newInstanceAsGadget ( final int k ) { final VarOptItemsSketch < T > sketch = new VarOptItemsSketch <> ( k , DEFAULT_RESIZE_FACTOR ) ; sketch . marks_ = new ArrayList <> ( sketch . currItemsAlloc_ ) ; return sketch ; }
Construct a varopt sketch for use as a unioning gadget meaning the array of marked elements is also initialized .
85
22
31,914
VarOptItemsSketch < T > copyAndSetN ( final boolean asSketch , final long adjustedN ) { final VarOptItemsSketch < T > sketch ; sketch = new VarOptItemsSketch <> ( data_ , weights_ , k_ , n_ , currItemsAlloc_ , rf_ , h_ , r_ , totalWtR_ ) ; if ( ! asSketch ) { sketch . marks_ = this . marks_ ; sketch . numMarksInH_ = this . numMarksInH_ ; } if ( adjustedN >= 0 ) { sketch . n_ = adjustedN ; } return sketch ; }
Creates a copy of the sketch optionally discarding any information about marks that would indicate the class s use as a union gadget as opposed to a valid sketch .
146
32
31,915
void decreaseKBy1 ( ) { if ( k_ <= 1 ) { throw new SketchesStateException ( "Cannot decrease k below 1 in union" ) ; } if ( ( h_ == 0 ) && ( r_ == 0 ) ) { // exact mode, but no data yet; this reduction is somewhat gratuitous -- k_ ; } else if ( ( h_ > 0 ) && ( r_ == 0 ) ) { // exact mode, but we have some data -- k_ ; if ( h_ > k_ ) { transitionFromWarmup ( ) ; } } else if ( ( h_ > 0 ) && ( r_ > 0 ) ) { // reservoir mode, but we have some exact samples. // Our strategy will be to pull an item out of H (which we are allowed to do since it's // still just data), reduce k, and then re-insert the item // first, slide the R zone to the left by 1, temporarily filling the gap final int oldGapIdx = h_ ; final int oldFinalRIdx = ( h_ + 1 + r_ ) - 1 ; assert oldFinalRIdx == k_ ; swapValues ( oldFinalRIdx , oldGapIdx ) ; // now we pull an item out of H; any item is ok, but if we grab the rightmost and then // reduce h_, the heap invariant will be preserved (and the gap will be restored), plus // the push() of the item that will probably happen later will be cheap. final int pulledIdx = h_ - 1 ; final T pulledItem = data_ . get ( pulledIdx ) ; final double pulledWeight = weights_ . get ( pulledIdx ) ; final boolean pulledMark = marks_ . get ( pulledIdx ) ; if ( pulledMark ) { -- numMarksInH_ ; } weights_ . set ( pulledIdx , - 1.0 ) ; // to make bugs easier to spot -- h_ ; -- k_ ; -- n_ ; // will be re-incremented with the update update ( pulledItem , pulledWeight , pulledMark ) ; } else if ( ( h_ == 0 ) && ( r_ > 0 ) ) { // pure reservoir mode, so can simply eject a randomly chosen sample from the reservoir assert r_ >= 2 ; final int rIdxToDelete = 1 + SamplingUtil . rand . nextInt ( r_ ) ; // 1 for the gap final int rightmostRIdx = ( 1 + r_ ) - 1 ; swapValues ( rIdxToDelete , rightmostRIdx ) ; weights_ . set ( rightmostRIdx , - 1.0 ) ; -- k_ ; -- r_ ; } }
Decreases sketch s value of k by 1 updating stored values as needed .
576
15
31,916
public ArrayOfDoublesUpdatableSketch build ( final WritableMemory dstMem ) { return new DirectArrayOfDoublesQuickSelectSketch ( nomEntries_ , resizeFactor_ . lg ( ) , samplingProbability_ , numValues_ , seed_ , dstMem ) ; }
Returns an ArrayOfDoublesUpdatableSketch with the current configuration of this Builder .
66
20
31,917
public static int bytesToInt ( final byte [ ] arr ) { int v = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { v |= ( arr [ i ] & 0XFF ) << ( i * 8 ) ; } return v ; }
Returns an int extracted from a Little - Endian byte array .
59
13
31,918
public static long bytesToLong ( final byte [ ] arr ) { long v = 0 ; for ( int i = 0 ; i < 8 ; i ++ ) { v |= ( arr [ i ] & 0XFF L ) << ( i * 8 ) ; } return v ; }
Returns a long extracted from a Little - Endian byte array .
60
13
31,919
public static byte [ ] intToBytes ( int v , final byte [ ] arr ) { for ( int i = 0 ; i < 4 ; i ++ ) { arr [ i ] = ( byte ) ( v & 0XFF ) ; v >>>= 8 ; } return arr ; }
Returns a Little - Endian byte array extracted from the given int .
60
14
31,920
public static byte [ ] longToBytes ( long v , final byte [ ] arr ) { for ( int i = 0 ; i < 8 ; i ++ ) { arr [ i ] = ( byte ) ( v & 0XFF L ) ; v >>>= 8 ; } return arr ; }
Returns a Little - Endian byte array extracted from the given long .
61
14
31,921
public static String longToHexBytes ( final long v ) { final long mask = 0XFF L ; final StringBuilder sb = new StringBuilder ( ) ; for ( int i = 8 ; i -- > 0 ; ) { final String s = Long . toHexString ( ( v >>> ( i * 8 ) ) & mask ) ; sb . append ( zeroPad ( s , 2 ) ) . append ( " " ) ; } return sb . toString ( ) ; }
Returns a string of spaced hex bytes in Big - Endian order .
104
14
31,922
public static String bytesToString ( final byte [ ] arr , final boolean signed , final boolean littleEndian , final String sep ) { final StringBuilder sb = new StringBuilder ( ) ; final int mask = ( signed ) ? 0XFFFFFFFF : 0XFF ; final int arrLen = arr . length ; if ( littleEndian ) { for ( int i = 0 ; i < ( arrLen - 1 ) ; i ++ ) { sb . append ( arr [ i ] & mask ) . append ( sep ) ; } sb . append ( arr [ arrLen - 1 ] & mask ) ; } else { for ( int i = arrLen ; i -- > 1 ; ) { sb . append ( arr [ i ] & mask ) . append ( sep ) ; } sb . append ( arr [ 0 ] & mask ) ; } return sb . toString ( ) ; }
Returns a string view of a byte array
189
8
31,923
public static String nanoSecToString ( final long nS ) { final long rem_nS = ( long ) ( nS % 1000.0 ) ; final long rem_uS = ( long ) ( ( nS / 1000.0 ) % 1000.0 ) ; final long rem_mS = ( long ) ( ( nS / 1000000.0 ) % 1000.0 ) ; final long sec = ( long ) ( nS / 1000000000.0 ) ; final String nSstr = zeroPad ( Long . toString ( rem_nS ) , 3 ) ; final String uSstr = zeroPad ( Long . toString ( rem_uS ) , 3 ) ; final String mSstr = zeroPad ( Long . toString ( rem_mS ) , 3 ) ; return String . format ( "%d.%3s_%3s_%3s" , sec , mSstr , uSstr , nSstr ) ; }
Returns the given time in nanoseconds formatted as Sec . mSec uSec nSec
207
19
31,924
public static final String characterPad ( final String s , final int fieldLength , final char padChar , final boolean postpend ) { final char [ ] chArr = s . toCharArray ( ) ; final int sLen = chArr . length ; if ( sLen < fieldLength ) { final char [ ] out = new char [ fieldLength ] ; final int blanks = fieldLength - sLen ; if ( postpend ) { for ( int i = 0 ; i < sLen ; i ++ ) { out [ i ] = chArr [ i ] ; } for ( int i = sLen ; i < fieldLength ; i ++ ) { out [ i ] = padChar ; } } else { //prepend for ( int i = 0 ; i < blanks ; i ++ ) { out [ i ] = padChar ; } for ( int i = blanks ; i < fieldLength ; i ++ ) { out [ i ] = chArr [ i - blanks ] ; } } return String . valueOf ( out ) ; } return s ; }
Prepend or postpend the given string with the given character to fill the given field length . If the given string is equal or greater than the given field length it will be returned without modification .
227
39
31,925
public static short computeSeedHash ( final long seed ) { final long [ ] seedArr = { seed } ; final short seedHash = ( short ) ( ( hash ( seedArr , 0L ) [ 0 ] ) & 0xFFFF L ) ; if ( seedHash == 0 ) { throw new SketchesArgumentException ( "The given seed: " + seed + " produced a seedHash of zero. " + "You must choose a different seed." ) ; } return seedHash ; }
Computes and checks the 16 - bit seed hash from the given long seed . The seed hash may not be zero in order to maintain compatibility with older serialized versions that did not have this concept .
107
40
31,926
public static void checkIfMultipleOf8AndGT0 ( final long v , final String argName ) { if ( ( ( v & 0X7 L ) == 0L ) && ( v > 0L ) ) { return ; } throw new SketchesArgumentException ( "The value of the parameter \"" + argName + "\" must be a positive multiple of 8 and greater than zero: " + v ) ; }
Checks if parameter v is a multiple of 8 and greater than zero .
90
15
31,927
public static void checkIfPowerOf2 ( final int v , final String argName ) { if ( ( v > 0 ) && ( ( v & ( v - 1 ) ) == 0 ) ) { return ; } throw new SketchesArgumentException ( "The value of the parameter \"" + argName + "\" must be a positive integer-power of 2" + " and greater than 0: " + v ) ; }
Checks the given parameter to make sure it is positive an integer - power of 2 and greater than zero .
91
22
31,928
public static int toLog2 ( final int value , final String argName ) { checkIfPowerOf2 ( value , argName ) ; return Integer . numberOfTrailingZeros ( value ) ; }
Checks the given value if it is a power of 2 . If not it throws an exception . Otherwise returns the log - base2 of the given value .
43
32
31,929
public static int [ ] evenlyLgSpaced ( final int lgStart , final int lgEnd , final int points ) { if ( points <= 0 ) { throw new SketchesArgumentException ( "points must be > 0" ) ; } if ( ( lgEnd < 0 ) || ( lgStart < 0 ) ) { throw new SketchesArgumentException ( "lgStart and lgEnd must be >= 0." ) ; } final int [ ] out = new int [ points ] ; out [ 0 ] = 1 << lgStart ; if ( points == 1 ) { return out ; } final double delta = ( lgEnd - lgStart ) / ( points - 1.0 ) ; for ( int i = 1 ; i < points ; i ++ ) { final double mXpY = ( delta * i ) + lgStart ; out [ i ] = ( int ) round ( pow ( 2 , mXpY ) ) ; } return out ; }
Returns an int array of points that will be evenly spaced on a log axis . This is designed for Log_base2 numbers .
212
26
31,930
public static int simpleIntLog2 ( final int x ) { final int exp = Integer . numberOfTrailingZeros ( x ) ; if ( x != ( 1 << exp ) ) { throw new SketchesArgumentException ( "Argument x cannot be negative or zero." ) ; } return exp ; }
Gives the log2 of an integer that is known to be a power of 2 .
66
18
31,931
public static final int startingSubMultiple ( final int lgTarget , final ResizeFactor rf , final int lgMin ) { final int lgRF = rf . lg ( ) ; return ( lgTarget <= lgMin ) ? lgMin : ( lgRF == 0 ) ? lgTarget : ( ( lgTarget - lgMin ) % lgRF ) + lgMin ; }
Gets the smallest allowed exponent of 2 that it is a sub - multiple of the target by zero one or more resize factors .
90
26
31,932
public static UpdateSketch heapify ( final Memory srcMem , final long seed ) { final Family family = Family . idToFamily ( srcMem . getByte ( FAMILY_BYTE ) ) ; if ( family . equals ( Family . ALPHA ) ) { return HeapAlphaSketch . heapifyInstance ( srcMem , seed ) ; } return HeapQuickSelectSketch . heapifyInstance ( srcMem , seed ) ; }
Instantiates an on - heap UpdateSketch from Memory .
95
14
31,933
public UpdateReturnState update ( final String datum ) { if ( ( datum == null ) || datum . isEmpty ( ) ) { return RejectedNullOrEmpty ; } final byte [ ] data = datum . getBytes ( UTF_8 ) ; return hashUpdate ( hash ( data , getSeed ( ) ) [ 0 ] >>> 1 ) ; }
Present this sketch with the given String . The string is converted to a byte array using UTF8 encoding . If the string is null or empty no update attempt is made and the method returns .
77
38
31,934
public UpdateReturnState update ( final byte [ ] data ) { if ( ( data == null ) || ( data . length == 0 ) ) { return RejectedNullOrEmpty ; } return hashUpdate ( hash ( data , getSeed ( ) ) [ 0 ] >>> 1 ) ; }
Present this sketch with the given byte array . If the byte array is null or empty no update attempt is made and the method returns .
60
27
31,935
public static DoublesSketch heapify ( final Memory srcMem ) { if ( checkIsCompactMemory ( srcMem ) ) { return CompactDoublesSketch . heapify ( srcMem ) ; } return UpdateDoublesSketch . heapify ( srcMem ) ; }
Heapify takes the sketch image in Memory and instantiates an on - heap Sketch . The resulting sketch will not retain any link to the source Memory .
61
31
31,936
public static DoublesSketch wrap ( final Memory srcMem ) { if ( checkIsCompactMemory ( srcMem ) ) { return DirectCompactDoublesSketch . wrapInstance ( srcMem ) ; } return DirectUpdateDoublesSketchR . wrapInstance ( srcMem ) ; }
Wrap this sketch around the given Memory image of a DoublesSketch compact or non - compact .
64
22
31,937
public DoublesSketch downSample ( final DoublesSketch srcSketch , final int smallerK , final WritableMemory dstMem ) { return downSampleInternal ( srcSketch , smallerK , dstMem ) ; }
From an source sketch create a new sketch that must have a smaller value of K . The original sketch is not modified .
51
24
31,938
public void putMemory ( final WritableMemory dstMem , final boolean compact ) { if ( isDirect ( ) && ( isCompact ( ) == compact ) ) { final Memory srcMem = getMemory ( ) ; srcMem . copyTo ( 0 , dstMem , 0 , getStorageBytes ( ) ) ; } else { final byte [ ] byteArr = toByteArray ( compact ) ; final int arrLen = byteArr . length ; final long memCap = dstMem . getCapacity ( ) ; if ( memCap < arrLen ) { throw new SketchesArgumentException ( "Destination Memory not large enough: " + memCap + " < " + arrLen ) ; } dstMem . putByteArray ( 0 , byteArr , 0 , arrLen ) ; } }
Puts the current sketch into the given Memory if there is sufficient space otherwise throws an error .
169
19
31,939
public static long convertToPrecedingCummulative ( final long [ ] array ) { long subtotal = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) { final long newSubtotal = subtotal + array [ i ] ; array [ i ] = subtotal ; subtotal = newSubtotal ; } return subtotal ; }
Convert the weights into totals of the weights preceding each item
77
12
31,940
public static int chunkContainingPos ( final long [ ] arr , final long pos ) { final int nominalLength = arr . length - 1 ; /* remember, arr contains an "extra" position */ assert nominalLength > 0 ; final long n = arr [ nominalLength ] ; assert 0 <= pos ; assert pos < n ; final int l = 0 ; final int r = nominalLength ; // the following three asserts should probably be retained since they ensure // that the necessary invariants hold at the beginning of the search assert l < r ; assert arr [ l ] <= pos ; assert pos < arr [ r ] ; return searchForChunkContainingPos ( arr , pos , l , r ) ; }
This is written in terms of a plain array to facilitate testing .
145
13
31,941
public CompactSketch < S > getResult ( ) { if ( count_ == 0 ) { return new CompactSketch < S > ( null , null , theta_ , isEmpty_ ) ; } final CompactSketch < S > result = new CompactSketch < S > ( Arrays . copyOfRange ( keys_ , 0 , count_ ) , Arrays . copyOfRange ( summaries_ , 0 , count_ ) , theta_ , isEmpty_ ) ; reset ( ) ; return result ; }
Gets the result of this operation
114
7
31,942
static final < T > void validateValues ( final T [ ] values , final Comparator < ? super T > comparator ) { final int lenM1 = values . length - 1 ; for ( int j = 0 ; j < lenM1 ; j ++ ) { if ( ( values [ j ] != null ) && ( values [ j + 1 ] != null ) && ( comparator . compare ( values [ j ] , values [ j + 1 ] ) < 0 ) ) { continue ; } throw new SketchesArgumentException ( "Values must be unique, monotonically increasing and not null." ) ; } }
Checks the sequential validity of the given array of values . They must be unique monotonically increasing and not null .
131
24
31,943
PairTable rebuild ( final int newLgSizeInts ) { checkLgSizeInts ( newLgSizeInts ) ; final int newSize = 1 << newLgSizeInts ; final int oldSize = 1 << lgSizeInts ; rtAssert ( newSize > numPairs ) ; final int [ ] oldSlotsArr = slotsArr ; slotsArr = new int [ newSize ] ; Arrays . fill ( slotsArr , - 1 ) ; lgSizeInts = newLgSizeInts ; for ( int i = 0 ; i < oldSize ; i ++ ) { final int item = oldSlotsArr [ i ] ; if ( item != - 1 ) { mustInsert ( this , item ) ; } } return this ; }
Rebuilds to a larger size . NumItems and validBits remain unchanged .
172
17
31,944
static int [ ] unwrappingGetItems ( final PairTable table , final int numPairs ) { if ( numPairs < 1 ) { return null ; } final int [ ] slotsArr = table . slotsArr ; final int tableSize = 1 << table . lgSizeInts ; final int [ ] result = new int [ numPairs ] ; int i = 0 ; int l = 0 ; int r = numPairs - 1 ; // Special rules for the region before the first empty slot. final int hiBit = 1 << ( table . validBits - 1 ) ; while ( ( i < tableSize ) && ( slotsArr [ i ] != - 1 ) ) { final int item = slotsArr [ i ++ ] ; if ( ( item & hiBit ) != 0 ) { result [ r -- ] = item ; } // This item was probably wrapped, so move to end. else { result [ l ++ ] = item ; } } // The rest of the table is processed normally. while ( i < tableSize ) { final int look = slotsArr [ i ++ ] ; if ( look != - 1 ) { result [ l ++ ] = look ; } } assert l == ( r + 1 ) ; return result ; }
While extracting the items from a linear probing hashtable this will usually undo the wrap - around provided that the table isn t too full . Experiments suggest that for sufficiently large tables the load factor would have to be over 90 percent before this would fail frequently and even then the subsequent sort would fix things up .
266
61
31,945
static void introspectiveInsertionSort ( final int [ ] a , final int l , final int r ) { final int length = ( r - l ) + 1 ; long cost = 0 ; final long costLimit = 8L * length ; for ( int i = l + 1 ; i <= r ; i ++ ) { int j = i ; final long v = a [ i ] & 0XFFFF_FFFF L ; //v must be long while ( ( j >= ( l + 1 ) ) && ( v < ( ( a [ j - 1 ] ) & 0XFFFF_FFFF L ) ) ) { a [ j ] = a [ j - 1 ] ; j -= 1 ; } a [ j ] = ( int ) v ; cost += ( i - j ) ; // distance moved is a measure of work if ( cost > costLimit ) { //we need an unsigned sort, but it is linear time and very rarely occurs final long [ ] b = new long [ a . length ] ; for ( int m = 0 ; m < a . length ; m ++ ) { b [ m ] = a [ m ] & 0XFFFF_FFFF L ; } Arrays . sort ( b , l , r + 1 ) ; for ( int m = 0 ; m < a . length ; m ++ ) { a [ m ] = ( int ) b [ m ] ; } // The following sanity check can be used during development //int bad = 0; //for (int m = l; m < (r - 1); m++) { // final long b1 = a[m] & 0XFFFF_FFFFL; // final long b2 = a[m + 1] & 0XFFFF_FFFFL; // if (b1 > b2) { bad++; } //} //assert (bad == 0); return ; } } // The following sanity check can be used during development // int bad = 0; // for (int m = l; m < (r - 1); m++) { // final long b1 = a[m] & 0XFFFF_FFFFL; // final long b2 = a[m + 1] & 0XFFFF_FFFFL; // if (b1 > b2) { bad++; } // } // assert (bad == 0); }
In applications where the input array is already nearly sorted insertion sort runs in linear time with a very small constant . This introspective version of insertion sort protects against the quadratic cost of sorting bad input arrays . It keeps track of how much work has been done and if that exceeds a constant times the array length it switches to a different sorting algorithm .
486
70
31,946
public double update ( final byte [ ] key , final byte [ ] identifier ) { if ( key == null ) { return Double . NaN ; } checkMethodKeySize ( key ) ; if ( identifier == null ) { return getEstimate ( key ) ; } final short coupon = ( short ) Map . coupon16 ( identifier ) ; final int baseMapIndex = maps_ [ 0 ] . findOrInsertKey ( key ) ; final double baseMapEstimate = maps_ [ 0 ] . update ( baseMapIndex , coupon ) ; if ( baseMapEstimate > 0 ) { return baseMapEstimate ; } final int level = - ( int ) baseMapEstimate ; // base map is level 0 if ( level == 0 ) { return promote ( key , coupon , maps_ [ 0 ] , baseMapIndex , level , baseMapIndex , 0 ) ; } final Map map = maps_ [ level ] ; final int index = map . findOrInsertKey ( key ) ; final double estimate = map . update ( index , coupon ) ; if ( estimate > 0 ) { return estimate ; } return promote ( key , coupon , map , index , level , baseMapIndex , - estimate ) ; }
Updates the map with a given key and identifier and returns the estimate of the number of unique identifiers encountered so far for the given key .
252
28
31,947
public double getEstimate ( final byte [ ] key ) { if ( key == null ) { return Double . NaN ; } checkMethodKeySize ( key ) ; final double est = maps_ [ 0 ] . getEstimate ( key ) ; if ( est >= 0.0 ) { return est ; } //key has been promoted final int level = - ( int ) est ; final Map map = maps_ [ level ] ; return map . getEstimate ( key ) ; }
Retrieves the current estimate of unique count for a given key .
101
14
31,948
public long getMemoryUsageBytes ( ) { long total = 0 ; for ( int i = 0 ; i < maps_ . length ; i ++ ) { if ( maps_ [ i ] != null ) { total += maps_ [ i ] . getMemoryUsageBytes ( ) ; } } return total ; }
Returns total bytes used by all internal maps
64
8
31,949
public long getKeyMemoryUsageBytes ( ) { long total = 0 ; for ( int i = 0 ; i < maps_ . length ; i ++ ) { if ( maps_ [ i ] != null ) { total += ( long ) ( maps_ [ i ] . getActiveEntries ( ) ) * keySizeBytes_ ; } } return total ; }
Returns total bytes used for key storage
75
7
31,950
int getActiveMaps ( ) { int levels = 0 ; final int iMapsLen = maps_ . length ; for ( int i = 0 ; i < iMapsLen ; i ++ ) { if ( maps_ [ i ] != null ) { levels ++ ; } } return levels ; }
Returns the number of active internal maps so far . Only the base map is initialized in the constructor so this method would return 1 . As more keys are promoted up to higher level maps the return value would grow until the last level HLL map is allocated .
60
51
31,951
private boolean propagateToSharedSketch ( final long hash ) { //noinspection StatementWithEmptyBody while ( localPropagationInProgress . get ( ) ) { } //busy wait until previous propagation completed localPropagationInProgress . set ( true ) ; final boolean res = shared . propagate ( localPropagationInProgress , null , hash ) ; //in this case the parent empty_ and curCount_ were not touched thetaLong_ = shared . getVolatileTheta ( ) ; return res ; }
Propagates a single hash value to the shared sketch
112
11
31,952
private void propagateToSharedSketch ( ) { //noinspection StatementWithEmptyBody while ( localPropagationInProgress . get ( ) ) { } //busy wait until previous propagation completed final CompactSketch compactSketch = compact ( propagateOrderedCompact , null ) ; localPropagationInProgress . set ( true ) ; shared . propagate ( localPropagationInProgress , compactSketch , ConcurrentSharedThetaSketch . NOT_SINGLE_HASH ) ; super . reset ( ) ; thetaLong_ = shared . getVolatileTheta ( ) ; }
Propagates the content of the buffer as a sketch to the shared sketch
134
15
31,953
private int countValidLevelsBelow ( final int tgtLvl ) { int count = 0 ; long bitPattern = ds_ . getBitPattern ( ) ; for ( int i = 0 ; ( i < tgtLvl ) && ( bitPattern > 0 ) ; ++ i , bitPattern >>>= 1 ) { if ( ( bitPattern & 1L ) > 0L ) { ++ count ; } } return count ; // shorter implementation, testing suggests a tiny bit slower //final long mask = (1 << tgtLvl) - 1; //return Long.bitCount(ds_.getBitPattern() & mask); }
Counts number of full levels in the sketch below tgtLvl . Useful for computing the level offset in a compact sketch .
133
26
31,954
static void checkFamilyID ( final int familyID ) { final Family family = Family . idToFamily ( familyID ) ; if ( ! family . equals ( Family . QUANTILES ) ) { throw new SketchesArgumentException ( "Possible corruption: Invalid Family: " + family . toString ( ) ) ; } }
Checks the validity of the given family ID
71
9
31,955
static boolean checkPreLongsFlagsCap ( final int preambleLongs , final int flags , final long memCapBytes ) { final boolean empty = ( flags & EMPTY_FLAG_MASK ) > 0 ; //Preamble flags empty state final int minPre = Family . QUANTILES . getMinPreLongs ( ) ; //1 final int maxPre = Family . QUANTILES . getMaxPreLongs ( ) ; //2 final boolean valid = ( ( preambleLongs == minPre ) && empty ) || ( ( preambleLongs == maxPre ) && ! empty ) ; if ( ! valid ) { throw new SketchesArgumentException ( "Possible corruption: PreambleLongs inconsistent with empty state: " + preambleLongs ) ; } checkHeapFlags ( flags ) ; if ( memCapBytes < ( preambleLongs << 3 ) ) { throw new SketchesArgumentException ( "Possible corruption: Insufficient capacity for preamble: " + memCapBytes ) ; } return empty ; }
Checks the consistency of the flag bits and the state of preambleLong and the memory capacity and returns the empty state .
231
26
31,956
static void checkHeapFlags ( final int flags ) { //only used by checkPreLongsFlagsCap and test final int allowedFlags = READ_ONLY_FLAG_MASK | EMPTY_FLAG_MASK | COMPACT_FLAG_MASK | ORDERED_FLAG_MASK ; final int flagsMask = ~ allowedFlags ; if ( ( flags & flagsMask ) > 0 ) { throw new SketchesArgumentException ( "Possible corruption: Invalid flags field: " + Integer . toBinaryString ( flags ) ) ; } }
Checks just the flags field of the preamble . Allowed flags are Read Only Empty Compact and ordered .
117
23
31,957
static boolean checkIsCompactMemory ( final Memory srcMem ) { // only reading so downcast is ok final int flags = extractFlags ( srcMem ) ; final int compactFlags = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK ; return ( flags & compactFlags ) > 0 ; }
Checks just the flags field of an input Memory object . Returns true for a compact sketch false for an update sketch . Does not perform additional checks including sketch family .
67
33
31,958
static final void checkSplitPointsOrder ( final double [ ] values ) { if ( values == null ) { throw new SketchesArgumentException ( "Values cannot be null." ) ; } final int lenM1 = values . length - 1 ; for ( int j = 0 ; j < lenM1 ; j ++ ) { if ( values [ j ] < values [ j + 1 ] ) { continue ; } throw new SketchesArgumentException ( "Values must be unique, monotonically increasing and not NaN." ) ; } }
Checks the sequential validity of the given array of double values . They must be unique monotonically increasing and not NaN .
115
26
31,959
static int computeRetainedItems ( final int k , final long n ) { final int bbCnt = computeBaseBufferItems ( k , n ) ; final long bitPattern = computeBitPattern ( k , n ) ; final int validLevels = computeValidLevels ( bitPattern ) ; return bbCnt + ( validLevels * k ) ; }
Returns the number of retained valid items in the sketch given k and n .
77
15
31,960
static int lowLevelCompressBytes ( final byte [ ] byteArray , // input final int numBytesToEncode , // input, must be an int final short [ ] encodingTable , // input final int [ ] compressedWords ) { // output int nextWordIndex = 0 ; long bitBuf = 0 ; // bits are packed into this first, then are flushed to compressedWords int bufBits = 0 ; // number of bits currently in bitbuf; must be between 0 and 31 for ( int byteIndex = 0 ; byteIndex < numBytesToEncode ; byteIndex ++ ) { final int theByte = byteArray [ byteIndex ] & 0XFF ; final long codeInfo = ( encodingTable [ theByte ] & 0XFFFF L ) ; final long codeVal = codeInfo & 0XFFF L ; final int codeWordLength = ( int ) ( codeInfo >>> 12 ) ; bitBuf |= ( codeVal << bufBits ) ; bufBits += codeWordLength ; //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); if ( bufBits >= 32 ) { compressedWords [ nextWordIndex ++ ] = ( int ) bitBuf ; bitBuf >>>= 32 ; bufBits -= 32 ; } } //Pad the bitstream with 11 zero-bits so that the decompressor's 12-bit peek // can't overrun its input. bufBits += 11 ; //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); if ( bufBits >= 32 ) { compressedWords [ nextWordIndex ++ ] = ( int ) bitBuf ; bitBuf >>>= 32 ; bufBits -= 32 ; } if ( bufBits > 0 ) { // We are done encoding now, so we flush the bit buffer. assert ( bufBits < 32 ) ; compressedWords [ nextWordIndex ++ ] = ( int ) bitBuf ; } return nextWordIndex ; }
It is the caller s responsibility to ensure that the compressedWords array is long enough .
417
17
31,961
private static int [ ] uncompressTheSurprisingValues ( final CompressedState source ) { final int srcK = 1 << source . lgK ; final int numPairs = source . numCsv ; assert numPairs > 0 ; final int [ ] pairs = new int [ numPairs ] ; final int numBaseBits = CpcCompression . golombChooseNumberOfBaseBits ( srcK + numPairs , numPairs ) ; lowLevelUncompressPairs ( pairs , numPairs , numBaseBits , source . csvStream , source . csvLengthInts ) ; return pairs ; }
the length of this array is known to the source sketch .
136
12
31,962
private static int [ ] trickyGetPairsFromWindow ( final byte [ ] window , final int k , final int numPairsToGet , final int emptySpace ) { final int outputLength = emptySpace + numPairsToGet ; final int [ ] pairs = new int [ outputLength ] ; int rowIndex = 0 ; int pairIndex = emptySpace ; for ( rowIndex = 0 ; rowIndex < k ; rowIndex ++ ) { int wByte = window [ rowIndex ] & 0XFF ; while ( wByte != 0 ) { final int colIndex = Integer . numberOfTrailingZeros ( wByte ) ; // assert (colIndex < 8); wByte ^= ( 1 << colIndex ) ; // erase the 1 pairs [ pairIndex ++ ] = ( rowIndex << 6 ) | colIndex ; } } assert ( pairIndex == outputLength ) ; return ( pairs ) ; }
will be filled in later by the caller .
190
9
31,963
private static void compressHybridFlavor ( final CompressedState target , final CpcSketch source ) { final int srcK = 1 << source . lgK ; final PairTable srcPairTable = source . pairTable ; final int srcNumPairs = srcPairTable . getNumPairs ( ) ; final int [ ] srcPairArr = PairTable . unwrappingGetItems ( srcPairTable , srcNumPairs ) ; introspectiveInsertionSort ( srcPairArr , 0 , srcNumPairs - 1 ) ; final byte [ ] srcSlidingWindow = source . slidingWindow ; final int srcWindowOffset = source . windowOffset ; final long srcNumCoupons = source . numCoupons ; assert ( srcSlidingWindow != null ) ; assert ( srcWindowOffset == 0 ) ; final long numPairs = srcNumCoupons - srcNumPairs ; // because the window offset is zero assert numPairs < Integer . MAX_VALUE ; final int numPairsFromArray = ( int ) numPairs ; assert ( numPairsFromArray + srcNumPairs ) == srcNumCoupons ; //for test final int [ ] allPairs = trickyGetPairsFromWindow ( srcSlidingWindow , srcK , numPairsFromArray , srcNumPairs ) ; PairTable . merge ( srcPairArr , 0 , srcNumPairs , allPairs , srcNumPairs , numPairsFromArray , allPairs , 0 ) ; // note the overlapping subarray trick //FOR TESTING If needed // for (int i = 0; i < (source.numCoupons - 1); i++) { // assert (Integer.compareUnsigned(allPairs[i], allPairs[i + 1]) < 0); } compressTheSurprisingValues ( target , source , allPairs , ( int ) srcNumCoupons ) ; }
of a Pinned sketch before compressing it . Hence the name Hybrid .
417
15
31,964
private static void compressSlidingFlavor ( final CompressedState target , final CpcSketch source ) { compressTheWindow ( target , source ) ; final PairTable srcPairTable = source . pairTable ; final int numPairs = srcPairTable . getNumPairs ( ) ; if ( numPairs > 0 ) { final int [ ] pairs = PairTable . unwrappingGetItems ( srcPairTable , numPairs ) ; // Here we apply a complicated transformation to the column indices, which // changes the implied ordering of the pairs, so we must do it before sorting. final int pseudoPhase = determinePseudoPhase ( source . lgK , source . numCoupons ) ; // NB assert ( pseudoPhase < 16 ) ; final byte [ ] permutation = columnPermutationsForEncoding [ pseudoPhase ] ; final int offset = source . windowOffset ; assert ( ( offset > 0 ) && ( offset <= 56 ) ) ; for ( int i = 0 ; i < numPairs ; i ++ ) { final int rowCol = pairs [ i ] ; final int row = rowCol >>> 6 ; int col = ( rowCol & 63 ) ; // first rotate the columns into a canonical configuration: // new = ((old - (offset+8)) + 64) mod 64 col = ( ( col + 56 ) - offset ) & 63 ; assert ( col >= 0 ) && ( col < 56 ) ; // then apply the permutation col = permutation [ col ] ; pairs [ i ] = ( row << 6 ) | col ; } introspectiveInsertionSort ( pairs , 0 , numPairs - 1 ) ; compressTheSurprisingValues ( target , source , pairs , numPairs ) ; } }
Complicated by the existence of both a left fringe and a right fringe .
369
15
31,965
public void update ( final float value ) { if ( Float . isNaN ( value ) ) { return ; } if ( isEmpty ( ) ) { minValue_ = value ; maxValue_ = value ; } else { if ( value < minValue_ ) { minValue_ = value ; } if ( value > maxValue_ ) { maxValue_ = value ; } } if ( levels_ [ 0 ] == 0 ) { compressWhileUpdating ( ) ; } n_ ++ ; isLevelZeroSorted_ = false ; final int nextPos = levels_ [ 0 ] - 1 ; assert levels_ [ 0 ] >= 0 ; levels_ [ 0 ] = nextPos ; items_ [ nextPos ] = value ; }
Updates this sketch with the given data item .
153
10
31,966
public void merge ( final KllFloatsSketch other ) { if ( ( other == null ) || other . isEmpty ( ) ) { return ; } if ( m_ != other . m_ ) { throw new SketchesArgumentException ( "incompatible M: " + m_ + " and " + other . m_ ) ; } final long finalN = n_ + other . n_ ; for ( int i = other . levels_ [ 0 ] ; i < other . levels_ [ 1 ] ; i ++ ) { update ( other . items_ [ i ] ) ; } if ( other . numLevels_ >= 2 ) { mergeHigherLevels ( other , finalN ) ; } if ( Float . isNaN ( minValue_ ) || ( other . minValue_ < minValue_ ) ) { minValue_ = other . minValue_ ; } if ( Float . isNaN ( maxValue_ ) || ( other . maxValue_ > maxValue_ ) ) { maxValue_ = other . maxValue_ ; } n_ = finalN ; assertCorrectTotalWeight ( ) ; if ( other . isEstimationMode ( ) ) { minK_ = min ( minK_ , other . minK_ ) ; } }
Merges another sketch into this one .
269
8
31,967
public float getQuantile ( final double fraction ) { if ( isEmpty ( ) ) { return Float . NaN ; } if ( fraction == 0.0 ) { return minValue_ ; } if ( fraction == 1.0 ) { return maxValue_ ; } if ( ( fraction < 0.0 ) || ( fraction > 1.0 ) ) { throw new SketchesArgumentException ( "Fraction cannot be less than zero or greater than 1.0" ) ; } final KllFloatsQuantileCalculator quant = getQuantileCalculator ( ) ; return quant . getQuantile ( fraction ) ; }
Returns an approximation to the value of the data item that would be preceded by the given fraction of a hypothetical sorted version of the input stream so far .
134
30
31,968
public static int getKFromEpsilon ( final double epsilon , final boolean pmf ) { //Ensure that eps is >= than the lowest possible eps given MAX_K and pmf=false. final double eps = max ( epsilon , 4.7634E-5 ) ; final double kdbl = pmf ? exp ( log ( 2.446 / eps ) / 0.9433 ) : exp ( log ( 2.296 / eps ) / 0.9723 ) ; final double krnd = round ( kdbl ) ; final double del = abs ( krnd - kdbl ) ; final int k = ( int ) ( ( del < 1E-6 ) ? krnd : ceil ( kdbl ) ) ; return max ( MIN_K , min ( MAX_K , k ) ) ; }
thousands of trials
187
4
31,969
public byte [ ] toByteArray ( ) { final byte [ ] bytes = new byte [ getSerializedSizeBytes ( ) ] ; final boolean isSingleItem = n_ == 1 ; bytes [ PREAMBLE_INTS_BYTE ] = ( byte ) ( isEmpty ( ) || isSingleItem ? PREAMBLE_INTS_SHORT : PREAMBLE_INTS_FULL ) ; bytes [ SER_VER_BYTE ] = isSingleItem ? serialVersionUID2 : serialVersionUID1 ; bytes [ FAMILY_BYTE ] = ( byte ) Family . KLL . getID ( ) ; bytes [ FLAGS_BYTE ] = ( byte ) ( ( isEmpty ( ) ? 1 << Flags . IS_EMPTY . ordinal ( ) : 0 ) | ( isLevelZeroSorted_ ? 1 << Flags . IS_LEVEL_ZERO_SORTED . ordinal ( ) : 0 ) | ( isSingleItem ? 1 << Flags . IS_SINGLE_ITEM . ordinal ( ) : 0 ) ) ; ByteArrayUtil . putShortLE ( bytes , K_SHORT , ( short ) k_ ) ; bytes [ M_BYTE ] = ( byte ) m_ ; if ( isEmpty ( ) ) { return bytes ; } int offset = DATA_START_SINGLE_ITEM ; if ( ! isSingleItem ) { ByteArrayUtil . putLongLE ( bytes , N_LONG , n_ ) ; ByteArrayUtil . putShortLE ( bytes , MIN_K_SHORT , ( short ) minK_ ) ; bytes [ NUM_LEVELS_BYTE ] = ( byte ) numLevels_ ; offset = DATA_START ; // the last integer in levels_ is not serialized because it can be derived for ( int i = 0 ; i < numLevels_ ; i ++ ) { ByteArrayUtil . putIntLE ( bytes , offset , levels_ [ i ] ) ; offset += Integer . BYTES ; } ByteArrayUtil . putFloatLE ( bytes , offset , minValue_ ) ; offset += Float . BYTES ; ByteArrayUtil . putFloatLE ( bytes , offset , maxValue_ ) ; offset += Float . BYTES ; } final int numItems = getNumRetained ( ) ; for ( int i = 0 ; i < numItems ; i ++ ) { ByteArrayUtil . putFloatLE ( bytes , offset , items_ [ levels_ [ 0 ] + i ] ) ; offset += Float . BYTES ; } return bytes ; }
Returns serialized sketch in a byte array form .
556
10
31,970
public static KllFloatsSketch heapify ( final Memory mem ) { final int preambleInts = mem . getByte ( PREAMBLE_INTS_BYTE ) & 0xff ; final int serialVersion = mem . getByte ( SER_VER_BYTE ) & 0xff ; final int family = mem . getByte ( FAMILY_BYTE ) & 0xff ; final int flags = mem . getByte ( FLAGS_BYTE ) & 0xff ; final int m = mem . getByte ( M_BYTE ) & 0xff ; if ( m != DEFAULT_M ) { throw new SketchesArgumentException ( "Possible corruption: M must be " + DEFAULT_M + ": " + m ) ; } final boolean isEmpty = ( flags & ( 1 << Flags . IS_EMPTY . ordinal ( ) ) ) > 0 ; final boolean isSingleItem = ( flags & ( 1 << Flags . IS_SINGLE_ITEM . ordinal ( ) ) ) > 0 ; if ( isEmpty || isSingleItem ) { if ( preambleInts != PREAMBLE_INTS_SHORT ) { throw new SketchesArgumentException ( "Possible corruption: preambleInts must be " + PREAMBLE_INTS_SHORT + " for an empty or single item sketch: " + preambleInts ) ; } } else { if ( preambleInts != PREAMBLE_INTS_FULL ) { throw new SketchesArgumentException ( "Possible corruption: preambleInts must be " + PREAMBLE_INTS_FULL + " for a sketch with more than one item: " + preambleInts ) ; } } if ( ( serialVersion != serialVersionUID1 ) && ( serialVersion != serialVersionUID2 ) ) { throw new SketchesArgumentException ( "Possible corruption: serial version mismatch: expected " + serialVersionUID1 + " or " + serialVersionUID2 + ", got " + serialVersion ) ; } if ( family != Family . KLL . getID ( ) ) { throw new SketchesArgumentException ( "Possible corruption: family mismatch: expected " + Family . KLL . getID ( ) + ", got " + family ) ; } return new KllFloatsSketch ( mem ) ; }
Heapify takes the sketch image in Memory and instantiates an on - heap sketch . The resulting sketch will not retain any link to the source Memory .
514
31
31,971
static void checkK ( final int k ) { if ( ( k < MIN_K ) || ( k > MAX_K ) ) { throw new SketchesArgumentException ( "K must be >= " + MIN_K + " and <= " + MAX_K + ": " + k ) ; } }
Checks the validity of the given value k
67
9
31,972
private void compressWhileUpdating ( ) { final int level = findLevelToCompact ( ) ; // It is important to do add the new top level right here. Be aware that this operation // grows the buffer and shifts the data and also the boundaries of the data and grows the // levels array and increments numLevels_ if ( level == ( numLevels_ - 1 ) ) { addEmptyTopLevelToCompletelyFullSketch ( ) ; } final int rawBeg = levels_ [ level ] ; final int rawLim = levels_ [ level + 1 ] ; // +2 is OK because we already added a new top level if necessary final int popAbove = levels_ [ level + 2 ] - rawLim ; final int rawPop = rawLim - rawBeg ; final boolean oddPop = KllHelper . isOdd ( rawPop ) ; final int adjBeg = oddPop ? rawBeg + 1 : rawBeg ; final int adjPop = oddPop ? rawPop - 1 : rawPop ; final int halfAdjPop = adjPop / 2 ; // level zero might not be sorted, so we must sort it if we wish to compact it if ( level == 0 ) { Arrays . sort ( items_ , adjBeg , adjBeg + adjPop ) ; } if ( popAbove == 0 ) { KllHelper . randomlyHalveUp ( items_ , adjBeg , adjPop ) ; } else { KllHelper . randomlyHalveDown ( items_ , adjBeg , adjPop ) ; KllHelper . mergeSortedArrays ( items_ , adjBeg , halfAdjPop , items_ , rawLim , popAbove , items_ , adjBeg + halfAdjPop ) ; } levels_ [ level + 1 ] -= halfAdjPop ; // adjust boundaries of the level above if ( oddPop ) { levels_ [ level ] = levels_ [ level + 1 ] - 1 ; // the current level now contains one item items_ [ levels_ [ level ] ] = items_ [ rawBeg ] ; // namely this leftover guy } else { levels_ [ level ] = levels_ [ level + 1 ] ; // the current level is now empty } // verify that we freed up halfAdjPop array slots just below the current level assert levels_ [ level ] == ( rawBeg + halfAdjPop ) ; // finally, we need to shift up the data in the levels below // so that the freed-up space can be used by level zero if ( level > 0 ) { final int amount = rawBeg - levels_ [ 0 ] ; System . arraycopy ( items_ , levels_ [ 0 ] , items_ , levels_ [ 0 ] + halfAdjPop , amount ) ; for ( int lvl = 0 ; lvl < level ; lvl ++ ) { levels_ [ lvl ] += halfAdjPop ; } } }
It cannot be used while merging while reducing k or anything else .
599
13
31,973
public CompactDoublesSketch compact ( final WritableMemory dstMem ) { if ( dstMem == null ) { return HeapCompactDoublesSketch . createFromUpdateSketch ( this ) ; } return DirectCompactDoublesSketch . createFromUpdateSketch ( this , dstMem ) ; }
Returns a compact version of this sketch . If passing in a Memory object the compact sketch will use that direct memory ; otherwise an on - heap sketch will be returned .
71
33
31,974
public static < T > ItemsSketch < T > getInstance ( final Comparator < ? super T > comparator ) { return getInstance ( PreambleUtil . DEFAULT_K , comparator ) ; }
Obtains a new instance of an ItemsSketch using the DEFAULT_K .
47
18
31,975
public static < T > ItemsSketch < T > getInstance ( final int k , final Comparator < ? super T > comparator ) { final ItemsSketch < T > qs = new ItemsSketch <> ( k , comparator ) ; final int bufAlloc = 2 * Math . min ( DoublesSketch . MIN_K , k ) ; //the min is important qs . n_ = 0 ; qs . combinedBufferItemCapacity_ = bufAlloc ; qs . combinedBuffer_ = new Object [ bufAlloc ] ; qs . baseBufferCount_ = 0 ; qs . bitPattern_ = 0 ; qs . minValue_ = null ; qs . maxValue_ = null ; return qs ; }
Obtains a new instance of an ItemsSketch .
165
12
31,976
public static < T > ItemsSketch < T > getInstance ( final Memory srcMem , final Comparator < ? super T > comparator , final ArrayOfItemsSerDe < T > serDe ) { final long memCapBytes = srcMem . getCapacity ( ) ; if ( memCapBytes < 8 ) { throw new SketchesArgumentException ( "Memory too small: " + memCapBytes ) ; } final int preambleLongs = extractPreLongs ( srcMem ) ; final int serVer = extractSerVer ( srcMem ) ; final int familyID = extractFamilyID ( srcMem ) ; final int flags = extractFlags ( srcMem ) ; final int k = extractK ( srcMem ) ; ItemsUtil . checkItemsSerVer ( serVer ) ; if ( ( serVer == 3 ) && ( ( flags & COMPACT_FLAG_MASK ) == 0 ) ) { throw new SketchesArgumentException ( "Non-compact Memory images are not supported." ) ; } final boolean empty = Util . checkPreLongsFlagsCap ( preambleLongs , flags , memCapBytes ) ; Util . checkFamilyID ( familyID ) ; final ItemsSketch < T > qs = getInstance ( k , comparator ) ; //checks k if ( empty ) { return qs ; } //Not empty, must have valid preamble + min, max final long n = extractN ( srcMem ) ; //can't check memory capacity here, not enough information final int extra = 2 ; //for min, max final int numMemItems = Util . computeRetainedItems ( k , n ) + extra ; //set class members qs . n_ = n ; qs . combinedBufferItemCapacity_ = Util . computeCombinedBufferItemCapacity ( k , n ) ; qs . baseBufferCount_ = computeBaseBufferItems ( k , n ) ; qs . bitPattern_ = computeBitPattern ( k , n ) ; qs . combinedBuffer_ = new Object [ qs . combinedBufferItemCapacity_ ] ; final int srcMemItemsOffsetBytes = preambleLongs * Long . BYTES ; final Memory mReg = srcMem . region ( srcMemItemsOffsetBytes , srcMem . getCapacity ( ) - srcMemItemsOffsetBytes ) ; final T [ ] itemsArray = serDe . deserializeFromMemory ( mReg , numMemItems ) ; qs . itemsArrayToCombinedBuffer ( itemsArray ) ; return qs ; }
Heapifies the given srcMem which must be a Memory image of a ItemsSketch
544
19
31,977
static < T > ItemsSketch < T > copy ( final ItemsSketch < T > sketch ) { final ItemsSketch < T > qsCopy = ItemsSketch . getInstance ( sketch . k_ , sketch . comparator_ ) ; qsCopy . n_ = sketch . n_ ; qsCopy . minValue_ = sketch . getMinValue ( ) ; qsCopy . maxValue_ = sketch . getMaxValue ( ) ; qsCopy . combinedBufferItemCapacity_ = sketch . getCombinedBufferAllocatedCount ( ) ; qsCopy . baseBufferCount_ = sketch . getBaseBufferCount ( ) ; qsCopy . bitPattern_ = sketch . getBitPattern ( ) ; final Object [ ] combBuf = sketch . getCombinedBuffer ( ) ; qsCopy . combinedBuffer_ = Arrays . copyOf ( combBuf , combBuf . length ) ; return qsCopy ; }
Returns a copy of the given sketch
205
7
31,978
public void update ( final T dataItem ) { // this method only uses the base buffer part of the combined buffer if ( dataItem == null ) { return ; } if ( ( maxValue_ == null ) || ( comparator_ . compare ( dataItem , maxValue_ ) > 0 ) ) { maxValue_ = dataItem ; } if ( ( minValue_ == null ) || ( comparator_ . compare ( dataItem , minValue_ ) < 0 ) ) { minValue_ = dataItem ; } if ( ( baseBufferCount_ + 1 ) > combinedBufferItemCapacity_ ) { ItemsSketch . growBaseBuffer ( this ) ; } combinedBuffer_ [ baseBufferCount_ ++ ] = dataItem ; n_ ++ ; if ( baseBufferCount_ == ( 2 * k_ ) ) { ItemsUtil . processFullBaseBuffer ( this ) ; } }
Updates this sketch with the given double data item
187
10
31,979
public T getQuantileUpperBound ( final double fraction ) { return getQuantile ( min ( 1.0 , fraction + Util . getNormalizedRankError ( k_ , false ) ) ) ; }
Gets the upper bound of the value interval in which the true quantile of the given rank exists with a confidence of at least 99% .
45
29
31,980
public T getQuantileLowerBound ( final double fraction ) { return getQuantile ( max ( 0 , fraction - Util . getNormalizedRankError ( k_ , false ) ) ) ; }
Gets the lower bound of the value interval in which the true quantile of the given rank exists with a confidence of at least 99% .
42
29
31,981
public void reset ( ) { n_ = 0 ; combinedBufferItemCapacity_ = 2 * Math . min ( DoublesSketch . MIN_K , k_ ) ; //the min is important combinedBuffer_ = new Object [ combinedBufferItemCapacity_ ] ; baseBufferCount_ = 0 ; bitPattern_ = 0 ; minValue_ = null ; maxValue_ = null ; }
Resets this sketch to a virgin state but retains the original value of k .
84
16
31,982
public ItemsSketch < T > downSample ( final int newK ) { final ItemsSketch < T > newSketch = ItemsSketch . getInstance ( newK , comparator_ ) ; ItemsMergeImpl . downSamplingMergeInto ( this , newSketch ) ; return newSketch ; }
From an existing sketch this creates a new sketch that can have a smaller value of K . The original sketch is not modified .
74
25
31,983
public void putMemory ( final WritableMemory dstMem , final ArrayOfItemsSerDe < T > serDe ) { final byte [ ] byteArr = toByteArray ( serDe ) ; final long memCap = dstMem . getCapacity ( ) ; if ( memCap < byteArr . length ) { throw new SketchesArgumentException ( "Destination Memory not large enough: " + memCap + " < " + byteArr . length ) ; } dstMem . putByteArray ( 0 , byteArr , 0 , byteArr . length ) ; }
Puts the current sketch into the given Memory if there is sufficient space . Otherwise throws an error .
124
20
31,984
private void itemsArrayToCombinedBuffer ( final T [ ] itemsArray ) { final int extra = 2 ; // space for min and max values //Load min, max minValue_ = itemsArray [ 0 ] ; maxValue_ = itemsArray [ 1 ] ; //Load base buffer System . arraycopy ( itemsArray , extra , combinedBuffer_ , 0 , baseBufferCount_ ) ; //Load levels long bits = bitPattern_ ; if ( bits > 0 ) { int index = extra + baseBufferCount_ ; for ( int level = 0 ; bits != 0L ; level ++ , bits >>>= 1 ) { if ( ( bits & 1L ) > 0L ) { System . arraycopy ( itemsArray , index , combinedBuffer_ , ( 2 + level ) * k_ , k_ ) ; index += k_ ; } } } }
Loads the Combined Buffer min and max from the given items array . The Combined Buffer is always in non - compact form and must be pre - allocated .
178
31
31,985
private void scanAllAsearchB ( ) { final long [ ] scanAArr = a_ . getCache ( ) ; final int arrLongsIn = scanAArr . length ; cache_ = new long [ arrLongsIn ] ; for ( int i = 0 ; i < arrLongsIn ; i ++ ) { final long hashIn = scanAArr [ i ] ; if ( ( hashIn <= 0L ) || ( hashIn >= thetaLong_ ) ) { continue ; } final int foundIdx = hashSearch ( bHashTable_ , lgArrLongsHT_ , hashIn ) ; if ( foundIdx > - 1 ) { continue ; } cache_ [ curCount_ ++ ] = hashIn ; } }
Sketch A is either unordered compact or hash table
162
12
31,986
public static double approximateLowerBoundOnP ( final long n , final long k , final double numStdDevs ) { checkInputs ( n , k ) ; if ( n == 0 ) { return 0.0 ; } // the coin was never flipped, so we know nothing else if ( k == 0 ) { return 0.0 ; } else if ( k == 1 ) { return ( exactLowerBoundOnPForKequalsOne ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else if ( k == n ) { return ( exactLowerBoundOnPForKequalsN ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else { final double x = abramowitzStegunFormula26p5p22 ( ( n - k ) + 1 , k , ( - 1.0 * numStdDevs ) ) ; return ( 1.0 - x ) ; // which is p } }
Computes lower bound of approximate Clopper - Pearson confidence interval for a binomial proportion .
211
18
31,987
public static double approximateUpperBoundOnP ( final long n , final long k , final double numStdDevs ) { checkInputs ( n , k ) ; if ( n == 0 ) { return 1.0 ; } // the coin was never flipped, so we know nothing else if ( k == n ) { return 1.0 ; } else if ( k == ( n - 1 ) ) { return ( exactUpperBoundOnPForKequalsNminusOne ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else if ( k == 0 ) { return ( exactUpperBoundOnPForKequalsZero ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else { final double x = abramowitzStegunFormula26p5p22 ( n - k , k + 1 , numStdDevs ) ; return ( 1.0 - x ) ; // which is p } }
Computes upper bound of approximate Clopper - Pearson confidence interval for a binomial proportion .
211
18
31,988
private static double erf_of_nonneg ( final double x ) { // The constants that appear below, formatted for easy checking against the book. // a1 = 0.07052 30784 // a3 = 0.00927 05272 // a5 = 0.00027 65672 // a2 = 0.04228 20123 // a4 = 0.00015 20143 // a6 = 0.00004 30638 final double a1 = 0.0705230784 ; final double a3 = 0.0092705272 ; final double a5 = 0.0002765672 ; final double a2 = 0.0422820123 ; final double a4 = 0.0001520143 ; final double a6 = 0.0000430638 ; final double x2 = x * x ; // x squared, x cubed, etc. final double x3 = x2 * x ; final double x4 = x2 * x2 ; final double x5 = x2 * x3 ; final double x6 = x3 * x3 ; final double sum = ( 1.0 + ( a1 * x ) + ( a2 * x2 ) + ( a3 * x3 ) + ( a4 * x4 ) + ( a5 * x5 ) + ( a6 * x6 ) ) ; final double sum2 = sum * sum ; // raise the sum to the 16th power final double sum4 = sum2 * sum2 ; final double sum8 = sum4 * sum4 ; final double sum16 = sum8 * sum8 ; return ( 1.0 - ( 1.0 / sum16 ) ) ; }
Abramowitz and Stegun formula 7 . 1 . 28 p . 88 ; Claims accuracy of about 7 decimal digits
350
24
31,989
private static double abramowitzStegunFormula26p5p22 ( final double a , final double b , final double yp ) { final double b2m1 = ( 2.0 * b ) - 1.0 ; final double a2m1 = ( 2.0 * a ) - 1.0 ; final double lambda = ( ( yp * yp ) - 3.0 ) / 6.0 ; final double htmp = ( 1.0 / a2m1 ) + ( 1.0 / b2m1 ) ; final double h = 2.0 / htmp ; final double term1 = ( yp * ( Math . sqrt ( h + lambda ) ) ) / h ; final double term2 = ( 1.0 / b2m1 ) - ( 1.0 / a2m1 ) ; final double term3 = ( lambda + ( 5.0 / 6.0 ) ) - ( 2.0 / ( 3.0 * h ) ) ; final double w = term1 - ( term2 * term3 ) ; final double xp = a / ( a + ( b * ( Math . exp ( 2.0 * w ) ) ) ) ; return xp ; }
that the formula was typed in correctly .
258
8
31,990
public static < T > ReservoirItemsSketch < T > newInstance ( final int k , final ResizeFactor rf ) { return new ReservoirItemsSketch <> ( k , rf ) ; }
Construct a mergeable sampling sketch with up to k samples using a specified resize factor .
47
17
31,991
@ SuppressWarnings ( "unchecked" ) public T [ ] getSamples ( ) { if ( itemsSeen_ == 0 ) { return null ; } final Class < ? > clazz = data_ . get ( 0 ) . getClass ( ) ; return data_ . toArray ( ( T [ ] ) Array . newInstance ( clazz , 0 ) ) ; }
Returns a copy of the items in the reservoir or null if empty . The returned array length may be smaller than the reservoir capacity .
82
26
31,992
@ SuppressWarnings ( "unchecked" ) ReservoirItemsSketch < T > copy ( ) { return new ReservoirItemsSketch <> ( reservoirSize_ , currItemsAlloc_ , itemsSeen_ , rf_ , ( ArrayList < T > ) data_ . clone ( ) ) ; }
Used during union operations to ensure we do not overwrite an existing reservoir . Creates a shallow copy of the reservoir .
72
23
31,993
public CompactSketch intersect ( final Sketch a , final Sketch b ) { return intersect ( a , b , true , null ) ; }
Perform intersect set operation on the two given sketch arguments and return the result as an ordered CompactSketch on the heap .
29
26
31,994
static DirectCouponList newInstance ( final int lgConfigK , final TgtHllType tgtHllType , final WritableMemory dstMem ) { insertPreInts ( dstMem , LIST_PREINTS ) ; insertSerVer ( dstMem ) ; insertFamilyId ( dstMem ) ; insertLgK ( dstMem , lgConfigK ) ; insertLgArr ( dstMem , LG_INIT_LIST_SIZE ) ; insertFlags ( dstMem , EMPTY_FLAG_MASK ) ; //empty and not compact insertListCount ( dstMem , 0 ) ; insertModes ( dstMem , tgtHllType , CurMode . LIST ) ; return new DirectCouponList ( lgConfigK , tgtHllType , CurMode . LIST , dstMem ) ; }
Standard factory for new DirectCouponList . This initializes the given WritableMemory .
178
19
31,995
static final int checkMaxLgArrLongs ( final Memory dstMem ) { final int preBytes = CONST_PREAMBLE_LONGS << 3 ; final long cap = dstMem . getCapacity ( ) ; final int maxLgArrLongs = Integer . numberOfTrailingZeros ( floorPowerOf2 ( ( int ) ( cap - preBytes ) ) >>> 3 ) ; if ( maxLgArrLongs < MIN_LG_ARR_LONGS ) { throw new SketchesArgumentException ( "dstMem not large enough for minimum sized hash table: " + cap ) ; } return maxLgArrLongs ; }
Returns the correct maximum lgArrLongs given the capacity of the Memory . Checks that the capacity is large enough for the minimum sized hash table .
146
31
31,996
static IntersectionImpl initNewHeapInstance ( final long seed ) { final IntersectionImpl impl = new IntersectionImpl ( null , seed , false ) ; impl . lgArrLongs_ = 0 ; impl . curCount_ = - 1 ; //Universal Set is true impl . thetaLong_ = Long . MAX_VALUE ; impl . empty_ = false ; //A virgin intersection represents the Universal Set so empty is FALSE! impl . hashTable_ = null ; return impl ; }
Construct a new Intersection target on the java heap .
104
11
31,997
static IntersectionImpl initNewDirectInstance ( final long seed , final WritableMemory dstMem ) { final IntersectionImpl impl = new IntersectionImpl ( dstMem , seed , true ) ; //Load Preamble insertPreLongs ( dstMem , CONST_PREAMBLE_LONGS ) ; //RF not used = 0 insertSerVer ( dstMem , SER_VER ) ; insertFamilyID ( dstMem , Family . INTERSECTION . getID ( ) ) ; //Note: Intersection does not use lgNomLongs or k, per se. //set lgArrLongs initially to minimum. Don't clear cache in mem insertLgArrLongs ( dstMem , MIN_LG_ARR_LONGS ) ; insertFlags ( dstMem , 0 ) ; //bigEndian = readOnly = compact = ordered = empty = false; //seedHash loaded and checked in private constructor insertCurCount ( dstMem , - 1 ) ; insertP ( dstMem , ( float ) 1.0 ) ; insertThetaLong ( dstMem , Long . MAX_VALUE ) ; //Initialize impl . lgArrLongs_ = MIN_LG_ARR_LONGS ; impl . curCount_ = - 1 ; //set in mem below impl . thetaLong_ = Long . MAX_VALUE ; impl . empty_ = false ; impl . maxLgArrLongs_ = checkMaxLgArrLongs ( dstMem ) ; //Only Off Heap return impl ; }
Construct a new Intersection target direct to the given destination Memory . Called by SetOperation . Builder .
326
20
31,998
static IntersectionImplR heapifyInstance ( final Memory srcMem , final long seed ) { final IntersectionImpl impl = new IntersectionImpl ( null , seed , false ) ; //Get Preamble //Note: Intersection does not use lgNomLongs (or k), per se. //seedHash loaded and checked in private constructor final int preLongsMem = srcMem . getByte ( PREAMBLE_LONGS_BYTE ) & 0X3F ; final int serVer = srcMem . getByte ( SER_VER_BYTE ) & 0XFF ; final int famID = srcMem . getByte ( FAMILY_BYTE ) & 0XFF ; final int lgArrLongs = srcMem . getByte ( LG_ARR_LONGS_BYTE ) & 0XFF ; final int flags = srcMem . getByte ( FLAGS_BYTE ) & 0XFF ; final int curCount = srcMem . getInt ( RETAINED_ENTRIES_INT ) ; final long thetaLong = srcMem . getLong ( THETA_LONG ) ; final boolean empty = ( flags & EMPTY_FLAG_MASK ) > 0 ; //Checks if ( preLongsMem != CONST_PREAMBLE_LONGS ) { throw new SketchesArgumentException ( "Memory PreambleLongs must equal " + CONST_PREAMBLE_LONGS + ": " + preLongsMem ) ; } if ( serVer != SER_VER ) { throw new SketchesArgumentException ( "Serialization Version must equal " + SER_VER ) ; } Family . INTERSECTION . checkFamilyID ( famID ) ; if ( empty ) { if ( curCount != 0 ) { throw new SketchesArgumentException ( "srcMem empty state inconsistent with curCount: " + empty + "," + curCount ) ; } //empty = true AND curCount_ = 0: OK } //Initialize impl . lgArrLongs_ = lgArrLongs ; impl . curCount_ = curCount ; impl . thetaLong_ = thetaLong ; impl . empty_ = empty ; if ( ! empty ) { if ( curCount > 0 ) { //can't be virgin, empty, or curCount == 0 impl . hashTable_ = new long [ 1 << lgArrLongs ] ; srcMem . getLongArray ( CONST_PREAMBLE_LONGS << 3 , impl . hashTable_ , 0 , 1 << lgArrLongs ) ; } } return impl ; }
Heapify an intersection target from a Memory image containing data .
565
13
31,999
@ SuppressWarnings ( { "unchecked" , "null" } ) public void update ( final Sketch < S > sketchIn ) { final boolean isFirstCall = isFirstCall_ ; isFirstCall_ = false ; if ( sketchIn == null ) { isEmpty_ = true ; sketch_ = null ; return ; } theta_ = min ( theta_ , sketchIn . getThetaLong ( ) ) ; isEmpty_ |= sketchIn . isEmpty ( ) ; if ( isEmpty_ || ( sketchIn . getRetainedEntries ( ) == 0 ) ) { sketch_ = null ; return ; } // assumes that constructor of QuickSelectSketch bumps the requested size up to the nearest power of 2 if ( isFirstCall ) { sketch_ = new QuickSelectSketch <> ( sketchIn . getRetainedEntries ( ) , ResizeFactor . X1 . lg ( ) , null ) ; final SketchIterator < S > it = sketchIn . iterator ( ) ; while ( it . next ( ) ) { final S summary = ( S ) it . getSummary ( ) . copy ( ) ; sketch_ . insert ( it . getKey ( ) , summary ) ; } } else { if ( sketch_ == null ) { return ; } final int matchSize = min ( sketch_ . getRetainedEntries ( ) , sketchIn . getRetainedEntries ( ) ) ; final long [ ] matchKeys = new long [ matchSize ] ; S [ ] matchSummaries = null ; int matchCount = 0 ; final SketchIterator < S > it = sketchIn . iterator ( ) ; while ( it . next ( ) ) { final S summary = sketch_ . find ( it . getKey ( ) ) ; if ( summary != null ) { matchKeys [ matchCount ] = it . getKey ( ) ; if ( matchSummaries == null ) { matchSummaries = ( S [ ] ) Array . newInstance ( summary . getClass ( ) , matchSize ) ; } matchSummaries [ matchCount ] = summarySetOps_ . intersection ( summary , it . getSummary ( ) ) ; matchCount ++ ; } } sketch_ = null ; if ( matchCount > 0 ) { sketch_ = new QuickSelectSketch <> ( matchCount , ResizeFactor . X1 . lg ( ) , null ) ; for ( int i = 0 ; i < matchCount ; i ++ ) { sketch_ . insert ( matchKeys [ i ] , matchSummaries [ i ] ) ; } } } if ( sketch_ != null ) { sketch_ . setThetaLong ( theta_ ) ; sketch_ . setNotEmpty ( ) ; } }
Updates the internal set by intersecting it with the given sketch
578
13