idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
34,100
public final double distance ( E e1 , E e2 ) { return distance ( e1 . getRoutingObjectID ( ) , e2 . getRoutingObjectID ( ) ) ; }
Returns the distance between the routing object of two entries .
34,101
public static < A > double [ ] alphaPWM ( A data , NumberArrayAdapter < ? , A > adapter , final int nmom ) { final int n = adapter . size ( data ) ; final double [ ] xmom = new double [ nmom ] ; double weight = 1. / n ; for ( int i = 0 ; i < n ; i ++ ) { final double val = adapter . getDouble ( data , i ) ; xmom [ 0 ] += weight * val ; for ( int j = 1 ; j < nmom ; j ++ ) { weight *= ( n - i - j + 1 ) / ( n - j + 1 ) ; xmom [ j ] += weight * val ; } } return xmom ; }
Compute the alpha_r factors using the method of probability - weighted moments .
34,102
public static < A > double [ ] alphaBetaPWM ( A data , NumberArrayAdapter < ? , A > adapter , final int nmom ) { final int n = adapter . size ( data ) ; final double [ ] xmom = new double [ nmom << 1 ] ; double aweight = 1. / n , bweight = aweight ; for ( int i = 0 ; i < n ; i ++ ) { final double val = adapter . getDouble ( data , i ) ; xmom [ 0 ] += aweight * val ; xmom [ 1 ] += bweight * val ; for ( int j = 1 , k = 2 ; j < nmom ; j ++ , k += 2 ) { aweight *= ( n - i - j + 1 ) / ( n - j + 1 ) ; bweight *= ( i - j + 1 ) / ( n - j + 1 ) ; xmom [ k + 1 ] += aweight * val ; xmom [ k + 1 ] += bweight * val ; } } return xmom ; }
Compute the alpha_r and beta_r factors in parallel using the method of probability - weighted moments . Usually cheaper than computing them separately .
34,103
public static < A > double [ ] samLMR ( A sorted , NumberArrayAdapter < ? , A > adapter , int nmom ) { final int n = adapter . size ( sorted ) ; final double [ ] sum = new double [ nmom ] ; nmom = n < nmom ? n : nmom ; for ( int i = 0 ; i < n ; i ++ ) { double term = adapter . getDouble ( sorted , i ) ; if ( Double . isInfinite ( term ) || Double . isNaN ( term ) ) { continue ; } sum [ 0 ] += term ; for ( int j = 1 , z = i ; j < nmom ; j ++ , z -- ) { term *= z ; sum [ j ] += term ; } } sum [ 0 ] /= n ; double z = n ; for ( int j = 1 ; j < nmom ; j ++ ) { z *= n - j ; sum [ j ] /= z ; } normalizeLMR ( sum , nmom ) ; if ( sum [ 1 ] == 0 ) { for ( int i = 2 ; i < nmom ; i ++ ) { sum [ i ] = 0. ; } return sum ; } for ( int i = 2 ; i < nmom ; i ++ ) { sum [ i ] /= sum [ 1 ] ; } return sum ; }
Compute the sample L - Moments using probability weighted moments .
34,104
private static void normalizeLMR ( double [ ] sum , int nmom ) { for ( int k = nmom - 1 ; k >= 1 ; -- k ) { double p = ( ( k & 1 ) == 0 ) ? + 1 : - 1 ; double temp = p * sum [ 0 ] ; for ( int i = 0 ; i < k ; i ++ ) { double ai = i + 1. ; p *= - ( k + ai ) * ( k - i ) / ( ai * ai ) ; temp += p * sum [ i + 1 ] ; } sum [ k ] = temp ; } }
Normalize the moments
34,105
private int [ ] countItemSupport ( final Relation < BitVector > relation , final int dim ) { final int [ ] counts = new int [ dim ] ; FiniteProgress prog = LOG . isVerbose ( ) ? new FiniteProgress ( "Finding frequent 1-items" , relation . size ( ) , LOG ) : null ; for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { SparseFeatureVector < ? > bv = relation . get ( iditer ) ; for ( int it = bv . iter ( ) ; bv . iterValid ( it ) ; it = bv . iterAdvance ( it ) ) { counts [ bv . iterDim ( it ) ] ++ ; } LOG . incrementProcessed ( prog ) ; } LOG . ensureCompleted ( prog ) ; return counts ; }
Count the support of each 1 - item .
34,106
private FPTree buildFPTree ( final Relation < BitVector > relation , int [ ] iidx , final int items ) { FPTree tree = new FPTree ( items ) ; FiniteProgress prog = LOG . isVerbose ( ) ? new FiniteProgress ( "Building FP-tree" , relation . size ( ) , LOG ) : null ; int [ ] buf = new int [ items ] ; for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { int l = 0 ; SparseFeatureVector < ? > bv = relation . get ( iditer ) ; for ( int it = bv . iter ( ) ; bv . iterValid ( it ) ; it = bv . iterAdvance ( it ) ) { int i = iidx [ bv . iterDim ( it ) ] ; if ( i < 0 ) { continue ; } buf [ l ++ ] = i ; } if ( l >= minlength ) { Arrays . sort ( buf , 0 , l ) ; tree . insert ( buf , 0 , l , 1 ) ; } LOG . incrementProcessed ( prog ) ; } LOG . ensureCompleted ( prog ) ; return tree ; }
Build the actual FP - tree structure .
34,107
public StringBuilder appendTo ( StringBuilder buf , VectorFieldTypeInformation < BitVector > meta ) { this . antecedent . appendTo ( buf , meta ) ; buf . append ( " ) ; this . consequent . appendItemsTo ( buf , meta ) ; buf . append ( ": " ) ; buf . append ( union . getSupport ( ) ) ; buf . append ( " : " ) ; buf . append ( this . measure ) ; return buf ; }
Append to a string buffer .
34,108
public void process ( Clustering < ? > result1 , Clustering < ? > result2 ) { final List < ? extends Cluster < ? > > cs1 = result1 . getAllClusters ( ) ; final List < ? extends Cluster < ? > > cs2 = result2 . getAllClusters ( ) ; size1 = cs1 . size ( ) ; size2 = cs2 . size ( ) ; contingency = new int [ size1 + 2 ] [ size2 + 2 ] ; noise1 = BitsUtil . zero ( size1 ) ; noise2 = BitsUtil . zero ( size2 ) ; { final Iterator < ? extends Cluster < ? > > it2 = cs2 . iterator ( ) ; for ( int i2 = 0 ; it2 . hasNext ( ) ; i2 ++ ) { final Cluster < ? > c2 = it2 . next ( ) ; if ( c2 . isNoise ( ) ) { BitsUtil . setI ( noise2 , i2 ) ; } contingency [ size1 + 1 ] [ i2 ] = c2 . size ( ) ; contingency [ size1 + 1 ] [ size2 ] += c2 . size ( ) ; } } final Iterator < ? extends Cluster < ? > > it1 = cs1 . iterator ( ) ; for ( int i1 = 0 ; it1 . hasNext ( ) ; i1 ++ ) { final Cluster < ? > c1 = it1 . next ( ) ; if ( c1 . isNoise ( ) ) { BitsUtil . setI ( noise1 , i1 ) ; } final DBIDs ids = DBIDUtil . ensureSet ( c1 . getIDs ( ) ) ; contingency [ i1 ] [ size2 + 1 ] = c1 . size ( ) ; contingency [ size1 ] [ size2 + 1 ] += c1 . size ( ) ; final Iterator < ? extends Cluster < ? > > it2 = cs2 . iterator ( ) ; for ( int i2 = 0 ; it2 . hasNext ( ) ; i2 ++ ) { final Cluster < ? > c2 = it2 . next ( ) ; int count = DBIDUtil . intersectionSize ( ids , c2 . getIDs ( ) ) ; contingency [ i1 ] [ i2 ] = count ; contingency [ i1 ] [ size2 ] += count ; contingency [ size1 ] [ i2 ] += count ; contingency [ size1 ] [ size2 ] += count ; } } }
Process two clustering results .
34,109
private long [ ] randomSubspace ( final int alldim , final int mindim , final int maxdim , final Random rand ) { long [ ] dimset = BitsUtil . zero ( alldim ) ; int [ ] dims = new int [ alldim ] ; for ( int d = 0 ; d < alldim ; d ++ ) { dims [ d ] = d ; } int subdim = mindim + rand . nextInt ( maxdim - mindim ) ; for ( int d = 0 ; d < alldim - subdim ; d ++ ) { int s = rand . nextInt ( alldim - d ) ; BitsUtil . setI ( dimset , dims [ s ] ) ; dims [ s ] = dims [ alldim - d - 1 ] ; } return dimset ; }
Choose a random subspace .
34,110
public Element renderCheckBox ( SVGPlot svgp , double x , double y , double size ) { final Element checkmark = SVGEffects . makeCheckmark ( svgp ) ; checkmark . setAttribute ( SVGConstants . SVG_TRANSFORM_ATTRIBUTE , "scale(" + ( size / 12 ) + ") translate(" + x + " " + y + ")" ) ; if ( ! checked ) { checkmark . setAttribute ( SVGConstants . SVG_STYLE_ATTRIBUTE , SVGConstants . CSS_DISPLAY_PROPERTY + ":" + SVGConstants . CSS_NONE_VALUE ) ; } Element checkbox_box = SVGUtil . svgRect ( svgp . getDocument ( ) , x , y , size , size ) ; checkbox_box . setAttribute ( SVGConstants . SVG_FILL_ATTRIBUTE , "#d4e4f1" ) ; checkbox_box . setAttribute ( SVGConstants . SVG_STROKE_ATTRIBUTE , "#a0a0a0" ) ; checkbox_box . setAttribute ( SVGConstants . SVG_STROKE_WIDTH_ATTRIBUTE , "0.5" ) ; final Element checkbox = svgp . svgElement ( SVGConstants . SVG_G_TAG ) ; checkbox . appendChild ( checkbox_box ) ; checkbox . appendChild ( checkmark ) ; if ( label != null ) { Element labele = svgp . svgText ( x + 2 * size , y + size , label ) ; checkbox . appendChild ( labele ) ; } EventTarget targ = ( EventTarget ) checkbox ; targ . addEventListener ( SVGConstants . SVG_CLICK_EVENT_TYPE , new EventListener ( ) { public void handleEvent ( Event evt ) { if ( checked ^= true ) { checkmark . removeAttribute ( SVGConstants . SVG_STYLE_ATTRIBUTE ) ; } else { checkmark . setAttribute ( SVGConstants . SVG_STYLE_ATTRIBUTE , SVGConstants . CSS_DISPLAY_PROPERTY + ":" + SVGConstants . CSS_NONE_VALUE ) ; } fireSwitchEvent ( new ChangeEvent ( SVGCheckbox . this ) ) ; } } , false ) ; return checkbox ; }
Render the SVG checkbox to a plot
34,111
protected void fireSwitchEvent ( ChangeEvent evt ) { Object [ ] listeners = listenerList . getListenerList ( ) ; for ( int i = 1 ; i < listeners . length ; i += 2 ) { if ( listeners [ i - 1 ] == ChangeListener . class ) { ( ( ChangeListener ) listeners [ i ] ) . stateChanged ( evt ) ; } } }
Fire the event to listeners
34,112
protected static void calculateSelectivityCoeffs ( List < DoubleObjPair < DAFile > > daFiles , NumberVector query , double epsilon ) { final int dimensions = query . getDimensionality ( ) ; double [ ] lowerVals = new double [ dimensions ] ; double [ ] upperVals = new double [ dimensions ] ; VectorApproximation queryApprox = calculatePartialApproximation ( null , query , daFiles ) ; for ( int i = 0 ; i < dimensions ; i ++ ) { final double val = query . doubleValue ( i ) ; lowerVals [ i ] = val - epsilon ; upperVals [ i ] = val + epsilon ; } DoubleVector lowerEpsilon = DoubleVector . wrap ( lowerVals ) ; VectorApproximation lowerEpsilonPartitions = calculatePartialApproximation ( null , lowerEpsilon , daFiles ) ; DoubleVector upperEpsilon = DoubleVector . wrap ( upperVals ) ; VectorApproximation upperEpsilonPartitions = calculatePartialApproximation ( null , upperEpsilon , daFiles ) ; for ( int i = 0 ; i < daFiles . size ( ) ; i ++ ) { int coeff = ( queryApprox . getApproximation ( i ) - lowerEpsilonPartitions . getApproximation ( i ) ) + ( upperEpsilonPartitions . getApproximation ( i ) - queryApprox . getApproximation ( i ) ) + 1 ; daFiles . get ( i ) . first = coeff ; } }
Calculate selectivity coefficients .
34,113
protected static VectorApproximation calculatePartialApproximation ( DBID id , NumberVector dv , List < DoubleObjPair < DAFile > > daFiles ) { int [ ] approximation = new int [ dv . getDimensionality ( ) ] ; for ( int i = 0 ; i < daFiles . size ( ) ; i ++ ) { double val = dv . doubleValue ( i ) ; double [ ] borders = daFiles . get ( i ) . second . getSplitPositions ( ) ; assert borders != null : "borders are null" ; int lastBorderIndex = borders . length - 1 ; if ( val < borders [ 0 ] ) { approximation [ i ] = 0 ; } else if ( val > borders [ lastBorderIndex ] ) { approximation [ i ] = lastBorderIndex - 1 ; } else { for ( int s = 0 ; s < lastBorderIndex ; s ++ ) { if ( val >= borders [ s ] && val < borders [ s + 1 ] && approximation [ i ] != - 1 ) { approximation [ i ] = s ; } } } } return new VectorApproximation ( id , approximation ) ; }
Calculate partial vector approximation .
34,114
public String solutionToString ( int fractionDigits ) { if ( ! isSolvable ( ) ) { throw new IllegalStateException ( "System is not solvable!" ) ; } DecimalFormat nf = new DecimalFormat ( ) ; nf . setMinimumFractionDigits ( fractionDigits ) ; nf . setMaximumFractionDigits ( fractionDigits ) ; nf . setDecimalFormatSymbols ( new DecimalFormatSymbols ( Locale . US ) ) ; nf . setNegativePrefix ( "" ) ; nf . setPositivePrefix ( "" ) ; int row = coeff [ 0 ] . length >> 1 ; int params = u . length ; int paramsDigits = integerDigits ( params ) ; int x0Digits = maxIntegerDigits ( x_0 ) ; int [ ] uDigits = maxIntegerDigits ( u ) ; StringBuilder buffer = new StringBuilder ( ) ; for ( int i = 0 ; i < x_0 . length ; i ++ ) { double value = x_0 [ i ] ; format ( nf , buffer , value , x0Digits ) ; for ( int j = 0 ; j < u [ 0 ] . length ; j ++ ) { if ( i == row ) { buffer . append ( " + a_" ) . append ( j ) . append ( " * " ) ; } else { buffer . append ( " " ) ; for ( int d = 0 ; d < paramsDigits ; d ++ ) { buffer . append ( ' ' ) ; } } format ( nf , buffer , u [ i ] [ j ] , uDigits [ j ] ) ; } buffer . append ( '\n' ) ; } return buffer . toString ( ) ; }
Returns a string representation of the solution of this equation system .
34,115
private void reducedRowEchelonForm ( int method ) { final int rows = coeff . length ; final int cols = coeff [ 0 ] . length ; int k = - 1 ; int pivotRow ; int pivotCol ; double pivot ; boolean exitLoop = false ; while ( ! exitLoop ) { k ++ ; IntIntPair pivotPos = new IntIntPair ( 0 , 0 ) ; IntIntPair currPos = new IntIntPair ( k , k ) ; switch ( method ) { case TRIVAL_PIVOT_SEARCH : pivotPos = nonZeroPivotSearch ( k ) ; break ; case TOTAL_PIVOT_SEARCH : pivotPos = totalPivotSearch ( k ) ; break ; } pivotRow = pivotPos . first ; pivotCol = pivotPos . second ; pivot = coeff [ this . row [ pivotRow ] ] [ col [ pivotCol ] ] ; if ( LOG . isDebugging ( ) ) { StringBuilder msg = new StringBuilder ( ) ; msg . append ( "equations " ) . append ( equationsToString ( 4 ) ) ; msg . append ( " *** pivot at (" ) . append ( pivotRow ) . append ( ',' ) . append ( pivotCol ) . append ( ") = " ) . append ( pivot ) . append ( '\n' ) ; LOG . debugFine ( msg . toString ( ) ) ; } permutePivot ( pivotPos , currPos ) ; if ( ( Math . abs ( pivot ) <= DELTA ) ) { exitLoop = true ; } if ( ( Math . abs ( pivot ) > DELTA ) ) { rank ++ ; pivotOperation ( k ) ; } if ( k == rows - 1 || k == cols - 1 ) { exitLoop = true ; } } reducedRowEchelonForm = true ; }
Brings this linear equation system into reduced row echelon form with choice of pivot method .
34,116
private IntIntPair nonZeroPivotSearch ( int k ) { int i , j ; double absValue ; for ( i = k ; i < coeff . length ; i ++ ) { for ( j = k ; j < coeff [ 0 ] . length ; j ++ ) { absValue = Math . abs ( coeff [ row [ i ] ] [ col [ j ] ] ) ; if ( absValue > 0 ) { return new IntIntPair ( i , j ) ; } } } return new IntIntPair ( k , k ) ; }
Method for trivial pivot search searches for non - zero entry .
34,117
private void permutePivot ( IntIntPair pos1 , IntIntPair pos2 ) { int r1 = pos1 . first ; int c1 = pos1 . second ; int r2 = pos2 . first ; int c2 = pos2 . second ; int index ; index = row [ r2 ] ; row [ r2 ] = row [ r1 ] ; row [ r1 ] = index ; index = col [ c2 ] ; col [ c2 ] = col [ c1 ] ; col [ c1 ] = index ; }
permutes two matrix rows and two matrix columns
34,118
private void pivotOperation ( int k ) { double pivot = coeff [ row [ k ] ] [ col [ k ] ] ; coeff [ row [ k ] ] [ col [ k ] ] = 1 ; for ( int i = k + 1 ; i < coeff [ k ] . length ; i ++ ) { coeff [ row [ k ] ] [ col [ i ] ] /= pivot ; } rhs [ row [ k ] ] /= pivot ; if ( LOG . isDebugging ( ) ) { StringBuilder msg = new StringBuilder ( ) ; msg . append ( "set pivot element to 1 " ) . append ( equationsToString ( 4 ) ) ; LOG . debugFine ( msg . toString ( ) ) ; } for ( int i = 0 ; i < coeff . length ; i ++ ) { if ( i == k ) { continue ; } double q = coeff [ row [ i ] ] [ col [ k ] ] ; coeff [ row [ i ] ] [ col [ k ] ] = 0 ; for ( int j = k + 1 ; j < coeff [ 0 ] . length ; j ++ ) { coeff [ row [ i ] ] [ col [ j ] ] = coeff [ row [ i ] ] [ col [ j ] ] - coeff [ row [ k ] ] [ col [ j ] ] * q ; } rhs [ row [ i ] ] = rhs [ row [ i ] ] - rhs [ row [ k ] ] * q ; } if ( LOG . isDebugging ( ) ) { StringBuilder msg = new StringBuilder ( ) ; msg . append ( "after pivot operation " ) . append ( equationsToString ( 4 ) ) ; LOG . debugFine ( msg . toString ( ) ) ; } }
performs a pivot operation
34,119
private void solve ( int method ) throws NullPointerException { if ( solved ) { return ; } if ( ! reducedRowEchelonForm ) { reducedRowEchelonForm ( method ) ; } if ( ! isSolvable ( method ) ) { if ( LOG . isDebugging ( ) ) { LOG . debugFine ( "Equation system is not solvable!" ) ; } return ; } final int cols = coeff [ 0 ] . length ; int numbound = 0 , numfree = 0 ; int [ ] boundIndices = new int [ cols ] , freeIndices = new int [ cols ] ; x_0 = new double [ cols ] ; outer : for ( int i = 0 ; i < coeff . length ; i ++ ) { for ( int j = i ; j < coeff [ row [ i ] ] . length ; j ++ ) { if ( coeff [ row [ i ] ] [ col [ j ] ] == 1 ) { x_0 [ col [ i ] ] = rhs [ row [ i ] ] ; boundIndices [ numbound ++ ] = col [ i ] ; continue outer ; } } freeIndices [ numfree ++ ] = i ; } StringBuilder msg = new StringBuilder ( ) ; if ( LOG . isDebugging ( ) ) { msg . append ( "\nSpecial solution x_0 = [" ) . append ( FormatUtil . format ( x_0 , "," , FormatUtil . NF4 ) ) . append ( ']' ) . append ( "\nbound Indices " ) . append ( FormatUtil . format ( boundIndices , "," ) ) . append ( "\nfree Indices " ) . append ( FormatUtil . format ( freeIndices , "," ) ) ; } Arrays . sort ( boundIndices , 0 , numbound ) ; int freeIndex = 0 ; int boundIndex = 0 ; u = new double [ cols ] [ numfree ] ; for ( int j = 0 ; j < u [ 0 ] . length ; j ++ ) { for ( int i = 0 ; i < u . length ; i ++ ) { if ( freeIndex < numfree && i == freeIndices [ freeIndex ] ) { u [ i ] [ j ] = 1 ; } else if ( boundIndex < numbound && i == boundIndices [ boundIndex ] ) { u [ i ] [ j ] = - coeff [ row [ boundIndex ] ] [ freeIndices [ freeIndex ] ] ; boundIndex ++ ; } } freeIndex ++ ; boundIndex = 0 ; } if ( LOG . isDebugging ( ) ) { msg . append ( "\nU" ) ; for ( double [ ] anU : u ) { msg . append ( '\n' ) . append ( FormatUtil . format ( anU , "," , FormatUtil . NF4 ) ) ; } LOG . debugFine ( msg . toString ( ) ) ; } solved = true ; }
solves linear system with the chosen method
34,120
private boolean isSolvable ( int method ) throws NullPointerException { if ( solved ) { return solvable ; } if ( ! reducedRowEchelonForm ) { reducedRowEchelonForm ( method ) ; } for ( int i = rank ; i < rhs . length ; i ++ ) { if ( Math . abs ( rhs [ row [ i ] ] ) > DELTA ) { solvable = false ; return false ; } } solvable = true ; return true ; }
Checks solvability of this linear equation system with the chosen method .
34,121
private int [ ] maxIntegerDigits ( double [ ] [ ] values ) { int [ ] digits = new int [ values [ 0 ] . length ] ; for ( int j = 0 ; j < values [ 0 ] . length ; j ++ ) { for ( double [ ] value : values ) { digits [ j ] = Math . max ( digits [ j ] , integerDigits ( value [ j ] ) ) ; } } return digits ; }
Returns the maximum integer digits in each column of the specified values .
34,122
private int maxIntegerDigits ( double [ ] values ) { int digits = 0 ; for ( double value : values ) { digits = Math . max ( digits , integerDigits ( value ) ) ; } return digits ; }
Returns the maximum integer digits of the specified values .
34,123
private int integerDigits ( double d ) { double value = Math . abs ( d ) ; if ( value < 10 ) { return 1 ; } return ( int ) FastMath . log10 ( value ) + 1 ; }
Returns the integer digits of the specified double value .
34,124
private void format ( NumberFormat nf , StringBuilder buffer , double value , int maxIntegerDigits ) { if ( value >= 0 ) { buffer . append ( " + " ) ; } else { buffer . append ( " - " ) ; } int digits = maxIntegerDigits - integerDigits ( value ) ; for ( int d = 0 ; d < digits ; d ++ ) { buffer . append ( ' ' ) ; } buffer . append ( nf . format ( Math . abs ( value ) ) ) ; }
Helper method for output of equations and solution . Appends the specified double value to the given string buffer according the number format and the maximum number of integer digits .
34,125
protected ArrayModifiableDBIDs initialMedoids ( DistanceQuery < V > distQ , DBIDs ids ) { if ( getLogger ( ) . isStatistics ( ) ) { getLogger ( ) . statistics ( new StringStatistic ( getClass ( ) . getName ( ) + ".initialization" , initializer . toString ( ) ) ) ; } Duration initd = getLogger ( ) . newDuration ( getClass ( ) . getName ( ) + ".initialization-time" ) . begin ( ) ; ArrayModifiableDBIDs medoids = DBIDUtil . newArray ( initializer . chooseInitialMedoids ( k , ids , distQ ) ) ; getLogger ( ) . statistics ( initd . end ( ) ) ; if ( medoids . size ( ) != k ) { throw new AbortException ( "Initializer " + initializer . toString ( ) + " did not return " + k + " means, but " + medoids . size ( ) ) ; } return medoids ; }
Choose the initial medoids .
34,126
public int getTotalClusterCount ( ) { int clusterCount = 0 ; for ( int i = 0 ; i < numclusters . length ; i ++ ) { clusterCount += numclusters [ i ] ; } return clusterCount ; }
Return the sum of all clusters
34,127
public int getHighestClusterCount ( ) { int maxClusters = 0 ; for ( int i = 0 ; i < numclusters . length ; i ++ ) { maxClusters = Math . max ( maxClusters , numclusters [ i ] ) ; } return maxClusters ; }
Returns the highest number of Clusters in the clusterings
34,128
protected static double getMinDist ( DBIDArrayIter j , DistanceQuery < ? > distQ , DBIDArrayIter mi , WritableDoubleDataStore mindist ) { double prev = mindist . doubleValue ( j ) ; if ( Double . isNaN ( prev ) ) { prev = Double . POSITIVE_INFINITY ; for ( mi . seek ( 0 ) ; mi . valid ( ) ; mi . advance ( ) ) { double d = distQ . distance ( j , mi ) ; prev = d < prev ? d : prev ; } mindist . putDouble ( j , prev ) ; } return prev ; }
Get the minimum distance to previous medoids .
34,129
private static void shuffle ( ArrayModifiableDBIDs ids , int ssize , int end , Random random ) { ssize = ssize < end ? ssize : end ; for ( int i = 1 ; i < ssize ; i ++ ) { ids . swap ( i - 1 , i + random . nextInt ( end - i ) ) ; } }
Partial Fisher - Yates shuffle .
34,130
public static LinearScale [ ] calcScales ( Relation < ? extends SpatialComparable > rel ) { int dim = RelationUtil . dimensionality ( rel ) ; DoubleMinMax [ ] minmax = DoubleMinMax . newArray ( dim ) ; LinearScale [ ] scales = new LinearScale [ dim ] ; for ( DBIDIter iditer = rel . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { SpatialComparable v = rel . get ( iditer ) ; if ( v instanceof NumberVector ) { for ( int d = 0 ; d < dim ; d ++ ) { final double mi = v . getMin ( d ) ; if ( mi != mi ) { continue ; } minmax [ d ] . put ( mi ) ; } } else { for ( int d = 0 ; d < dim ; d ++ ) { final double mi = v . getMin ( d ) ; if ( mi == mi ) { minmax [ d ] . put ( mi ) ; } final double ma = v . getMax ( d ) ; if ( ma == ma ) { minmax [ d ] . put ( ma ) ; } } } } for ( int d = 0 ; d < dim ; d ++ ) { scales [ d ] = new LinearScale ( minmax [ d ] . getMin ( ) , minmax [ d ] . getMax ( ) ) ; } return scales ; }
Compute a linear scale for each dimension .
34,131
public FrequentItemsetsResult run ( Database db , final Relation < BitVector > relation ) { final int dim = RelationUtil . dimensionality ( relation ) ; final VectorFieldTypeInformation < BitVector > meta = RelationUtil . assumeVectorField ( relation ) ; final int minsupp = getMinimumSupport ( relation . size ( ) ) ; LOG . verbose ( "Build 1-dimensional transaction lists." ) ; Duration ctime = LOG . newDuration ( STAT + "eclat.transposition.time" ) . begin ( ) ; DBIDs [ ] idx = buildIndex ( relation , dim , minsupp ) ; LOG . statistics ( ctime . end ( ) ) ; FiniteProgress prog = LOG . isVerbose ( ) ? new FiniteProgress ( "Building frequent itemsets" , idx . length , LOG ) : null ; Duration etime = LOG . newDuration ( STAT + "eclat.extraction.time" ) . begin ( ) ; final List < Itemset > solution = new ArrayList < > ( ) ; for ( int i = 0 ; i < idx . length ; i ++ ) { LOG . incrementProcessed ( prog ) ; extractItemsets ( idx , i , minsupp , solution ) ; } LOG . ensureCompleted ( prog ) ; Collections . sort ( solution ) ; LOG . statistics ( etime . end ( ) ) ; LOG . statistics ( new LongStatistic ( STAT + "frequent-itemsets" , solution . size ( ) ) ) ; return new FrequentItemsetsResult ( "Eclat" , "eclat" , solution , meta , relation . size ( ) ) ; }
Run the Eclat algorithm
34,132
public static TreeNode build ( List < Class < ? > > choices , String rootpkg ) { MutableTreeNode root = new PackageNode ( rootpkg , rootpkg ) ; HashMap < String , MutableTreeNode > lookup = new HashMap < > ( ) ; if ( rootpkg != null ) { lookup . put ( rootpkg , root ) ; } lookup . put ( "de.lmu.ifi.dbs.elki" , root ) ; lookup . put ( "" , root ) ; String prefix = rootpkg != null ? rootpkg + "." : null ; Class < ? > [ ] choic = choices . toArray ( new Class < ? > [ choices . size ( ) ] ) ; Arrays . sort ( choic , ELKIServiceScanner . SORT_BY_PRIORITY ) ; for ( Class < ? > impl : choic ) { String name = impl . getName ( ) ; name = ( prefix != null && name . startsWith ( prefix ) ) ? name . substring ( prefix . length ( ) ) : name ; int plen = ( impl . getPackage ( ) != null ) ? impl . getPackage ( ) . getName ( ) . length ( ) + 1 : 0 ; MutableTreeNode c = new ClassNode ( impl . getName ( ) . substring ( plen ) , name ) ; MutableTreeNode p = null ; int l = name . lastIndexOf ( '.' ) ; while ( p == null ) { if ( l < 0 ) { p = root ; break ; } String pname = name . substring ( 0 , l ) ; p = lookup . get ( pname ) ; if ( p != null ) { break ; } l = pname . lastIndexOf ( '.' ) ; MutableTreeNode tmp = new PackageNode ( l >= 0 ? pname . substring ( l + 1 ) : pname , pname ) ; tmp . insert ( c , 0 ) ; c = tmp ; lookup . put ( pname , tmp ) ; name = pname ; } p . insert ( c , p . getChildCount ( ) ) ; } for ( int i = 0 ; i < root . getChildCount ( ) ; i ++ ) { MutableTreeNode c = ( MutableTreeNode ) root . getChildAt ( i ) ; MutableTreeNode c2 = simplifyTree ( c , null ) ; if ( c != c2 ) { root . remove ( i ) ; root . insert ( c2 , i ) ; } } return root ; }
Build the class tree for a given set of choices .
34,133
private static MutableTreeNode simplifyTree ( MutableTreeNode cur , String prefix ) { if ( cur instanceof PackageNode ) { PackageNode node = ( PackageNode ) cur ; if ( node . getChildCount ( ) == 1 ) { String newprefix = ( prefix != null ) ? prefix + "." + ( String ) node . getUserObject ( ) : ( String ) node . getUserObject ( ) ; cur = simplifyTree ( ( MutableTreeNode ) node . getChildAt ( 0 ) , newprefix ) ; } else { if ( prefix != null ) { node . setUserObject ( prefix + "." + ( String ) node . getUserObject ( ) ) ; } for ( int i = 0 ; i < node . getChildCount ( ) ; i ++ ) { MutableTreeNode c = ( MutableTreeNode ) node . getChildAt ( i ) ; MutableTreeNode c2 = simplifyTree ( c , null ) ; if ( c != c2 ) { node . remove ( i ) ; node . insert ( c2 , i ) ; } } } } else if ( cur instanceof ClassNode ) { ClassNode node = ( ClassNode ) cur ; if ( prefix != null ) { node . setUserObject ( prefix + "." + ( String ) node . getUserObject ( ) ) ; } } return cur ; }
Simplify the tree .
34,134
protected String formatValue ( List < Class < ? extends C > > val ) { StringBuilder buf = new StringBuilder ( 50 + val . size ( ) * 25 ) ; String pkgname = restrictionClass . getPackage ( ) . getName ( ) ; for ( Class < ? extends C > c : val ) { if ( buf . length ( ) > 0 ) { buf . append ( LIST_SEP ) ; } String name = c . getName ( ) ; boolean stripPrefix = name . length ( ) > pkgname . length ( ) && name . startsWith ( pkgname ) && name . charAt ( pkgname . length ( ) ) == '.' ; buf . append ( name , stripPrefix ? pkgname . length ( ) + 1 : 0 , name . length ( ) ) ; } return buf . toString ( ) ; }
Format as string .
34,135
protected void publish ( final LogRecord record ) { if ( record instanceof ProgressLogRecord ) { ProgressLogRecord preg = ( ProgressLogRecord ) record ; Progress prog = preg . getProgress ( ) ; JProgressBar pbar = getOrCreateProgressBar ( prog ) ; updateProgressBar ( prog , pbar ) ; if ( prog . isComplete ( ) ) { removeProgressBar ( prog , pbar ) ; } if ( prog . isComplete ( ) || prog instanceof StepProgress ) { publishTextRecord ( record ) ; } } else { publishTextRecord ( record ) ; } }
Publish a logging record .
34,136
private void publishTextRecord ( final LogRecord record ) { try { logpane . publish ( record ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error writing a log-like message." , e ) ; } }
Publish a text record to the pane
34,137
private JProgressBar getOrCreateProgressBar ( Progress prog ) { JProgressBar pbar = pbarmap . get ( prog ) ; if ( pbar == null ) { synchronized ( pbarmap ) { if ( prog instanceof FiniteProgress ) { pbar = new JProgressBar ( 0 , ( ( FiniteProgress ) prog ) . getTotal ( ) ) ; pbar . setStringPainted ( true ) ; } else if ( prog instanceof IndefiniteProgress ) { pbar = new JProgressBar ( ) ; pbar . setIndeterminate ( true ) ; pbar . setStringPainted ( true ) ; } else if ( prog instanceof MutableProgress ) { pbar = new JProgressBar ( 0 , ( ( MutableProgress ) prog ) . getTotal ( ) ) ; pbar . setStringPainted ( true ) ; } else { throw new RuntimeException ( "Unsupported progress record" ) ; } pbarmap . put ( prog , pbar ) ; final JProgressBar pbar2 = pbar ; SwingUtilities . invokeLater ( ( ) -> addProgressBar ( pbar2 ) ) ; } } return pbar ; }
Get an existing or create a new progress bar .
34,138
private void updateProgressBar ( Progress prog , JProgressBar pbar ) { if ( prog instanceof FiniteProgress ) { pbar . setValue ( ( ( FiniteProgress ) prog ) . getProcessed ( ) ) ; pbar . setString ( ( ( FiniteProgress ) prog ) . toString ( ) ) ; } else if ( prog instanceof IndefiniteProgress ) { pbar . setValue ( ( ( IndefiniteProgress ) prog ) . getProcessed ( ) ) ; pbar . setString ( ( ( IndefiniteProgress ) prog ) . toString ( ) ) ; } else if ( prog instanceof MutableProgress ) { pbar . setValue ( ( ( MutableProgress ) prog ) . getProcessed ( ) ) ; pbar . setMaximum ( ( ( MutableProgress ) prog ) . getProcessed ( ) ) ; pbar . setString ( ( ( MutableProgress ) prog ) . toString ( ) ) ; } else { throw new RuntimeException ( "Unsupported progress record" ) ; } }
Update a progress bar
34,139
private void removeProgressBar ( Progress prog , JProgressBar pbar ) { synchronized ( pbarmap ) { pbarmap . remove ( prog ) ; SwingUtilities . invokeLater ( ( ) -> removeProgressBar ( pbar ) ) ; } }
Remove a progress bar
34,140
public void clear ( ) { logpane . clear ( ) ; synchronized ( pbarmap ) { for ( Entry < Progress , JProgressBar > ent : pbarmap . entrySet ( ) ) { super . remove ( ent . getValue ( ) ) ; pbarmap . remove ( ent . getKey ( ) ) ; } } }
Clear the current contents .
34,141
public void componentResized ( ComponentEvent e ) { if ( e . getComponent ( ) == component ) { double newRatio = getCurrentRatio ( ) ; if ( Math . abs ( newRatio - activeRatio ) > threshold ) { activeRatio = newRatio ; executeResize ( newRatio ) ; } } }
React to a component resize event .
34,142
public String format ( LogRecord record ) { String msg = record . getMessage ( ) ; if ( msg . length ( ) > 0 ) { if ( record instanceof ProgressLogRecord ) { return msg ; } if ( msg . endsWith ( OutputStreamLogger . NEWLINE ) ) { return msg ; } } return msg + OutputStreamLogger . NEWLINE ; }
Retrieves the message as it is set in the given LogRecord .
34,143
protected double [ ] alignLabels ( List < ClassLabel > l1 , double [ ] d1 , Collection < ClassLabel > l2 ) { assert ( l1 . size ( ) == d1 . length ) ; if ( l1 == l2 ) { return d1 . clone ( ) ; } double [ ] d2 = new double [ l2 . size ( ) ] ; Iterator < ClassLabel > i2 = l2 . iterator ( ) ; for ( int i = 0 ; i2 . hasNext ( ) ; ) { ClassLabel l = i2 . next ( ) ; int idx = l1 . indexOf ( l ) ; if ( idx < 0 && getLogger ( ) . isDebuggingFiner ( ) ) { getLogger ( ) . debugFiner ( "Label not found: " + l ) ; } d2 [ i ] = ( idx >= 0 ) ? d1 [ idx ] : 0. ; } return d2 ; }
Align the labels for a label query .
34,144
public void setInitialClusters ( List < ? extends Cluster < ? extends MeanModel > > initialMeans ) { double [ ] [ ] vecs = new double [ initialMeans . size ( ) ] [ ] ; for ( int i = 0 ; i < vecs . length ; i ++ ) { vecs [ i ] = initialMeans . get ( i ) . getModel ( ) . getMean ( ) ; } this . initialMeans = vecs ; }
Set the initial means .
34,145
public static void exception ( String message , Throwable e ) { if ( message == null && e != null ) { message = e . getMessage ( ) ; } logExpensive ( Level . SEVERE , message , e ) ; }
Static version to log a severe exception .
34,146
public static void warning ( String message , Throwable e ) { if ( message == null && e != null ) { message = e . getMessage ( ) ; } logExpensive ( Level . WARNING , message , e ) ; }
Static version to log a warning message .
34,147
public static void message ( String message , Throwable e ) { if ( message == null && e != null ) { message = e . getMessage ( ) ; } logExpensive ( Level . INFO , message , e ) ; }
Static version to log a info message .
34,148
private static final String [ ] inferCaller ( ) { StackTraceElement [ ] stack = ( new Throwable ( ) ) . getStackTrace ( ) ; int ix = 0 ; while ( ix < stack . length ) { StackTraceElement frame = stack [ ix ] ; if ( ! frame . getClassName ( ) . equals ( LoggingUtil . class . getCanonicalName ( ) ) ) { return new String [ ] { frame . getClassName ( ) , frame . getMethodName ( ) } ; } ix ++ ; } return null ; }
Infer which class has called the logging helper .
34,149
public static long binomialCoefficient ( long n , long k ) { final long m = Math . max ( k , n - k ) ; double temp = 1 ; for ( long i = n , j = 1 ; i > m ; i -- , j ++ ) { temp = temp * i / j ; } return ( long ) temp ; }
Binomial coefficient also known as n choose k .
34,150
public static double approximateBinomialCoefficient ( int n , int k ) { final int m = max ( k , n - k ) ; long temp = 1 ; for ( int i = n , j = 1 ; i > m ; i -- , j ++ ) { temp = temp * i / j ; } return temp ; }
Binomial coefficent also known as n choose k ) .
34,151
public static int [ ] sequence ( int start , int end ) { if ( start >= end ) { return EMPTY_INTS ; } int [ ] ret = new int [ end - start ] ; for ( int j = 0 ; start < end ; start ++ , j ++ ) { ret [ j ] = start ; } return ret ; }
Generate an array of integers .
34,152
public KNNDistanceOrderResult run ( Database database , Relation < O > relation ) { final DistanceQuery < O > distanceQuery = database . getDistanceQuery ( relation , getDistanceFunction ( ) ) ; final KNNQuery < O > knnQuery = database . getKNNQuery ( distanceQuery , k + 1 ) ; final int size = ( int ) ( ( sample <= 1. ) ? Math . ceil ( relation . size ( ) * sample ) : sample ) ; DBIDs sample = DBIDUtil . randomSample ( relation . getDBIDs ( ) , size , rnd ) ; FiniteProgress prog = LOG . isVerbose ( ) ? new FiniteProgress ( "Sampling kNN distances" , size , LOG ) : null ; double [ ] knnDistances = new double [ size ] ; int i = 0 ; for ( DBIDIter iditer = sample . iter ( ) ; iditer . valid ( ) ; iditer . advance ( ) , i ++ ) { final KNNList neighbors = knnQuery . getKNNForDBID ( iditer , k + 1 ) ; knnDistances [ i ] = neighbors . getKNNDistance ( ) ; LOG . incrementProcessed ( prog ) ; } LOG . ensureCompleted ( prog ) ; return new KNNDistanceOrderResult ( knnDistances , k ) ; }
Provides an order of the kNN - distances for all objects within the specified database .
34,153
public DataStore < M > preprocess ( Class < ? super M > modelcls , Relation < O > relation , RangeQuery < O > query ) { WritableDataStore < M > storage = DataStoreUtil . makeStorage ( relation . getDBIDs ( ) , DataStoreFactory . HINT_HOT | DataStoreFactory . HINT_TEMP , modelcls ) ; Duration time = getLogger ( ) . newDuration ( this . getClass ( ) . getName ( ) + ".preprocessing-time" ) . begin ( ) ; FiniteProgress progress = getLogger ( ) . isVerbose ( ) ? new FiniteProgress ( this . getClass ( ) . getName ( ) , relation . size ( ) , getLogger ( ) ) : null ; for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { DoubleDBIDList neighbors = query . getRangeForDBID ( iditer , epsilon ) ; storage . put ( iditer , computeLocalModel ( iditer , neighbors , relation ) ) ; getLogger ( ) . incrementProcessed ( progress ) ; } getLogger ( ) . ensureCompleted ( progress ) ; getLogger ( ) . statistics ( time . end ( ) ) ; return storage ; }
Perform the preprocessing step .
34,154
public < NV extends NumberVector > NV projectScaledToDataSpace ( double [ ] v , NumberVector . Factory < NV > factory ) { final int dim = v . length ; double [ ] vec = new double [ dim ] ; for ( int d = 0 ; d < dim ; d ++ ) { vec [ d ] = scales [ d ] . getUnscaled ( v [ d ] ) ; } return factory . newNumberVector ( vec ) ; }
Project a vector from scaled space to data space .
34,155
public < NV extends NumberVector > NV projectRenderToDataSpace ( double [ ] v , NumberVector . Factory < NV > prototype ) { final int dim = v . length ; double [ ] vec = projectRenderToScaled ( v ) ; for ( int d = 0 ; d < dim ; d ++ ) { vec [ d ] = scales [ d ] . getUnscaled ( vec [ d ] ) ; } return prototype . newNumberVector ( vec ) ; }
Project a vector from rendering space to data space .
34,156
public < NV extends NumberVector > NV projectRelativeScaledToDataSpace ( double [ ] v , NumberVector . Factory < NV > prototype ) { final int dim = v . length ; double [ ] vec = new double [ dim ] ; for ( int d = 0 ; d < dim ; d ++ ) { vec [ d ] = scales [ d ] . getRelativeUnscaled ( v [ d ] ) ; } return prototype . newNumberVector ( vec ) ; }
Project a relative vector from scaled space to data space .
34,157
public PointerHierarchyRepresentationResult complete ( ) { if ( csize != null ) { csize . destroy ( ) ; csize = null ; } if ( mergecount != ids . size ( ) - 1 ) { LOG . warning ( mergecount + " merges were added to the hierarchy, expected " + ( ids . size ( ) - 1 ) ) ; } if ( prototypes != null ) { return new PointerPrototypeHierarchyRepresentationResult ( ids , parent , parentDistance , isSquared , order , prototypes ) ; } return new PointerHierarchyRepresentationResult ( ids , parent , parentDistance , isSquared , order ) ; }
Finalize the result .
34,158
public int getSize ( DBIDRef id ) { if ( csize == null ) { csize = DataStoreUtil . makeIntegerStorage ( ids , DataStoreFactory . HINT_HOT | DataStoreFactory . HINT_TEMP , 1 ) ; } return csize . intValue ( id ) ; }
Get the cluster size of the current object .
34,159
public void setSize ( DBIDRef id , int size ) { if ( csize == null ) { csize = DataStoreUtil . makeIntegerStorage ( ids , DataStoreFactory . HINT_HOT | DataStoreFactory . HINT_TEMP , 1 ) ; } csize . putInt ( id , size ) ; }
Set the cluster size of an object .
34,160
public OutlierResult run ( Database database , Relation < N > spatial , Relation < O > relation ) { final NeighborSetPredicate npred = getNeighborSetPredicateFactory ( ) . instantiate ( database , spatial ) ; DistanceQuery < O > distFunc = getNonSpatialDistanceFunction ( ) . instantiate ( relation ) ; WritableDoubleDataStore lrds = DataStoreUtil . makeDoubleStorage ( relation . getDBIDs ( ) , DataStoreFactory . HINT_TEMP | DataStoreFactory . HINT_HOT ) ; WritableDoubleDataStore lofs = DataStoreUtil . makeDoubleStorage ( relation . getDBIDs ( ) , DataStoreFactory . HINT_STATIC ) ; DoubleMinMax lofminmax = new DoubleMinMax ( ) ; for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { DBIDs neighbors = npred . getNeighborDBIDs ( iditer ) ; double avg = 0 ; for ( DBIDIter iter = neighbors . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { avg += distFunc . distance ( iditer , iter ) ; } double lrd = 1 / ( avg / neighbors . size ( ) ) ; if ( Double . isNaN ( lrd ) ) { lrd = 0 ; } lrds . putDouble ( iditer , lrd ) ; } for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { DBIDs neighbors = npred . getNeighborDBIDs ( iditer ) ; double avg = 0 ; for ( DBIDIter iter = neighbors . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { avg += lrds . doubleValue ( iter ) ; } final double lrd = ( avg / neighbors . size ( ) ) / lrds . doubleValue ( iditer ) ; if ( ! Double . isNaN ( lrd ) ) { lofs . putDouble ( iditer , lrd ) ; lofminmax . put ( lrd ) ; } else { lofs . putDouble ( iditer , 0.0 ) ; } } DoubleRelation scoreResult = new MaterializedDoubleRelation ( "Spatial Outlier Factor" , "sof-outlier" , lofs , relation . getDBIDs ( ) ) ; OutlierScoreMeta scoreMeta = new QuotientOutlierScoreMeta ( lofminmax . getMin ( ) , lofminmax . getMax ( ) , 0.0 , Double . POSITIVE_INFINITY , 1.0 ) ; OutlierResult or = new OutlierResult ( scoreMeta , scoreResult ) ; or . addChildResult ( npred ) ; return or ; }
The main run method
34,161
public void insertHandler ( Class < ? > restrictionClass , H handler ) { handlers . add ( new Pair < Class < ? > , H > ( restrictionClass , handler ) ) ; }
Insert a handler to the beginning of the stack .
34,162
public H getHandler ( Object o ) { if ( o == null ) { return null ; } ListIterator < Pair < Class < ? > , H > > iter = handlers . listIterator ( handlers . size ( ) ) ; while ( iter . hasPrevious ( ) ) { Pair < Class < ? > , H > pair = iter . previous ( ) ; try { pair . getFirst ( ) . cast ( o ) ; return pair . getSecond ( ) ; } catch ( ClassCastException e ) { } } return null ; }
Find a matching handler for the given object
34,163
public synchronized static Logging getLogger ( final String name ) { Logging logger = loggers . get ( name ) ; if ( logger == null ) { logger = new Logging ( Logger . getLogger ( name ) ) ; loggers . put ( name , logger ) ; } return logger ; }
Retrieve logging utility for a particular class .
34,164
public void log ( java . util . logging . Level level , CharSequence message ) { LogRecord rec = new ELKILogRecord ( level , message ) ; logger . log ( rec ) ; }
Log a log message at the given level .
34,165
public void error ( CharSequence message , Throwable e ) { log ( Level . SEVERE , message , e ) ; }
Log a message at the severe level .
34,166
public void warning ( CharSequence message , Throwable e ) { log ( Level . WARNING , message , e ) ; }
Log a message at the warning level .
34,167
public void statistics ( CharSequence message , Throwable e ) { log ( Level . STATISTICS , message , e ) ; }
Log a message at the STATISTICS level .
34,168
public void veryverbose ( CharSequence message , Throwable e ) { log ( Level . VERYVERBOSE , message , e ) ; }
Log a message at the veryverbose level .
34,169
public void exception ( CharSequence message , Throwable e ) { log ( Level . SEVERE , message , e ) ; }
Log a message with exception at the severe level .
34,170
public void exception ( Throwable e ) { final String msg = e . getMessage ( ) ; log ( Level . SEVERE , msg != null ? msg : "An exception occurred." , e ) ; }
Log an exception at the severe level .
34,171
public void statistics ( Statistic stats ) { if ( stats != null ) { log ( Level . STATISTICS , stats . getKey ( ) + ": " + stats . formatValue ( ) ) ; } }
Log a statistics object .
34,172
public MultipleObjectsBundle generate ( ) { if ( generators . isEmpty ( ) ) { throw new AbortException ( "No clusters specified." ) ; } final int dim = generators . get ( 0 ) . getDim ( ) ; for ( GeneratorInterface c : generators ) { if ( c . getDim ( ) != dim ) { throw new AbortException ( "Cluster dimensions do not agree." ) ; } } MultipleObjectsBundle bundle = new MultipleObjectsBundle ( ) ; VectorFieldTypeInformation < DoubleVector > type = new VectorFieldTypeInformation < > ( DoubleVector . FACTORY , dim ) ; bundle . appendColumn ( type , new ArrayList < > ( ) ) ; bundle . appendColumn ( TypeUtil . CLASSLABEL , new ArrayList < > ( ) ) ; bundle . appendColumn ( Model . TYPE , new ArrayList < Model > ( ) ) ; ClassLabel [ ] labels = new ClassLabel [ generators . size ( ) ] ; Model [ ] models = new Model [ generators . size ( ) ] ; initLabelsAndModels ( generators , labels , models , relabelClusters ) ; final AssignPoint assignment ; if ( ! testAgainstModel ) { assignment = new AssignPoint ( ) ; } else if ( relabelClusters == null ) { assignment = new TestModel ( ) ; } else if ( ! relabelDistance ) { assignment = new AssignLabelsByDensity ( labels ) ; } else { assignment = new AssignLabelsByDistance ( labels ) ; } for ( int i = 0 ; i < labels . length ; i ++ ) { final GeneratorInterface curclus = generators . get ( i ) ; assignment . newCluster ( i , curclus ) ; GeneratorInterfaceDynamic cursclus = ( curclus instanceof GeneratorInterfaceDynamic ) ? ( GeneratorInterfaceDynamic ) curclus : null ; int kept = 0 ; while ( kept < curclus . getSize ( ) ) { List < double [ ] > newp = curclus . generate ( curclus . getSize ( ) - kept ) ; for ( double [ ] p : newp ) { int bestc = assignment . getAssignment ( i , p ) ; if ( bestc < 0 ) { cursclus . incrementDiscarded ( ) ; continue ; } bundle . appendSimple ( DoubleVector . wrap ( p ) , labels [ bestc ] , models [ bestc ] ) ; ++ kept ; } } } return bundle ; }
Main loop to generate data set .
34,173
private void initLabelsAndModels ( ArrayList < GeneratorInterface > generators , ClassLabel [ ] labels , Model [ ] models , Pattern reassign ) { int existingclusters = 0 ; if ( reassign != null ) { for ( int i = 0 ; i < labels . length ; i ++ ) { final GeneratorInterface curclus = generators . get ( i ) ; if ( ! reassign . matcher ( curclus . getName ( ) ) . find ( ) ) { labels [ i ] = new SimpleClassLabel ( curclus . getName ( ) ) ; models [ i ] = curclus . makeModel ( ) ; ++ existingclusters ; } } if ( existingclusters == 0 ) { LOG . warning ( "All clusters matched the 'reassign' pattern. Ignoring." ) ; } if ( existingclusters == 1 ) { for ( int i = 0 ; i < labels . length ; i ++ ) { if ( labels [ i ] != null ) { Arrays . fill ( labels , labels [ i ] ) ; Arrays . fill ( models , models [ i ] ) ; break ; } } } if ( existingclusters == labels . length ) { LOG . warning ( "No clusters matched the 'reassign' pattern." ) ; } } if ( existingclusters == 0 ) { for ( int i = 0 ; i < labels . length ; i ++ ) { final GeneratorInterface curclus = generators . get ( i ) ; labels [ i ] = new SimpleClassLabel ( curclus . getName ( ) ) ; models [ i ] = curclus . makeModel ( ) ; } } }
Initialize cluster labels and models .
34,174
public static < V extends FeatureVector < ? > > VectorFieldTypeInformation < V > assumeVectorField ( Relation < V > relation ) { try { return ( ( VectorFieldTypeInformation < V > ) relation . getDataTypeInformation ( ) ) ; } catch ( Exception e ) { throw new UnsupportedOperationException ( "Expected a vector field, got type information: " + relation . getDataTypeInformation ( ) . toString ( ) , e ) ; } }
Get the vector field type information from a relation .
34,175
public static < V extends NumberVector > NumberVector . Factory < V > getNumberVectorFactory ( Relation < V > relation ) { final VectorFieldTypeInformation < V > type = assumeVectorField ( relation ) ; @ SuppressWarnings ( "unchecked" ) final NumberVector . Factory < V > factory = ( NumberVector . Factory < V > ) type . getFactory ( ) ; return factory ; }
Get the number vector factory of a database relation .
34,176
public static int dimensionality ( Relation < ? extends SpatialComparable > relation ) { final SimpleTypeInformation < ? extends SpatialComparable > type = relation . getDataTypeInformation ( ) ; if ( type instanceof FieldTypeInformation ) { return ( ( FieldTypeInformation ) type ) . getDimensionality ( ) ; } return - 1 ; }
Get the dimensionality of a database relation .
34,177
public static double [ ] [ ] computeMinMax ( Relation < ? extends NumberVector > relation ) { int dim = RelationUtil . dimensionality ( relation ) ; double [ ] mins = new double [ dim ] , maxs = new double [ dim ] ; for ( int i = 0 ; i < dim ; i ++ ) { mins [ i ] = Double . MAX_VALUE ; maxs [ i ] = - Double . MAX_VALUE ; } for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { final NumberVector o = relation . get ( iditer ) ; for ( int d = 0 ; d < dim ; d ++ ) { final double v = o . doubleValue ( d ) ; mins [ d ] = ( v < mins [ d ] ) ? v : mins [ d ] ; maxs [ d ] = ( v > maxs [ d ] ) ? v : maxs [ d ] ; } } return new double [ ] [ ] { mins , maxs } ; }
Determines the minimum and maximum values in each dimension of all objects stored in the given database .
34,178
public static < V extends SpatialComparable > String getColumnLabel ( Relation < ? extends V > rel , int col ) { SimpleTypeInformation < ? extends V > type = rel . getDataTypeInformation ( ) ; if ( ! ( type instanceof VectorFieldTypeInformation ) ) { return "Column " + col ; } final VectorFieldTypeInformation < ? > vtype = ( VectorFieldTypeInformation < ? > ) type ; String lbl = vtype . getLabel ( col ) ; return ( lbl != null ) ? lbl : ( "Column " + col ) ; }
Get the column name or produce a generic label Column XY .
34,179
@ SuppressWarnings ( "unchecked" ) public static < V extends NumberVector , T extends NumberVector > Relation < V > relationUglyVectorCast ( Relation < T > database ) { return ( Relation < V > ) database ; }
An ugly vector type cast unavoidable in some situations due to Generics .
34,180
public KNNList get ( DBIDRef id ) { if ( storage == null ) { if ( getLogger ( ) . isDebugging ( ) ) { getLogger ( ) . debug ( "Running kNN preprocessor: " + this . getClass ( ) ) ; } preprocess ( ) ; } return storage . get ( id ) ; }
Get the k nearest neighbors .
34,181
public Clustering < DimensionModel > run ( Database database , Relation < V > relation ) { COPACNeighborPredicate . Instance npred = new COPACNeighborPredicate < V > ( settings ) . instantiate ( database , relation ) ; CorePredicate . Instance < DBIDs > cpred = new MinPtsCorePredicate ( settings . minpts ) . instantiate ( database ) ; Clustering < Model > dclusters = new GeneralizedDBSCAN . Instance < > ( npred , cpred , false ) . run ( ) ; Clustering < DimensionModel > result = new Clustering < > ( "COPAC clustering" , "copac-clustering" ) ; for ( It < Cluster < Model > > iter = dclusters . iterToplevelClusters ( ) ; iter . valid ( ) ; iter . advance ( ) ) { Cluster < Model > clus = iter . get ( ) ; if ( clus . size ( ) > 0 ) { int dim = npred . dimensionality ( clus . getIDs ( ) . iter ( ) ) ; DimensionModel model = new DimensionModel ( dim ) ; result . addToplevelCluster ( new Cluster < > ( clus . getIDs ( ) , model ) ) ; } } return result ; }
Run the COPAC algorithm .
34,182
public int getUnpairedClusteringIndex ( ) { for ( int index = 0 ; index < clusterIds . length ; index ++ ) { if ( clusterIds [ index ] == UNCLUSTERED ) { return index ; } } return - 1 ; }
Returns the index of the first clustering having an unpaired cluster or - 1 no unpaired cluster exists .
34,183
protected static boolean isNull ( Object val ) { return ( val == null ) || STRING_NULL . equals ( val ) || DOUBLE_NULL . equals ( val ) || INTEGER_NULL . equals ( val ) ; }
Test a value for null .
34,184
private static String formatCause ( Throwable cause ) { if ( cause == null ) { return "" ; } String message = cause . getMessage ( ) ; return "\n" + ( message != null ? message : cause . toString ( ) ) ; }
Format the error cause .
34,185
public TextWriterWriterInterface < ? > getWriterFor ( Object o ) { if ( o == null ) { return null ; } TextWriterWriterInterface < ? > writer = writers . getHandler ( o ) ; if ( writer != null ) { return writer ; } try { final Class < ? > decl = o . getClass ( ) . getMethod ( "toString" ) . getDeclaringClass ( ) ; if ( decl == Object . class ) { return null ; } writers . insertHandler ( decl , fallbackwriter ) ; return fallbackwriter ; } catch ( NoSuchMethodException | SecurityException e ) { return null ; } }
Retrieve an appropriate writer from the handler list .
34,186
protected Cluster < BiclusterModel > defineBicluster ( BitSet rows , BitSet cols ) { ArrayDBIDs rowIDs = rowsBitsetToIDs ( rows ) ; int [ ] colIDs = colsBitsetToIDs ( cols ) ; return new Cluster < > ( rowIDs , new BiclusterModel ( colIDs ) ) ; }
Defines a Bicluster as given by the included rows and columns .
34,187
public double getSampleSkewness ( ) { if ( ! ( m2 > 0 ) || ! ( n > 2 ) ) { throw new ArithmeticException ( "Skewness not defined when variance is 0 or weight <= 2.0!" ) ; } return ( m3 * n / ( n - 1 ) / ( n - 2 ) ) / FastMath . pow ( getSampleVariance ( ) , 1.5 ) ; }
Get the skewness using sample variance .
34,188
public static double cosineOrHaversineDeg ( double lat1 , double lon1 , double lat2 , double lon2 ) { return cosineOrHaversineRad ( deg2rad ( lat1 ) , deg2rad ( lon1 ) , deg2rad ( lat2 ) , deg2rad ( lon2 ) ) ; }
Use cosine or haversine dynamically .
34,189
public static double crossTrackDistanceRad ( double lat1 , double lon1 , double lat2 , double lon2 , double latQ , double lonQ , double dist1Q ) { final double dlon12 = lon2 - lon1 ; final double dlon1Q = lonQ - lon1 ; final DoubleWrapper tmp = new DoubleWrapper ( ) ; final double slat1 = sinAndCos ( lat1 , tmp ) , clat1 = tmp . value ; final double slatQ = sinAndCos ( latQ , tmp ) , clatQ = tmp . value ; final double slat2 = sinAndCos ( lat2 , tmp ) , clat2 = tmp . value ; final double sdlon12 = sinAndCos ( dlon12 , tmp ) , cdlon12 = tmp . value ; final double sdlon1Q = sinAndCos ( dlon1Q , tmp ) , cdlon1Q = tmp . value ; final double yE = sdlon12 * clat2 ; final double yQ = sdlon1Q * clatQ ; final double xE = clat1 * slat2 - slat1 * clat2 * cdlon12 ; final double xQ = clat1 * slatQ - slat1 * clatQ * cdlon1Q ; final double crs12 = atan2 ( yE , xE ) ; final double crs1Q = atan2 ( yQ , xQ ) ; return asin ( sin ( dist1Q ) * sin ( crs1Q - crs12 ) ) ; }
Compute the cross - track distance .
34,190
public static double alongTrackDistanceRad ( double lat1 , double lon1 , double lat2 , double lon2 , double latQ , double lonQ , double dist1Q , double ctd ) { int sign = Math . abs ( bearingRad ( lat1 , lon1 , lat2 , lon2 ) - bearingRad ( lat1 , lon1 , latQ , lonQ ) ) < HALFPI ? + 1 : - 1 ; return sign * acos ( cos ( dist1Q ) / cos ( ctd ) ) ; }
The along track distance is the distance from S to Q along the track S to E .
34,191
private static double [ ] reversed ( double [ ] a ) { Arrays . sort ( a ) ; for ( int i = 0 , j = a . length - 1 ; i < j ; i ++ , j -- ) { double tmp = a [ i ] ; a [ i ] = a [ j ] ; a [ j ] = tmp ; } return a ; }
Sort an array of doubles in descending order .
34,192
private double computeExplainedVariance ( double [ ] eigenValues , int filteredEigenPairs ) { double strongsum = 0. , weaksum = 0. ; for ( int i = 0 ; i < filteredEigenPairs ; i ++ ) { strongsum += eigenValues [ i ] ; } for ( int i = filteredEigenPairs ; i < eigenValues . length ; i ++ ) { weaksum += eigenValues [ i ] ; } return strongsum / ( strongsum + weaksum ) ; }
Compute the explained variance for a filtered EigenPairs .
34,193
private void assertSortedByDistance ( DoubleDBIDList results ) { double dist = - 1.0 ; boolean sorted = true ; for ( DoubleDBIDListIter it = results . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { double qr = it . doubleValue ( ) ; if ( qr < dist ) { sorted = false ; } dist = qr ; } if ( ! sorted ) { try { ModifiableDoubleDBIDList . class . cast ( results ) . sort ( ) ; } catch ( ClassCastException | UnsupportedOperationException e ) { LoggingUtil . warning ( "WARNING: results not sorted by distance!" , e ) ; } } }
Ensure that the results are sorted by distance .
34,194
public static String prefixParameterToMessage ( Parameter < ? > p , String message ) { return new StringBuilder ( 100 + message . length ( ) ) . append ( p instanceof Flag ? "Flag '" : "Parameter '" ) . append ( p . getOptionID ( ) . getName ( ) ) . append ( "' " ) . append ( message ) . toString ( ) ; }
Prefix parameter information to error message .
34,195
public static String prefixParametersToMessage ( Parameter < ? > p , String mid , Parameter < ? > p2 , String message ) { return new StringBuilder ( 200 + mid . length ( ) + message . length ( ) ) . append ( p instanceof Flag ? "Flag '" : "Parameter '" ) . append ( p . getOptionID ( ) . getName ( ) ) . append ( "' " ) . append ( mid ) . append ( p instanceof Flag ? " Flag '" : " Parameter '" ) . append ( p . getOptionID ( ) . getName ( ) ) . append ( message . length ( ) > 0 ? "' " : "'." ) . append ( message ) . toString ( ) ; }
Prefix parameters to error message .
34,196
protected int computeHeight ( ) { N node = getRoot ( ) ; int height = 1 ; while ( ! node . isLeaf ( ) && node . getNumEntries ( ) != 0 ) { E entry = node . getEntry ( 0 ) ; node = getNode ( entry ) ; height ++ ; } return height ; }
Computes the height of this RTree . Is called by the constructor . and should be overwritten by subclasses if necessary .
34,197
private List < E > createBulkDirectoryNodes ( List < E > nodes ) { int minEntries = dirMinimum ; int maxEntries = dirCapacity - 1 ; ArrayList < E > result = new ArrayList < > ( ) ; List < List < E > > partitions = settings . bulkSplitter . partition ( nodes , minEntries , maxEntries ) ; for ( List < E > partition : partitions ) { N dirNode = createNewDirectoryNode ( ) ; for ( E o : partition ) { dirNode . addDirectoryEntry ( o ) ; } writeNode ( dirNode ) ; result . add ( createNewDirectoryEntry ( dirNode ) ) ; if ( getLogger ( ) . isDebuggingFiner ( ) ) { getLogger ( ) . debugFiner ( "Directory page no: " + dirNode . getPageID ( ) ) ; } } return result ; }
Creates and returns the directory nodes for bulk load .
34,198
private N createRoot ( N root , List < E > objects ) { for ( E entry : objects ) { if ( entry instanceof LeafEntry ) { root . addLeafEntry ( entry ) ; } else { root . addDirectoryEntry ( entry ) ; } } ( ( SpatialDirectoryEntry ) getRootEntry ( ) ) . setMBR ( root . computeMBR ( ) ) ; writeNode ( root ) ; if ( getLogger ( ) . isDebuggingFiner ( ) ) { StringBuilder msg = new StringBuilder ( ) ; msg . append ( "pageNo " ) . append ( root . getPageID ( ) ) ; getLogger ( ) . debugFiner ( msg . toString ( ) ) ; } return root ; }
Returns a root node for bulk load . If the objects are data objects a leaf node will be returned if the objects are nodes a directory node will be returned .
34,199
private int tailingNonNewline ( char [ ] cbuf , int off , int len ) { for ( int cnt = 0 ; cnt < len ; cnt ++ ) { final int pos = off + ( len - 1 ) - cnt ; if ( cbuf [ pos ] == UNIX_NEWLINE ) { return cnt ; } if ( cbuf [ pos ] == CARRIAGE_RETURN ) { return cnt ; } } return len ; }
Count the tailing non - newline characters .