idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
33,400
public static AffineTransformation reorderAxesTransformation ( int dim , int ... axes ) { double [ ] [ ] m = zeroMatrix ( dim + 1 ) ; for ( int i = 0 ; i < axes . length ; i ++ ) { assert ( 0 < axes [ i ] && axes [ i ] <= dim ) ; m [ i ] [ axes [ i ] - 1 ] = 1.0 ; } int useddim = 1 ; for ( int i = axes . length ; i < dim + 1 ; i ++ ) { { boolean search = true ; while ( search ) { search = false ; for ( int a : axes ) { if ( a == useddim ) { search = true ; useddim ++ ; break ; } } } } m [ i ] [ useddim - 1 ] = 1.0 ; useddim ++ ; } assert ( useddim - 2 == dim ) ; return new AffineTransformation ( dim , m , null ) ; }
Generate a transformation that reorders axes in the given way .
33,401
public void addTranslation ( double [ ] v ) { assert ( v . length == dim ) ; inv = null ; double [ ] [ ] homTrans = unitMatrix ( dim + 1 ) ; for ( int i = 0 ; i < dim ; i ++ ) { homTrans [ i ] [ dim ] = v [ i ] ; } trans = times ( homTrans , trans ) ; }
Add a translation operation to the matrix
33,402
public void addMatrix ( double [ ] [ ] m ) { assert ( m . length == dim ) ; assert ( m [ 0 ] . length == dim ) ; inv = null ; double [ ] [ ] ht = new double [ dim + 1 ] [ dim + 1 ] ; for ( int i = 0 ; i < dim ; i ++ ) { for ( int j = 0 ; j < dim ; j ++ ) { ht [ i ] [ j ] = m [ i ] [ j ] ; } } ht [ dim ] [ dim ] = 1.0 ; trans = times ( ht , trans ) ; }
Add a matrix operation to the matrix .
33,403
public void addRotation ( int axis1 , int axis2 , double angle ) { assert ( axis1 >= 0 ) ; assert ( axis1 < dim ) ; assert ( axis1 >= 0 ) ; assert ( axis2 < dim ) ; assert ( axis1 != axis2 ) ; inv = null ; double [ ] [ ] ht = new double [ dim + 1 ] [ dim + 1 ] ; for ( int i = 0 ; i < dim + 1 ; i ++ ) { ht [ i ] [ i ] = 1.0 ; } final DoubleWrapper tmp = new DoubleWrapper ( ) ; double s = FastMath . sinAndCos ( angle , tmp ) , c = tmp . value ; ht [ axis1 ] [ axis1 ] = + c ; ht [ axis1 ] [ axis2 ] = - s ; ht [ axis2 ] [ axis1 ] = + s ; ht [ axis2 ] [ axis2 ] = + c ; trans = times ( ht , trans ) ; }
Convenience function to apply a rotation in 2 dimensions .
33,404
public void addAxisReflection ( int axis ) { assert ( 0 < axis && axis <= dim ) ; inv = null ; for ( int i = 0 ; i <= dim ; i ++ ) { trans [ axis - 1 ] [ i ] = - trans [ axis - 1 ] [ i ] ; } }
Add a reflection along the given axis .
33,405
public double [ ] homogeneVector ( double [ ] v ) { assert ( v . length == dim ) ; double [ ] dv = Arrays . copyOf ( v , dim + 1 ) ; dv [ dim ] = 1.0 ; return dv ; }
Transform an absolute vector into homogeneous coordinates .
33,406
public double [ ] homogeneRelativeVector ( double [ ] v ) { assert ( v . length == dim ) ; double [ ] dv = Arrays . copyOf ( v , dim + 1 ) ; dv [ dim ] = 0.0 ; return dv ; }
Transform a relative vector into homogeneous coordinates .
33,407
private double computeConfidence ( int support , int samples ) { final double z = NormalDistribution . standardNormalQuantile ( alpha ) ; final double eprob = support / ( double ) samples ; return Math . max ( 0. , eprob - z * FastMath . sqrt ( ( eprob * ( 1 - eprob ) ) / samples ) ) ; }
Estimate the confidence probability of a clustering .
33,408
protected Clustering < ? > runClusteringAlgorithm ( ResultHierarchy hierarchy , Result parent , DBIDs ids , DataStore < DoubleVector > store , int dim , String title ) { SimpleTypeInformation < DoubleVector > t = new VectorFieldTypeInformation < > ( DoubleVector . FACTORY , dim ) ; Relation < DoubleVector > sample = new MaterializedRelation < > ( t , ids , title , store ) ; ProxyDatabase d = new ProxyDatabase ( ids , sample ) ; Clustering < ? > clusterResult = samplesAlgorithm . run ( d ) ; d . getHierarchy ( ) . remove ( sample ) ; d . getHierarchy ( ) . remove ( clusterResult ) ; hierarchy . add ( parent , sample ) ; hierarchy . add ( sample , clusterResult ) ; return clusterResult ; }
Run a clustering algorithm on a single instance .
33,409
public static void load ( Class < ? > parent , ClassLoader cl ) { char [ ] buf = new char [ 0x4000 ] ; try { String fullName = RESOURCE_PREFIX + parent . getName ( ) ; Enumeration < URL > configfiles = cl . getResources ( fullName ) ; while ( configfiles . hasMoreElements ( ) ) { URL nextElement = configfiles . nextElement ( ) ; URLConnection conn = nextElement . openConnection ( ) ; conn . setUseCaches ( false ) ; try ( InputStreamReader is = new InputStreamReader ( conn . getInputStream ( ) , "UTF-8" ) ; ) { int start = 0 , cur = 0 , valid = is . read ( buf , 0 , buf . length ) ; char c ; while ( cur < valid ) { while ( cur < valid && ( c = buf [ cur ] ) != '\n' && c != '\r' ) { cur ++ ; } if ( cur == valid && is . ready ( ) ) { if ( start > 0 ) { System . arraycopy ( buf , start , buf , 0 , valid - start ) ; valid -= start ; cur -= start ; start = 0 ; } else if ( valid == buf . length ) { throw new IOException ( "Buffer size exceeded. Maximum line length in service files is: " + buf . length + " in file: " + fullName ) ; } valid = is . read ( buf , valid , buf . length - valid ) ; continue ; } parseLine ( parent , buf , start , cur ) ; while ( cur < valid && ( ( c = buf [ cur ] ) == '\n' || c == '\r' ) ) { cur ++ ; } start = cur ; } } catch ( IOException x ) { throw new AbortException ( "Error reading configuration file" , x ) ; } } } catch ( IOException x ) { throw new AbortException ( "Could not load service configuration files." , x ) ; } }
Load the service file .
33,410
private static void parseLine ( Class < ? > parent , char [ ] line , int begin , int end ) { while ( begin < end && line [ begin ] == ' ' ) { begin ++ ; } if ( begin >= end || line [ begin ] == '#' ) { return ; } int cend = begin + 1 ; while ( cend < end && line [ cend ] != ' ' ) { cend ++ ; } String cname = new String ( line , begin , cend - begin ) ; ELKIServiceRegistry . register ( parent , cname ) ; for ( int abegin = cend + 1 , aend = - 1 ; abegin < end ; abegin = aend + 1 ) { while ( abegin < end && line [ abegin ] == ' ' ) { abegin ++ ; } aend = abegin + 1 ; while ( aend < end && line [ aend ] != ' ' ) { aend ++ ; } ELKIServiceRegistry . registerAlias ( parent , new String ( line , abegin , aend - abegin ) , cname ) ; } return ; }
Parse a single line from a service registry file .
33,411
public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { super . readExternal ( in ) ; this . knnDistance = in . readDouble ( ) ; }
Calls the super method and reads the knn distance of this entry from the specified input stream .
33,412
private Pair < Pair < KNNQuery < O > , KNNQuery < O > > , Pair < RKNNQuery < O > , RKNNQuery < O > > > getKNNAndRkNNQueries ( Database database , Relation < O > relation , StepProgress stepprog ) { DistanceQuery < O > drefQ = database . getDistanceQuery ( relation , referenceDistanceFunction ) ; KNNQuery < O > kNNRefer = database . getKNNQuery ( drefQ , krefer , DatabaseQuery . HINT_HEAVY_USE , DatabaseQuery . HINT_OPTIMIZED_ONLY , DatabaseQuery . HINT_NO_CACHE ) ; RKNNQuery < O > rkNNRefer = database . getRKNNQuery ( drefQ , DatabaseQuery . HINT_HEAVY_USE , DatabaseQuery . HINT_OPTIMIZED_ONLY , DatabaseQuery . HINT_NO_CACHE ) ; if ( kNNRefer == null || rkNNRefer == null ) { if ( stepprog != null ) { stepprog . beginStep ( 1 , "Materializing neighborhood w.r.t. reference neighborhood distance function." , LOG ) ; } MaterializeKNNAndRKNNPreprocessor < O > preproc = new MaterializeKNNAndRKNNPreprocessor < > ( relation , referenceDistanceFunction , krefer ) ; kNNRefer = preproc . getKNNQuery ( drefQ , krefer , DatabaseQuery . HINT_HEAVY_USE ) ; rkNNRefer = preproc . getRKNNQuery ( drefQ , krefer , DatabaseQuery . HINT_HEAVY_USE ) ; database . getHierarchy ( ) . add ( relation , preproc ) ; } else { if ( stepprog != null ) { stepprog . beginStep ( 1 , "Optimized neighborhood w.r.t. reference neighborhood distance function provided by database." , LOG ) ; } } DistanceQuery < O > dreachQ = database . getDistanceQuery ( relation , reachabilityDistanceFunction ) ; KNNQuery < O > kNNReach = database . getKNNQuery ( dreachQ , kreach , DatabaseQuery . HINT_HEAVY_USE , DatabaseQuery . HINT_OPTIMIZED_ONLY , DatabaseQuery . HINT_NO_CACHE ) ; RKNNQuery < O > rkNNReach = database . getRKNNQuery ( dreachQ , DatabaseQuery . HINT_HEAVY_USE , DatabaseQuery . HINT_OPTIMIZED_ONLY , DatabaseQuery . HINT_NO_CACHE ) ; if ( kNNReach == null || rkNNReach == null ) { if ( stepprog != null ) { stepprog . beginStep ( 2 , "Materializing neighborhood w.r.t. reachability distance function." , LOG ) ; } ListParameterization config = new ListParameterization ( ) ; config . addParameter ( AbstractMaterializeKNNPreprocessor . Factory . DISTANCE_FUNCTION_ID , reachabilityDistanceFunction ) ; config . addParameter ( AbstractMaterializeKNNPreprocessor . Factory . K_ID , kreach ) ; MaterializeKNNAndRKNNPreprocessor < O > preproc = new MaterializeKNNAndRKNNPreprocessor < > ( relation , reachabilityDistanceFunction , kreach ) ; kNNReach = preproc . getKNNQuery ( dreachQ , kreach , DatabaseQuery . HINT_HEAVY_USE ) ; rkNNReach = preproc . getRKNNQuery ( dreachQ , kreach , DatabaseQuery . HINT_HEAVY_USE ) ; database . getHierarchy ( ) . add ( relation , preproc ) ; } Pair < KNNQuery < O > , KNNQuery < O > > kNNPair = new Pair < > ( kNNRefer , kNNReach ) ; Pair < RKNNQuery < O > , RKNNQuery < O > > rkNNPair = new Pair < > ( rkNNRefer , rkNNReach ) ; return new Pair < > ( kNNPair , rkNNPair ) ; }
Get the kNN and rkNN queries for the algorithm .
33,413
public COPACNeighborPredicate . Instance instantiate ( Database database , Relation < V > relation ) { DistanceQuery < V > dq = database . getDistanceQuery ( relation , EuclideanDistanceFunction . STATIC ) ; KNNQuery < V > knnq = database . getKNNQuery ( dq , settings . k ) ; WritableDataStore < COPACModel > storage = DataStoreUtil . makeStorage ( relation . getDBIDs ( ) , DataStoreFactory . HINT_HOT | DataStoreFactory . HINT_TEMP , COPACModel . class ) ; Duration time = LOG . newDuration ( this . getClass ( ) . getName ( ) + ".preprocessing-time" ) . begin ( ) ; FiniteProgress progress = LOG . isVerbose ( ) ? new FiniteProgress ( this . getClass ( ) . getName ( ) , relation . size ( ) , LOG ) : null ; for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { DoubleDBIDList ref = knnq . getKNNForDBID ( iditer , settings . k ) ; storage . put ( iditer , computeLocalModel ( iditer , ref , relation ) ) ; LOG . incrementProcessed ( progress ) ; } LOG . ensureCompleted ( progress ) ; LOG . statistics ( time . end ( ) ) ; return new Instance ( relation . getDBIDs ( ) , storage ) ; }
Full instantiation method .
33,414
protected COPACModel computeLocalModel ( DBIDRef id , DoubleDBIDList knnneighbors , Relation < V > relation ) { PCAResult epairs = settings . pca . processIds ( knnneighbors , relation ) ; int pdim = settings . filter . filter ( epairs . getEigenvalues ( ) ) ; PCAFilteredResult pcares = new PCAFilteredResult ( epairs . getEigenPairs ( ) , pdim , 1. , 0. ) ; double [ ] [ ] mat = pcares . similarityMatrix ( ) ; double [ ] vecP = relation . get ( id ) . toArray ( ) ; if ( pdim == vecP . length ) { return new COPACModel ( pdim , DBIDUtil . EMPTYDBIDS ) ; } HashSetModifiableDBIDs survivors = DBIDUtil . newHashSet ( ) ; for ( DBIDIter neighbor = relation . iterDBIDs ( ) ; neighbor . valid ( ) ; neighbor . advance ( ) ) { double [ ] diff = minusEquals ( relation . get ( neighbor ) . toArray ( ) , vecP ) ; double cdistP = transposeTimesTimes ( diff , mat , diff ) ; if ( cdistP <= epsilonsq ) { survivors . add ( neighbor ) ; } } return new COPACModel ( pdim , survivors ) ; }
COPAC model computation
33,415
public ModifiableHyperBoundingBox computeMBR ( ) { E firstEntry = getEntry ( 0 ) ; if ( firstEntry == null ) { return null ; } ModifiableHyperBoundingBox mbr = new ModifiableHyperBoundingBox ( firstEntry ) ; for ( int i = 1 ; i < numEntries ; i ++ ) { mbr . extend ( getEntry ( i ) ) ; } return mbr ; }
Recomputing the MBR is rather expensive .
33,416
public void applyCamera ( GL2 gl ) { gl . glMatrixMode ( GL2 . GL_PROJECTION ) ; gl . glLoadIdentity ( ) ; glu . gluPerspective ( 45f , width / ( float ) height , 0.f , 10.f ) ; eye [ 0 ] = ( float ) Math . sin ( theta ) * 2.f ; eye [ 1 ] = .5f ; eye [ 2 ] = ( float ) Math . cos ( theta ) * 2.f ; glu . gluLookAt ( eye [ 0 ] , eye [ 1 ] , eye [ 2 ] , .0f , .0f , 0.f , 0.f , 1.f , 0.f ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glLoadIdentity ( ) ; gl . glViewport ( 0 , 0 , width , height ) ; }
Apply the camera settings .
33,417
private void linearScanBatchKNN ( ArrayDBIDs ids , List < KNNHeap > heaps ) { final DistanceQuery < O > dq = distanceQuery ; for ( DBIDIter iter = getRelation ( ) . getDBIDs ( ) . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { int index = 0 ; for ( DBIDIter iter2 = ids . iter ( ) ; iter2 . valid ( ) ; iter2 . advance ( ) , index ++ ) { KNNHeap heap = heaps . get ( index ) ; heap . insert ( dq . distance ( iter2 , iter ) , iter ) ; } } }
Linear batch knn for arbitrary distance functions .
33,418
public static double [ ] [ ] computeWeightMatrix ( int bpp ) { final int dim = bpp * bpp * bpp ; final double [ ] [ ] m = new double [ dim ] [ dim ] ; final double max = 3. * ( bpp - 1. ) ; for ( int x = 0 ; x < dim ; x ++ ) { final int rx = ( x / bpp ) / bpp ; final int gx = ( x / bpp ) % bpp ; final int bx = x % bpp ; for ( int y = x ; y < dim ; y ++ ) { final int ry = ( y / bpp ) / bpp ; final int gy = ( y / bpp ) % bpp ; final int by = y % bpp ; final double dr = Math . abs ( rx - ry ) ; final double dg = Math . abs ( gx - gy ) ; final double db = Math . abs ( bx - by ) ; final double val = 1 - ( dr + dg + db ) / max ; m [ x ] [ y ] = m [ y ] [ x ] = val ; } } return m ; }
Compute weight matrix for a RGB color histogram
33,419
protected void initializeDataExtends ( Relation < NumberVector > relation , int dim , double [ ] min , double [ ] extend ) { assert ( min . length == dim && extend . length == dim ) ; if ( minima == null || maxima == null || minima . length == 0 || maxima . length == 0 ) { double [ ] [ ] minmax = RelationUtil . computeMinMax ( relation ) ; final double [ ] dmin = minmax [ 0 ] , dmax = minmax [ 1 ] ; for ( int d = 0 ; d < dim ; d ++ ) { min [ d ] = dmin [ d ] ; extend [ d ] = dmax [ d ] - dmin [ d ] ; } return ; } if ( minima . length == dim ) { System . arraycopy ( minima , 0 , min , 0 , dim ) ; } else if ( minima . length == 1 ) { Arrays . fill ( min , minima [ 0 ] ) ; } else { throw new AbortException ( "Invalid minima specified: expected " + dim + " got minima dimensionality: " + minima . length ) ; } if ( maxima . length == dim ) { for ( int d = 0 ; d < dim ; d ++ ) { extend [ d ] = maxima [ d ] - min [ d ] ; } return ; } else if ( maxima . length == 1 ) { for ( int d = 0 ; d < dim ; d ++ ) { extend [ d ] = maxima [ 0 ] - min [ d ] ; } return ; } else { throw new AbortException ( "Invalid maxima specified: expected " + dim + " got maxima dimensionality: " + maxima . length ) ; } }
Initialize the uniform sampling area .
33,420
static protected int countSharedNeighbors ( DBIDs neighbors1 , DBIDs neighbors2 ) { int intersection = 0 ; DBIDIter iter1 = neighbors1 . iter ( ) ; DBIDIter iter2 = neighbors2 . iter ( ) ; while ( iter1 . valid ( ) && iter2 . valid ( ) ) { final int comp = DBIDUtil . compare ( iter1 , iter2 ) ; if ( comp == 0 ) { intersection ++ ; iter1 . advance ( ) ; iter2 . advance ( ) ; } else if ( comp < 0 ) { iter1 . advance ( ) ; } else { iter2 . advance ( ) ; } } return intersection ; }
Compute the intersection size
33,421
protected static < O > DoubleIntPair [ ] rankReferencePoints ( DistanceQuery < O > distanceQuery , O obj , ArrayDBIDs referencepoints ) { DoubleIntPair [ ] priority = new DoubleIntPair [ referencepoints . size ( ) ] ; for ( DBIDArrayIter iter = referencepoints . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { final int i = iter . getOffset ( ) ; final double dist = distanceQuery . distance ( obj , iter ) ; priority [ i ] = new DoubleIntPair ( dist , i ) ; } Arrays . sort ( priority ) ; return priority ; }
Sort the reference points by distance to the query object
33,422
protected static void binarySearch ( ModifiableDoubleDBIDList index , DoubleDBIDListIter iter , double val ) { int left = 0 , right = index . size ( ) ; while ( left < right ) { final int mid = ( left + right ) >>> 1 ; final double curd = iter . seek ( mid ) . doubleValue ( ) ; if ( val < curd ) { right = mid ; } else if ( val > curd ) { left = mid + 1 ; } else { left = mid ; break ; } } if ( left >= index . size ( ) ) { -- left ; } iter . seek ( left ) ; }
Seek an iterator to the desired position using binary search .
33,423
public Result runAlgorithms ( Database database ) { ResultHierarchy hier = database . getHierarchy ( ) ; if ( LOG . isStatistics ( ) ) { boolean first = true ; for ( It < Index > it = hier . iterDescendants ( database ) . filter ( Index . class ) ; it . valid ( ) ; it . advance ( ) ) { if ( first ) { LOG . statistics ( "Index statistics before running algorithms:" ) ; first = false ; } it . get ( ) . logStatistics ( ) ; } } stepresult = new BasicResult ( "Algorithm Step" , "algorithm-step" ) ; for ( Algorithm algorithm : algorithms ) { Thread . currentThread ( ) . setName ( algorithm . toString ( ) ) ; Duration duration = LOG . isStatistics ( ) ? LOG . newDuration ( algorithm . getClass ( ) . getName ( ) + ".runtime" ) . begin ( ) : null ; Result res = algorithm . run ( database ) ; if ( duration != null ) { LOG . statistics ( duration . end ( ) ) ; } if ( LOG . isStatistics ( ) ) { boolean first = true ; for ( It < Index > it = hier . iterDescendants ( database ) . filter ( Index . class ) ; it . valid ( ) ; it . advance ( ) ) { if ( first ) { LOG . statistics ( "Index statistics after running algorithm " + algorithm . toString ( ) + ":" ) ; first = false ; } it . get ( ) . logStatistics ( ) ; } } if ( res != null ) { hier . add ( database , res ) ; } } return stepresult ; }
Run algorithms .
33,424
public CollectionResult < double [ ] > run ( Database database , Relation < O > rel ) { DistanceQuery < O > dq = rel . getDistanceQuery ( getDistanceFunction ( ) ) ; int size = rel . size ( ) ; long pairs = ( size * ( long ) size ) >> 1 ; final long ssize = sampling <= 1 ? ( long ) Math . ceil ( sampling * pairs ) : ( long ) sampling ; if ( ssize > Integer . MAX_VALUE ) { throw new AbortException ( "Sampling size too large." ) ; } final int qsize = quantile <= 0 ? 1 : ( int ) Math . ceil ( quantile * ssize ) ; DoubleMaxHeap heap = new DoubleMaxHeap ( qsize ) ; ArrayDBIDs ids = DBIDUtil . ensureArray ( rel . getDBIDs ( ) ) ; DBIDArrayIter i1 = ids . iter ( ) , i2 = ids . iter ( ) ; Random r = rand . getSingleThreadedRandom ( ) ; FiniteProgress prog = LOG . isVerbose ( ) ? new FiniteProgress ( "Sampling" , ( int ) ssize , LOG ) : null ; for ( long i = 0 ; i < ssize ; i ++ ) { int x = r . nextInt ( size - 1 ) + 1 , y = r . nextInt ( x ) ; double dist = dq . distance ( i1 . seek ( x ) , i2 . seek ( y ) ) ; if ( dist != dist || ( nozeros && dist < Double . MIN_NORMAL ) ) { continue ; } heap . add ( dist , qsize ) ; LOG . incrementProcessed ( prog ) ; } LOG . statistics ( new DoubleStatistic ( PREFIX + ".quantile" , quantile ) ) ; LOG . statistics ( new LongStatistic ( PREFIX + ".samplesize" , ssize ) ) ; LOG . statistics ( new DoubleStatistic ( PREFIX + ".distance" , heap . peek ( ) ) ) ; LOG . ensureCompleted ( prog ) ; Collection < String > header = Arrays . asList ( new String [ ] { "Distance" } ) ; Collection < double [ ] > data = Arrays . asList ( new double [ ] [ ] { new double [ ] { heap . peek ( ) } } ) ; return new CollectionResult < double [ ] > ( "Distances sample" , "distance-sample" , data , header ) ; }
Run the distance quantile sampler .
33,425
protected boolean parseLineInternal ( ) { int i = 0 ; for ( ; tokenizer . valid ( ) ; tokenizer . advance ( ) , i ++ ) { if ( ! isLabelColumn ( i ) && ! tokenizer . isQuoted ( ) ) { try { attributes . add ( tokenizer . getDouble ( ) ) ; continue ; } catch ( NumberFormatException e ) { if ( ! warnedPrecision && ( e == ParseUtil . PRECISION_OVERFLOW || e == ParseUtil . EXPONENT_OVERFLOW ) ) { getLogger ( ) . warning ( "Too many digits in what looked like a double number - treating as string: " + tokenizer . getSubstring ( ) ) ; warnedPrecision = true ; } } } String lbl = tokenizer . getStrippedSubstring ( ) ; if ( lbl . length ( ) > 0 ) { haslabels = true ; lbl = unique . addOrGet ( lbl ) ; labels . add ( lbl ) ; } } if ( curvec == null && attributes . size == 0 ) { columnnames = new ArrayList < > ( labels ) ; haslabels = false ; curvec = null ; curlbl = null ; labels . clear ( ) ; return false ; } curvec = createVector ( ) ; curlbl = LabelList . make ( labels ) ; attributes . clear ( ) ; labels . clear ( ) ; return true ; }
Internal method for parsing a single line . Used by both line based parsing as well as block parsing . This saves the building of meta data for each line .
33,426
SimpleTypeInformation < V > getTypeInformation ( int mindim , int maxdim ) { if ( mindim > maxdim ) { throw new AbortException ( "No vectors were read from the input file - cannot determine vector data type." ) ; } if ( mindim == maxdim ) { String [ ] colnames = null ; if ( columnnames != null && mindim <= columnnames . size ( ) ) { colnames = new String [ mindim ] ; int j = 0 ; for ( int i = 0 ; i < mindim ; i ++ ) { if ( isLabelColumn ( i ) ) { continue ; } colnames [ j ] = columnnames . get ( i ) ; j ++ ; } if ( j != mindim ) { colnames = null ; } } return new VectorFieldTypeInformation < > ( factory , mindim , colnames ) ; } return new VectorTypeInformation < > ( factory , factory . getDefaultSerializer ( ) , mindim , maxdim ) ; }
Get a prototype object for the given dimensionality .
33,427
private void materializeKNNAndRKNNs ( ArrayDBIDs ids , FiniteProgress progress ) { for ( DBIDIter iter = ids . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { if ( materialized_RkNN . get ( iter ) == null ) { materialized_RkNN . put ( iter , new TreeSet < DoubleDBIDPair > ( ) ) ; } } List < ? extends KNNList > kNNList = knnQuery . getKNNForBulkDBIDs ( ids , k ) ; for ( DBIDArrayIter id = ids . iter ( ) ; id . valid ( ) ; id . advance ( ) ) { KNNList kNNs = kNNList . get ( id . getOffset ( ) ) ; storage . put ( id , kNNs ) ; for ( DoubleDBIDListIter iter = kNNs . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { materialized_RkNN . get ( iter ) . add ( DBIDUtil . newPair ( iter . doubleValue ( ) , id ) ) ; } LOG . incrementProcessed ( progress ) ; } LOG . ensureCompleted ( progress ) ; }
Materializes the kNNs and RkNNs of the specified object IDs .
33,428
public DoubleDBIDList getRKNN ( DBIDRef id ) { TreeSet < DoubleDBIDPair > rKNN = materialized_RkNN . get ( id ) ; if ( rKNN == null ) { return null ; } ModifiableDoubleDBIDList ret = DBIDUtil . newDistanceDBIDList ( rKNN . size ( ) ) ; for ( DoubleDBIDPair pair : rKNN ) { ret . add ( pair ) ; } ret . sort ( ) ; return ret ; }
Returns the materialized RkNNs of the specified id .
33,429
public void insert ( NumberVector nv ) { final int dim = nv . getDimensionality ( ) ; if ( root == null ) { ClusteringFeature leaf = new ClusteringFeature ( dim ) ; leaf . addToStatistics ( nv ) ; root = new TreeNode ( dim , capacity ) ; root . children [ 0 ] = leaf ; root . addToStatistics ( nv ) ; ++ leaves ; return ; } TreeNode other = insert ( root , nv ) ; if ( other != null ) { TreeNode newnode = new TreeNode ( dim , capacity ) ; newnode . addToStatistics ( newnode . children [ 0 ] = root ) ; newnode . addToStatistics ( newnode . children [ 1 ] = other ) ; root = newnode ; } }
Insert a data point into the tree .
33,430
protected void rebuildTree ( ) { final int dim = root . getDimensionality ( ) ; double t = estimateThreshold ( root ) / leaves ; t *= t ; thresholdsq = t > thresholdsq ? t : thresholdsq ; LOG . debug ( "New squared threshold: " + thresholdsq ) ; LeafIterator iter = new LeafIterator ( root ) ; assert ( iter . valid ( ) ) ; ClusteringFeature first = iter . get ( ) ; leaves = 0 ; root = new TreeNode ( dim , capacity ) ; root . children [ 0 ] = first ; root . addToStatistics ( first ) ; ++ leaves ; for ( iter . advance ( ) ; iter . valid ( ) ; iter . advance ( ) ) { TreeNode other = insert ( root , iter . get ( ) ) ; if ( other != null ) { TreeNode newnode = new TreeNode ( dim , capacity ) ; newnode . addToStatistics ( newnode . children [ 0 ] = root ) ; newnode . addToStatistics ( newnode . children [ 1 ] = other ) ; root = newnode ; } } }
Rebuild the CFTree to condense it to approximately half the size .
33,431
private TreeNode insert ( TreeNode node , NumberVector nv ) { ClusteringFeature [ ] cfs = node . children ; assert ( cfs [ 0 ] != null ) : "Unexpected empty node!" ; ClusteringFeature best = cfs [ 0 ] ; double bestd = distance . squaredDistance ( nv , best ) ; for ( int i = 1 ; i < cfs . length ; i ++ ) { ClusteringFeature cf = cfs [ i ] ; if ( cf == null ) { break ; } double d2 = distance . squaredDistance ( nv , cf ) ; if ( d2 < bestd ) { best = cf ; bestd = d2 ; } } if ( ! ( best instanceof TreeNode ) ) { if ( absorption . squaredCriterion ( best , nv ) <= thresholdsq ) { best . addToStatistics ( nv ) ; node . addToStatistics ( nv ) ; return null ; } best = new ClusteringFeature ( nv . getDimensionality ( ) ) ; best . addToStatistics ( nv ) ; ++ leaves ; if ( add ( node . children , best ) ) { node . addToStatistics ( nv ) ; return null ; } return split ( node , best ) ; } assert ( best instanceof TreeNode ) : "Node is neither child nor inner?" ; TreeNode newchild = insert ( ( TreeNode ) best , nv ) ; if ( newchild == null || add ( node . children , newchild ) ) { node . addToStatistics ( nv ) ; return null ; } return split ( node , newchild ) ; }
Recursive insertion .
33,432
private boolean add ( ClusteringFeature [ ] children , ClusteringFeature child ) { for ( int i = 0 ; i < children . length ; i ++ ) { if ( children [ i ] == null ) { children [ i ] = child ; return true ; } } return false ; }
Add a node to the first unused slot .
33,433
protected StringBuilder printDebug ( StringBuilder buf , ClusteringFeature n , int d ) { FormatUtil . appendSpace ( buf , d ) . append ( n . n ) ; for ( int i = 0 ; i < n . getDimensionality ( ) ; i ++ ) { buf . append ( ' ' ) . append ( n . centroid ( i ) ) ; } buf . append ( " - " ) . append ( n . n ) . append ( '\n' ) ; if ( n instanceof TreeNode ) { ClusteringFeature [ ] children = ( ( TreeNode ) n ) . children ; for ( int i = 0 ; i < children . length ; i ++ ) { ClusteringFeature c = children [ i ] ; if ( c != null ) { printDebug ( buf , c , d + 1 ) ; } } } return buf ; }
Utility function for debugging .
33,434
public static double cdf ( double val , int v ) { double x = v / ( val * val + v ) ; return 1 - ( 0.5 * BetaDistribution . regularizedIncBeta ( x , v * .5 , 0.5 ) ) ; }
Static version of the CDF of the t - distribution for t &gt ; 0
33,435
public void add ( DBIDRef iter , int column , double score ) { changepoints . add ( new ChangePoint ( iter , column , score ) ) ; }
Add a change point to the result .
33,436
public void appendToBuffer ( StringBuilder buf ) { Iterator < Polygon > iter = polygons . iterator ( ) ; while ( iter . hasNext ( ) ) { Polygon poly = iter . next ( ) ; poly . appendToBuffer ( buf ) ; if ( iter . hasNext ( ) ) { buf . append ( " -- " ) ; } } }
Append polygons to the buffer .
33,437
public void initialize ( CharSequence input , int begin , int end ) { this . input = input ; this . send = end ; this . matcher . reset ( input ) . region ( begin , end ) ; this . index = begin ; advance ( ) ; }
Initialize parser with a new string .
33,438
public String getStrippedSubstring ( ) { int sstart = start , send = end ; while ( sstart < send ) { char c = input . charAt ( sstart ) ; if ( c != ' ' || c != '\n' || c != '\r' || c != '\t' ) { break ; } ++ sstart ; } while ( -- send >= sstart ) { char c = input . charAt ( send ) ; if ( c != ' ' || c != '\n' || c != '\r' || c != '\t' ) { break ; } } ++ send ; return ( sstart < send ) ? input . subSequence ( sstart , send ) . toString ( ) : "" ; }
Get the current part as substring
33,439
private char isQuote ( int index ) { if ( index >= input . length ( ) ) { return 0 ; } char c = input . charAt ( index ) ; for ( int i = 0 ; i < quoteChars . length ; i ++ ) { if ( c == quoteChars [ i ] ) { return c ; } } return 0 ; }
Detect quote characters .
33,440
public static WritableRecordStore makeRecordStorage ( DBIDs ids , int hints , Class < ? > ... dataclasses ) { return DataStoreFactory . FACTORY . makeRecordStorage ( ids , hints , dataclasses ) ; }
Make a new record storage to associate the given ids with an object of class dataclass .
33,441
public static int [ ] randomPermutation ( final int [ ] out , Random random ) { for ( int i = out . length - 1 ; i > 0 ; i -- ) { int ri = random . nextInt ( i + 1 ) ; int tmp = out [ ri ] ; out [ ri ] = out [ i ] ; out [ i ] = tmp ; } return out ; }
Perform a random permutation of the array in - place .
33,442
protected void makeRunnerIfNeeded ( ) { boolean stop = true ; for ( WeakReference < UpdateRunner > wur : updaterunner ) { UpdateRunner ur = wur . get ( ) ; if ( ur == null ) { updaterunner . remove ( wur ) ; } else if ( ! ur . isEmpty ( ) ) { stop = false ; } } if ( stop ) { return ; } if ( pending . get ( ) != null ) { return ; } JSVGComponent component = this . cref . get ( ) ; if ( component == null ) { return ; } synchronized ( this ) { synchronized ( component ) { UpdateManager um = component . getUpdateManager ( ) ; if ( um != null ) { synchronized ( um ) { if ( um . isRunning ( ) ) { Runnable newrunner = new Runnable ( ) { public void run ( ) { if ( pending . compareAndSet ( this , null ) ) { for ( WeakReference < UpdateRunner > wur : updaterunner ) { UpdateRunner ur = wur . get ( ) ; if ( ur == null || ur . isEmpty ( ) ) { continue ; } ur . runQueue ( ) ; } } } } ; pending . set ( newrunner ) ; um . getUpdateRunnableQueue ( ) . invokeLater ( newrunner ) ; return ; } } } } } }
Join the runnable queue of a component .
33,443
public void fullRedraw ( ) { if ( ! ( getWidth ( ) > 0 && getHeight ( ) > 0 ) ) { LoggingUtil . warning ( "Thumbnail of zero size requested: " + visFactory ) ; return ; } if ( thumbid < 0 ) { layer . appendChild ( SVGUtil . svgWaitIcon ( plot . getDocument ( ) , 0 , 0 , getWidth ( ) , getHeight ( ) ) ) ; if ( pendingThumbnail == null ) { pendingThumbnail = ThumbnailThread . queue ( this ) ; } return ; } Element i = plot . svgElement ( SVGConstants . SVG_IMAGE_TAG ) ; SVGUtil . setAtt ( i , SVGConstants . SVG_X_ATTRIBUTE , 0 ) ; SVGUtil . setAtt ( i , SVGConstants . SVG_Y_ATTRIBUTE , 0 ) ; SVGUtil . setAtt ( i , SVGConstants . SVG_WIDTH_ATTRIBUTE , getWidth ( ) ) ; SVGUtil . setAtt ( i , SVGConstants . SVG_HEIGHT_ATTRIBUTE , getHeight ( ) ) ; i . setAttributeNS ( SVGConstants . XLINK_NAMESPACE_URI , SVGConstants . XLINK_HREF_QNAME , ThumbnailRegistryEntry . INTERNAL_PROTOCOL + ":" + thumbid ) ; layer . appendChild ( i ) ; }
Perform a full redraw .
33,444
public static Centroid make ( Relation < ? extends NumberVector > relation , DBIDs ids ) { final int dim = RelationUtil . dimensionality ( relation ) ; Centroid c = new Centroid ( dim ) ; double [ ] elems = c . elements ; int count = 0 ; for ( DBIDIter iter = ids . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { NumberVector v = relation . get ( iter ) ; for ( int i = 0 ; i < dim ; i ++ ) { elems [ i ] += v . doubleValue ( i ) ; } count += 1 ; } if ( count == 0 ) { return c ; } for ( int i = 0 ; i < dim ; i ++ ) { elems [ i ] /= count ; } c . wsum = count ; return c ; }
Static constructor from an existing relation .
33,445
protected void firstRow ( double [ ] buf , int band , NumberVector v1 , NumberVector v2 , int dim2 ) { final double val1 = v1 . doubleValue ( 0 ) ; buf [ 0 ] = delta ( val1 , v2 . doubleValue ( 0 ) ) ; final int w = ( band >= dim2 ) ? dim2 - 1 : band ; for ( int j = 1 ; j <= w ; j ++ ) { buf [ j ] = buf [ j - 1 ] + delta ( val1 , v2 . doubleValue ( j ) ) ; } }
Fill the first row .
33,446
public double getWeight ( double distance , double max , double stddev ) { if ( stddev <= 0 ) { return 1 ; } double normdistance = distance / stddev ; return scaling * FastMath . exp ( - .5 * normdistance * normdistance ) / stddev ; }
Get Gaussian Weight using standard deviation for scaling . max is ignored .
33,447
public boolean nextLineExceptComments ( ) throws IOException { while ( nextLine ( ) ) { if ( comment == null || ! comment . reset ( buf ) . matches ( ) ) { tokenizer . initialize ( buf , 0 , buf . length ( ) ) ; return true ; } } return false ; }
Read the next line into the tokenizer .
33,448
public static Element makeArrow ( SVGPlot svgp , Direction dir , double x , double y , double size ) { final double hs = size / 2. ; switch ( dir ) { case LEFT : return new SVGPath ( ) . drawTo ( x + hs , y + hs ) . drawTo ( x - hs , y ) . drawTo ( x + hs , y - hs ) . drawTo ( x + hs , y + hs ) . close ( ) . makeElement ( svgp ) ; case DOWN : return new SVGPath ( ) . drawTo ( x - hs , y - hs ) . drawTo ( x + hs , y - hs ) . drawTo ( x , y + hs ) . drawTo ( x - hs , y - hs ) . close ( ) . makeElement ( svgp ) ; case RIGHT : return new SVGPath ( ) . drawTo ( x - hs , y - hs ) . drawTo ( x + hs , y ) . drawTo ( x - hs , y + hs ) . drawTo ( x - hs , y - hs ) . close ( ) . makeElement ( svgp ) ; case UP : return new SVGPath ( ) . drawTo ( x - hs , y + hs ) . drawTo ( x , y - hs ) . drawTo ( x + hs , y + hs ) . drawTo ( x - hs , y + hs ) . close ( ) . makeElement ( svgp ) ; default : throw new IllegalArgumentException ( "Unexpected direction: " + dir ) ; } }
Draw an arrow at the given position .
33,449
private double hammingDistanceNumberVector ( NumberVector o1 , NumberVector o2 ) { final int d1 = o1 . getDimensionality ( ) , d2 = o2 . getDimensionality ( ) ; int differences = 0 ; int d = 0 ; for ( ; d < d1 && d < d2 ; d ++ ) { double v1 = o1 . doubleValue ( d ) , v2 = o2 . doubleValue ( d ) ; if ( v1 != v1 || v2 != v2 ) { continue ; } if ( v1 != v2 ) { ++ differences ; } } for ( ; d < d1 ; d ++ ) { double v1 = o1 . doubleValue ( d ) ; if ( v1 != 0. && v1 == v1 ) { ++ differences ; } } for ( ; d < d2 ; d ++ ) { double v2 = o2 . doubleValue ( d ) ; if ( v2 != 0. && v2 == v2 ) { ++ differences ; } } return differences ; }
Version for number vectors .
33,450
public static long [ ] interleaveBits ( long [ ] coords , int iter ) { final int numdim = coords . length ; final long [ ] bitset = BitsUtil . zero ( numdim ) ; final long mask = 1L << 63 - iter ; for ( int dim = 0 ; dim < numdim ; dim ++ ) { if ( ( coords [ dim ] & mask ) != 0 ) { BitsUtil . setI ( bitset , dim ) ; } } return bitset ; }
Select the iter highest bit from each dimension .
33,451
public void visChanged ( VisualizationItem item ) { for ( int i = vlistenerList . size ( ) ; -- i >= 0 ; ) { final VisualizationListener listener = vlistenerList . get ( i ) ; if ( listener != null ) { listener . visualizationChanged ( item ) ; } } }
A visualization item has changed .
33,452
public static void setVisible ( VisualizerContext context , VisualizationTask task , boolean visibility ) { if ( visibility && task . isTool ( ) ) { Hierarchy < Object > vistree = context . getVisHierarchy ( ) ; for ( It < VisualizationTask > iter2 = vistree . iterAll ( ) . filter ( VisualizationTask . class ) ; iter2 . valid ( ) ; iter2 . advance ( ) ) { VisualizationTask other = iter2 . get ( ) ; if ( other != task && other . isTool ( ) && other . isVisible ( ) ) { context . visChanged ( other . visibility ( false ) ) ; } } } context . visChanged ( task . visibility ( visibility ) ) ; }
Utility function to change Visualizer visibility .
33,453
protected int findMerge ( int end , MatrixParadigm mat , PointerHierarchyRepresentationBuilder builder ) { assert ( end > 0 ) ; final DBIDArrayIter ix = mat . ix , iy = mat . iy ; final double [ ] matrix = mat . matrix ; double mindist = Double . POSITIVE_INFINITY ; int x = - 1 , y = - 1 ; for ( int ox = 0 , xbase = 0 ; ox < end ; xbase += ox ++ ) { if ( builder . isLinked ( ix . seek ( ox ) ) ) { continue ; } assert ( xbase == MatrixParadigm . triangleSize ( ox ) ) ; for ( int oy = 0 ; oy < ox ; oy ++ ) { if ( builder . isLinked ( iy . seek ( oy ) ) ) { continue ; } final double dist = matrix [ xbase + oy ] ; if ( dist <= mindist ) { mindist = dist ; x = ox ; y = oy ; } } } assert ( x >= 0 && y >= 0 ) ; assert ( y < x ) ; merge ( end , mat , builder , mindist , x , y ) ; return x ; }
Perform the next merge step in AGNES .
33,454
private void updateCholesky ( ) { CholeskyDecomposition chol = new CholeskyDecomposition ( covariance ) ; if ( ! chol . isSPD ( ) ) { double s = 0. ; for ( int i = 0 ; i < covariance . length ; i ++ ) { s += covariance [ i ] [ i ] ; } s *= SINGULARITY_CHEAT / covariance . length ; for ( int i = 0 ; i < covariance . length ; i ++ ) { covariance [ i ] [ i ] += s ; } chol = new CholeskyDecomposition ( covariance ) ; } if ( ! chol . isSPD ( ) ) { LOG . warning ( "A cluster has degenerated, likely due to lack of variance in a subset of the data or too extreme magnitude differences.\n" + "The algorithm will likely stop without converging, and fail to produce a good fit." ) ; chol = this . chol != null ? this . chol : chol ; } this . chol = chol ; logNormDet = FastMath . log ( weight ) - .5 * logNorm - getHalfLogDeterminant ( this . chol ) ; }
Update the cholesky decomposition .
33,455
public boolean validate ( Class < ? extends C > obj ) throws ParameterException { if ( obj == null ) { throw new UnspecifiedParameterException ( this ) ; } if ( ! restrictionClass . isAssignableFrom ( obj ) ) { throw new WrongParameterValueException ( this , obj . getName ( ) , "Given class not a subclass / implementation of " + restrictionClass . getName ( ) ) ; } return super . validate ( obj ) ; }
Checks if the given parameter value is valid for this ClassParameter . If not a parameter exception is thrown .
33,456
protected void addListeners ( ) { context . addResultListener ( this ) ; context . addVisualizationListener ( this ) ; if ( task . has ( UpdateFlag . ON_DATA ) ) { context . addDataStoreListener ( this ) ; } }
Add the listeners according to the mask .
33,457
public void addGenerator ( Distribution gen ) { if ( trans != null ) { throw new AbortException ( "Generators may no longer be added when transformations have been applied." ) ; } axes . add ( gen ) ; dim ++ ; }
Add a new generator to the cluster . No transformations must have been added so far!
33,458
public void addRotation ( int axis1 , int axis2 , double angle ) { if ( trans == null ) { trans = new AffineTransformation ( dim ) ; } trans . addRotation ( axis1 , axis2 , angle ) ; }
Apply a rotation to the generator
33,459
public void addTranslation ( double [ ] v ) { if ( trans == null ) { trans = new AffineTransformation ( dim ) ; } trans . addTranslation ( v ) ; }
Add a translation to the generator
33,460
public List < double [ ] > generate ( int count ) { ArrayList < double [ ] > result = new ArrayList < > ( count ) ; while ( result . size ( ) < count ) { double [ ] d = new double [ dim ] ; for ( int i = 0 ; i < dim ; i ++ ) { d [ i ] = axes . get ( i ) . nextRandom ( ) ; } if ( trans != null ) { d = trans . apply ( d ) ; } if ( testClipping ( d ) ) { if ( -- retries < 0 ) { throw new AbortException ( "Maximum retry count in generator exceeded." ) ; } continue ; } result . add ( d ) ; } return result ; }
Generate the given number of additional points .
33,461
public Clustering < MeanModel > run ( Database database , Relation < V > relation ) { final DBIDs ids = relation . getDBIDs ( ) ; double [ ] [ ] means = initializer . chooseInitialMeans ( database , relation , k , getDistanceFunction ( ) ) ; List < ModifiableDBIDs > clusters = new ArrayList < > ( ) ; for ( int i = 0 ; i < k ; i ++ ) { clusters . add ( DBIDUtil . newHashSet ( relation . size ( ) / k + 2 ) ) ; } final WritableDataStore < Meta > metas = initializeMeta ( relation , means ) ; ArrayModifiableDBIDs tids = initialAssignment ( clusters , metas , ids ) ; means = means ( clusters , means , relation ) ; means = refineResult ( relation , means , clusters , metas , tids ) ; Clustering < MeanModel > result = new Clustering < > ( "k-Means Samesize Clustering" , "kmeans-samesize-clustering" ) ; for ( int i = 0 ; i < clusters . size ( ) ; i ++ ) { result . addToplevelCluster ( new Cluster < > ( clusters . get ( i ) , new MeanModel ( means [ i ] ) ) ) ; } return result ; }
Run k - means with cluster size constraints .
33,462
protected WritableDataStore < Meta > initializeMeta ( Relation < V > relation , double [ ] [ ] means ) { NumberVectorDistanceFunction < ? super V > df = getDistanceFunction ( ) ; final WritableDataStore < Meta > metas = DataStoreUtil . makeStorage ( relation . getDBIDs ( ) , DataStoreFactory . HINT_HOT | DataStoreFactory . HINT_TEMP , Meta . class ) ; for ( DBIDIter id = relation . iterDBIDs ( ) ; id . valid ( ) ; id . advance ( ) ) { Meta c = new Meta ( k ) ; V fv = relation . get ( id ) ; for ( int i = 0 ; i < k ; i ++ ) { final double d = c . dists [ i ] = df . distance ( fv , DoubleVector . wrap ( means [ i ] ) ) ; if ( i > 0 ) { if ( d < c . dists [ c . primary ] ) { c . primary = i ; } else if ( d > c . dists [ c . secondary ] ) { c . secondary = i ; } } } metas . put ( id , c ) ; } return metas ; }
Initialize the metadata storage .
33,463
protected void transfer ( final WritableDataStore < Meta > metas , Meta meta , ModifiableDBIDs src , ModifiableDBIDs dst , DBIDRef id , int dstnum ) { src . remove ( id ) ; dst . add ( id ) ; meta . primary = dstnum ; metas . put ( id , meta ) ; }
Transfer a single element from one cluster to another .
33,464
public double toPValue ( double d , int n ) { double b = d / 30 + 1. / ( 36 * n ) ; double z = .5 * MathUtil . PISQUARE * MathUtil . PISQUARE * n * b ; if ( z < 1.1 || z > 8.5 ) { double e = FastMath . exp ( 0.3885037 - 1.164879 * z ) ; return ( e > 1 ) ? 1 : ( e < 0 ) ? 0 : e ; } for ( int i = 0 ; i < 86 ; i ++ ) { if ( TABPOS [ i ] >= z ) { if ( TABPOS [ i ] == z ) { return TABVAL [ i ] ; } double x1 = TABPOS [ i ] , x0 = TABPOS [ i - 1 ] ; double y1 = TABVAL [ i ] , y0 = TABVAL [ i - 1 ] ; return y0 + ( y1 - y0 ) * ( z - x0 ) / ( x1 - x0 ) ; } } return - 1 ; }
Convert Hoeffding D value to a p - value .
33,465
public static void run ( DBIDs ids , Processor ... procs ) { ParallelCore core = ParallelCore . getCore ( ) ; core . connect ( ) ; try { ArrayDBIDs aids = DBIDUtil . ensureArray ( ids ) ; final int size = aids . size ( ) ; int numparts = core . getParallelism ( ) ; numparts = ( size > numparts * numparts * 16 ) ? numparts * Math . max ( 1 , numparts - 1 ) : numparts ; final int blocksize = ( size + ( numparts - 1 ) ) / numparts ; List < Future < ArrayDBIDs > > parts = new ArrayList < > ( numparts ) ; for ( int i = 0 ; i < numparts ; i ++ ) { final int start = i * blocksize ; final int end = Math . min ( start + blocksize , size ) ; Callable < ArrayDBIDs > run = new BlockArrayRunner ( aids , start , end , procs ) ; parts . add ( core . submit ( run ) ) ; } for ( Future < ArrayDBIDs > fut : parts ) { fut . get ( ) ; } } catch ( ExecutionException e ) { throw new RuntimeException ( "Processor execution failed." , e ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "Parallel execution interrupted." ) ; } finally { core . disconnect ( ) ; } }
Run a task on all available CPUs .
33,466
public void replot ( ) { width = co . size ( ) ; height = ( int ) Math . ceil ( width * .2 ) ; ratio = width / ( double ) height ; height = height < MIN_HEIGHT ? MIN_HEIGHT : height > MAX_HEIGHT ? MAX_HEIGHT : height ; if ( scale == null ) { scale = computeScale ( co ) ; } BufferedImage img = new BufferedImage ( width , height , BufferedImage . TYPE_INT_ARGB ) ; int x = 0 ; for ( DBIDIter it = co . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { double reach = co . getReachability ( it ) ; final int y = scaleToPixel ( reach ) ; try { int col = colors . getColorForDBID ( it ) ; for ( int y2 = height - 1 ; y2 >= y ; y2 -- ) { img . setRGB ( x , y2 , col ) ; } } catch ( ArrayIndexOutOfBoundsException e ) { LOG . error ( "Plotting out of range: " + x + "," + y + " >= " + width + "x" + height ) ; } x ++ ; } plot = img ; }
Trigger a redraw of the OPTICS plot
33,467
public int scaleToPixel ( double reach ) { return ( Double . isInfinite ( reach ) || Double . isNaN ( reach ) ) ? 0 : ( int ) Math . round ( scale . getScaled ( reach , height - .5 , .5 ) ) ; }
Scale a reachability distance to a pixel value .
33,468
public String getSVGPlotURI ( ) { if ( plotnum < 0 ) { plotnum = ThumbnailRegistryEntry . registerImage ( plot ) ; } return ThumbnailRegistryEntry . INTERNAL_PREFIX + plotnum ; }
Get the SVG registered plot number
33,469
public static OPTICSPlot plotForClusterOrder ( ClusterOrder co , VisualizerContext context ) { final StylingPolicy policy = context . getStylingPolicy ( ) ; OPTICSPlot opticsplot = new OPTICSPlot ( co , policy ) ; return opticsplot ; }
Static method to find an optics plot for a result or to create a new one using the given context .
33,470
public double [ ] [ ] inverse ( ) { double [ ] [ ] b = new double [ piv . length ] [ m ] ; for ( int i = 0 ; i < piv . length ; i ++ ) { b [ piv [ i ] ] [ i ] = 1. ; } return solveInplace ( b ) ; }
Find the inverse matrix .
33,471
private boolean parseLine ( ) { cureid = null ; curpoly = null ; curlbl = null ; polys . clear ( ) ; coords . clear ( ) ; labels . clear ( ) ; Matcher m = COORD . matcher ( reader . getBuffer ( ) ) ; for ( ; tokenizer . valid ( ) ; tokenizer . advance ( ) ) { m . region ( tokenizer . getStart ( ) , tokenizer . getEnd ( ) ) ; if ( m . find ( ) ) { try { double c1 = ParseUtil . parseDouble ( m . group ( 1 ) ) ; double c2 = ParseUtil . parseDouble ( m . group ( 2 ) ) ; if ( m . group ( 3 ) != null ) { double c3 = ParseUtil . parseDouble ( m . group ( 3 ) ) ; coords . add ( new double [ ] { c1 , c2 , c3 } ) ; } else { coords . add ( new double [ ] { c1 , c2 } ) ; } continue ; } catch ( NumberFormatException e ) { LOG . warning ( "Looked like a coordinate pair but didn't parse: " + tokenizer . getSubstring ( ) ) ; } } final int len = tokenizer . getEnd ( ) - tokenizer . getStart ( ) ; if ( POLYGON_SEPARATOR . length ( ) == len && reader . getBuffer ( ) . subSequence ( tokenizer . getStart ( ) , tokenizer . getEnd ( ) ) . equals ( POLYGON_SEPARATOR ) ) { if ( ! coords . isEmpty ( ) ) { polys . add ( new Polygon ( new ArrayList < > ( coords ) ) ) ; } continue ; } String cur = tokenizer . getSubstring ( ) ; if ( cureid == null ) { cureid = new ExternalID ( cur ) ; } else { labels . add ( cur ) ; } } if ( ! coords . isEmpty ( ) ) { polys . add ( new Polygon ( coords ) ) ; } curpoly = new PolygonsObject ( polys ) ; curlbl = ( haslabels || ! labels . isEmpty ( ) ) ? LabelList . make ( labels ) : null ; return true ; }
Parse a single line .
33,472
public void runResultHandlers ( ResultHierarchy hier , Database db ) { for ( ResultHandler resulthandler : resulthandlers ) { Thread . currentThread ( ) . setName ( resulthandler . toString ( ) ) ; resulthandler . processNewResult ( hier , db ) ; } }
Run the result handlers .
33,473
@ SuppressWarnings ( "unchecked" ) public static void setDefaultHandlerVisualizer ( ) { defaultHandlers = new ArrayList < > ( 1 ) ; Class < ? extends ResultHandler > clz ; try { clz = ( Class < ? extends ResultHandler > ) Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( "de.lmu.ifi.dbs.elki.result.AutomaticVisualization" ) ; } catch ( ClassNotFoundException e ) { clz = ResultWriter . class ; } defaultHandlers . add ( clz ) ; }
Set the default handler to the Batik addon visualizer if available .
33,474
public synchronized void connect ( ) { if ( executor == null ) { executor = new ThreadPoolExecutor ( 0 , processors , 10L , TimeUnit . MILLISECONDS , new LinkedBlockingQueue < Runnable > ( ) ) ; executor . allowCoreThreadTimeOut ( true ) ; } if ( ++ connected == 1 ) { executor . allowCoreThreadTimeOut ( false ) ; executor . setCorePoolSize ( executor . getMaximumPoolSize ( ) ) ; } }
Connect to the executor .
33,475
public void add ( double x , double y ) { data . add ( x ) ; data . add ( y ) ; minx = Math . min ( minx , x ) ; maxx = Math . max ( maxx , x ) ; miny = Math . min ( miny , y ) ; maxy = Math . max ( maxy , y ) ; }
Add a coordinate pair but don t simplify
33,476
public void addAndSimplify ( double x , double y ) { final int len = data . size ( ) ; if ( len >= 4 ) { final double l1x = data . get ( len - 4 ) ; final double l1y = data . get ( len - 3 ) ; final double l2x = data . get ( len - 2 ) ; final double l2y = data . get ( len - 1 ) ; final double ldx = l2x - l1x ; final double ldy = l2y - l1y ; final double cdx = x - l2x ; final double cdy = y - l2y ; if ( ( ldx == 0 ) && ( cdx == 0 ) ) { data . remove ( len - 2 , 2 ) ; } else if ( ( ldy == 0 ) && ( cdy == 0 ) ) { data . remove ( len - 2 , 2 ) ; } else if ( ldy > 0 && cdy > 0 ) { if ( Math . abs ( ( ldx / ldy ) - ( cdx / cdy ) ) < THRESHOLD ) { data . remove ( len - 2 , 2 ) ; } } } add ( x , y ) ; }
Add a coordinate pair performing curve simplification if possible .
33,477
public void rescale ( double sx , double sy ) { for ( int i = 0 ; i < data . size ( ) ; i += 2 ) { data . set ( i , sx * data . get ( i ) ) ; data . set ( i + 1 , sy * data . get ( i + 1 ) ) ; } maxx *= sx ; maxy *= sy ; }
Rescale the graph .
33,478
private IndexTreePath < E > choosePath ( AbstractMTree < ? , N , E , ? > tree , E object , IndexTreePath < E > subtree ) { N node = tree . getNode ( subtree . getEntry ( ) ) ; if ( node . isLeaf ( ) ) { return subtree ; } int bestIdx = 0 ; E bestEntry = node . getEntry ( 0 ) ; double bestDistance = tree . distance ( object . getRoutingObjectID ( ) , bestEntry . getRoutingObjectID ( ) ) ; for ( int i = 1 ; i < node . getNumEntries ( ) ; i ++ ) { E entry = node . getEntry ( i ) ; double distance = tree . distance ( object . getRoutingObjectID ( ) , entry . getRoutingObjectID ( ) ) ; if ( distance < bestDistance ) { bestIdx = i ; bestEntry = entry ; bestDistance = distance ; } } return choosePath ( tree , object , new IndexTreePath < > ( subtree , bestEntry , bestIdx ) ) ; }
Chooses the best path of the specified subtree for insertion of the given object .
33,479
public void rewind ( ) { synchronized ( used ) { for ( ParameterPair pair : used ) { current . addParameter ( pair ) ; } used . clear ( ) ; } }
Rewind the configuration to the initial situation
33,480
public UniformDistribution estimate ( double min , double max , final int count ) { double grow = ( count > 1 ) ? 0.5 * ( max - min ) / ( count - 1 ) : 0. ; return new UniformDistribution ( Math . max ( min - grow , - Double . MAX_VALUE ) , Math . min ( max + grow , Double . MAX_VALUE ) ) ; }
Estimate from simple characteristics .
33,481
public static double cdf ( double val , double k , double lambda , double theta ) { return ( val > theta ) ? ( 1.0 - FastMath . exp ( - FastMath . pow ( ( val - theta ) / lambda , k ) ) ) : val == val ? 0.0 : Double . NaN ; }
CDF of Weibull distribution
33,482
public static double quantile ( double val , double k , double lambda , double theta ) { if ( val < 0.0 || val > 1.0 ) { return Double . NaN ; } else if ( val == 0 ) { return 0.0 ; } else if ( val == 1 ) { return Double . POSITIVE_INFINITY ; } else { return theta + lambda * FastMath . pow ( - FastMath . log ( 1.0 - val ) , 1.0 / k ) ; } }
Quantile function of Weibull distribution
33,483
public PCAResult processIds ( DBIDs ids , Relation < ? extends NumberVector > database ) { return processCovarMatrix ( covarianceMatrixBuilder . processIds ( ids , database ) ) ; }
Run PCA on a collection of database IDs .
33,484
public PCAResult processQueryResult ( DoubleDBIDList results , Relation < ? extends NumberVector > database ) { return processCovarMatrix ( covarianceMatrixBuilder . processQueryResults ( results , database ) ) ; }
Run PCA on a QueryResult Collection .
33,485
public boolean isFullRank ( ) { double t = 0. ; for ( int j = 0 ; j < n ; j ++ ) { double v = Rdiag [ j ] ; if ( v == 0 ) { return false ; } v = Math . abs ( v ) ; t = v > t ? v : t ; } t *= 1e-15 ; for ( int j = 1 ; j < n ; j ++ ) { if ( Math . abs ( Rdiag [ j ] ) < t ) { return false ; } } return true ; }
Is the matrix full rank?
33,486
public int rank ( double t ) { int rank = n ; for ( int j = 0 ; j < n ; j ++ ) { if ( Math . abs ( Rdiag [ j ] ) <= t ) { -- rank ; } } return rank ; }
Get the matrix rank?
33,487
private void setupCSS ( VisualizerContext context , SVGPlot svgp , XYPlot plot ) { StyleLibrary style = context . getStyleLibrary ( ) ; for ( XYPlot . Curve curve : plot ) { CSSClass csscls = new CSSClass ( this , SERIESID + curve . getColor ( ) ) ; csscls . setStatement ( SVGConstants . SVG_FILL_ATTRIBUTE , SVGConstants . SVG_NONE_VALUE ) ; style . lines ( ) . formatCSSClass ( csscls , curve . getColor ( ) , style . getLineWidth ( StyleLibrary . XYCURVE ) ) ; svgp . addCSSClassOrLogError ( csscls ) ; } CSSClass label = new CSSClass ( this , CSS_AXIS_LABEL ) ; label . setStatement ( SVGConstants . CSS_FILL_PROPERTY , style . getTextColor ( StyleLibrary . XYCURVE ) ) ; label . setStatement ( SVGConstants . CSS_FONT_FAMILY_PROPERTY , style . getFontFamily ( StyleLibrary . XYCURVE ) ) ; label . setStatement ( SVGConstants . CSS_FONT_SIZE_PROPERTY , style . getTextSize ( StyleLibrary . XYCURVE ) ) ; label . setStatement ( SVGConstants . CSS_TEXT_ANCHOR_PROPERTY , SVGConstants . CSS_MIDDLE_VALUE ) ; svgp . addCSSClassOrLogError ( label ) ; svgp . updateStyleElement ( ) ; }
Setup the CSS classes for the plot .
33,488
public int compareTo ( EigenPair o ) { if ( this . eigenvalue < o . eigenvalue ) { return - 1 ; } if ( this . eigenvalue > o . eigenvalue ) { return + 1 ; } return 0 ; }
Compares this object with the specified object for order . Returns a negative integer zero or a positive integer as this object s eigenvalue is greater than equal to or less than the specified object s eigenvalue .
33,489
protected static double calcPosterior ( double f , double alpha , double mu , double sigma , double lambda ) { final double pi = calcP_i ( f , mu , sigma ) ; final double qi = calcQ_i ( f , lambda ) ; return ( alpha * pi ) / ( alpha * pi + ( 1.0 - alpha ) * qi ) ; }
Compute the a posterior probability for the given parameters .
33,490
public void split ( ) { if ( hasChildren ( ) ) { return ; } final boolean issplit = ( maxSplitDimension >= ( getDimensionality ( ) - 1 ) ) ; final int childLevel = issplit ? level + 1 : level ; final int splitDim = issplit ? 0 : maxSplitDimension + 1 ; final double splitPoint = getMin ( splitDim ) + ( getMax ( splitDim ) - getMin ( splitDim ) ) * .5 ; for ( int i = 0 ; i < 2 ; i ++ ) { double [ ] min = SpatialUtil . getMin ( this ) ; double [ ] max = SpatialUtil . getMax ( this ) ; if ( i == 0 ) { min [ splitDim ] = splitPoint ; } else { max [ splitDim ] = splitPoint ; } ModifiableDBIDs childIDs = split . determineIDs ( getIDs ( ) , new HyperBoundingBox ( min , max ) , d_min , d_max ) ; if ( childIDs != null ) { if ( i == 0 ) { rightChild = new CASHInterval ( min , max , split , childIDs , splitDim , childLevel , d_min , d_max ) ; } else { leftChild = new CASHInterval ( min , max , split , childIDs , splitDim , childLevel , d_min , d_max ) ; } } } if ( LOG . isDebuggingFine ( ) ) { StringBuilder msg = new StringBuilder ( ) ; msg . append ( "Child level " ) . append ( childLevel ) . append ( ", split Dim " ) . append ( splitDim ) ; if ( leftChild != null ) { msg . append ( "\nleft " ) . append ( leftChild ) ; } if ( rightChild != null ) { msg . append ( "\nright " ) . append ( rightChild ) ; } LOG . fine ( msg . toString ( ) ) ; } }
Splits this interval into 2 children .
33,491
public void run ( ) { MultipleObjectsBundle data = generator . loadData ( ) ; if ( LOG . isVerbose ( ) ) { LOG . verbose ( "Writing output ..." ) ; } try { if ( outputFile . exists ( ) && LOG . isVerbose ( ) ) { LOG . verbose ( "The file " + outputFile + " already exists, " + "the generator result will be APPENDED." ) ; } try ( OutputStreamWriter outStream = new FileWriter ( outputFile , true ) ) { writeClusters ( outStream , data ) ; } } catch ( IOException e ) { throw new AbortException ( "IO Error in data generator." , e ) ; } if ( LOG . isVerbose ( ) ) { LOG . verbose ( "Done." ) ; } }
Runs the wrapper with the specified arguments .
33,492
private static long getGlobalSeed ( ) { String sseed = System . getProperty ( "elki.seed" ) ; return ( sseed != null ) ? Long . parseLong ( sseed ) : System . nanoTime ( ) ; }
Initialize the default random .
33,493
public double computeFirstCover ( boolean leaf ) { double max = 0. ; for ( DistanceEntry < E > e : firstAssignments ) { double cover = leaf ? e . getDistance ( ) : ( e . getEntry ( ) . getCoveringRadius ( ) + e . getDistance ( ) ) ; max = cover > max ? cover : max ; } return max ; }
Compute the covering radius of the first assignment .
33,494
public double computeSecondCover ( boolean leaf ) { double max = 0. ; for ( DistanceEntry < E > e : secondAssignments ) { double cover = leaf ? e . getDistance ( ) : ( e . getEntry ( ) . getCoveringRadius ( ) + e . getDistance ( ) ) ; max = cover > max ? cover : max ; } return max ; }
Compute the covering radius of the second assignment .
33,495
protected void offerAt ( final int pos , O e ) { if ( pos == NO_VALUE ) { if ( size + 1 > queue . length ) { resize ( size + 1 ) ; } index . put ( e , size ) ; size ++ ; heapifyUp ( size - 1 , e ) ; heapModified ( ) ; return ; } assert ( pos >= 0 ) : "Unexpected negative position." ; assert ( queue [ pos ] . equals ( e ) ) ; if ( comparator . compare ( e , queue [ pos ] ) >= 0 ) { return ; } heapifyUp ( pos , e ) ; heapModified ( ) ; return ; }
Offer element at the given position .
33,496
public O removeObject ( O e ) { int pos = index . getInt ( e ) ; return ( pos >= 0 ) ? removeAt ( pos ) : null ; }
Remove the given object from the queue .
33,497
private long sumMatrix ( int [ ] [ ] mat ) { long ret = 0 ; for ( int i = 0 ; i < mat . length ; i ++ ) { final int [ ] row = mat [ i ] ; for ( int j = 0 ; j < row . length ; j ++ ) { ret += row [ j ] ; } } return ret ; }
Compute the sum of a matrix .
33,498
private int countAboveThreshold ( int [ ] [ ] mat , double threshold ) { int ret = 0 ; for ( int i = 0 ; i < mat . length ; i ++ ) { int [ ] row = mat [ i ] ; for ( int j = 0 ; j < row . length ; j ++ ) { if ( row [ j ] >= threshold ) { ret ++ ; } } } return ret ; }
Count the number of cells above the threshold .
33,499
private int [ ] [ ] houghTransformation ( boolean [ ] [ ] mat ) { final int xres = mat . length , yres = mat [ 0 ] . length ; final double tscale = STEPS * .66 / ( xres + yres ) ; final int [ ] [ ] ret = new int [ STEPS ] [ STEPS ] ; for ( int x = 0 ; x < mat . length ; x ++ ) { final boolean [ ] row = mat [ x ] ; for ( int y = 0 ; y < mat [ 0 ] . length ; y ++ ) { if ( row [ y ] ) { for ( int i = 0 ; i < STEPS ; i ++ ) { final int d = ( STEPS >> 1 ) + ( int ) ( tscale * ( x * table . cos ( i ) + y * table . sin ( i ) ) ) ; if ( d > 0 && d < STEPS ) { ret [ d ] [ i ] ++ ; } } } } } return ret ; }
Perform a hough transformation on the binary image in mat .