idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
33,900
public static boolean almostEquals ( final double [ ] m1 , final double [ ] m2 , final double maxdelta ) { if ( m1 == m2 ) { return true ; } if ( m1 == null || m2 == null ) { return false ; } final int rowdim = m1 . length ; if ( rowdim != m2 . length ) { return false ; } for ( int i = 0 ; i < rowdim ; i ++ ) { if ( Math . abs ( m1 [ i ] - m2 [ i ] ) > maxdelta ) { return false ; } } return true ; }
Compare two matrices with a delta parameter to take numerical errors into account .
33,901
public static double angle ( double [ ] v1 , double [ ] v2 ) { final int mindim = ( v1 . length <= v2 . length ) ? v1 . length : v2 . length ; double s = 0 , e1 = 0 , e2 = 0 ; for ( int k = 0 ; k < mindim ; k ++ ) { final double r1 = v1 [ k ] , r2 = v2 [ k ] ; s += r1 * r2 ; e1 += r1 * r1 ; e2 += r2 * r2 ; } for ( int k = mindim ; k < v1 . length ; k ++ ) { final double r1 = v1 [ k ] ; e1 += r1 * r1 ; } for ( int k = mindim ; k < v2 . length ; k ++ ) { final double r2 = v2 [ k ] ; e2 += r2 * r2 ; } double a = FastMath . sqrt ( ( s / e1 ) * ( s / e2 ) ) ; return ( a < 1. ) ? a : 1. ; }
Compute the cosine of the angle between two vectors where the smaller angle between those vectors is viewed .
33,902
protected void updateFromSelection ( ) { DBIDSelection sel = context . getSelection ( ) ; if ( sel != null ) { this . dbids = DBIDUtil . newArray ( sel . getSelectedIds ( ) ) ; this . dbids . sort ( ) ; } else { this . dbids = DBIDUtil . newArray ( ) ; } }
Update our selection
33,903
public static DataStoreEvent insertionEvent ( DBIDs inserts ) { return new DataStoreEvent ( inserts , DBIDUtil . EMPTYDBIDS , DBIDUtil . EMPTYDBIDS ) ; }
Insertion event .
33,904
public static DataStoreEvent removalEvent ( DBIDs removals ) { return new DataStoreEvent ( DBIDUtil . EMPTYDBIDS , removals , DBIDUtil . EMPTYDBIDS ) ; }
Removal event .
33,905
public static DataStoreEvent updateEvent ( DBIDs updates ) { return new DataStoreEvent ( DBIDUtil . EMPTYDBIDS , DBIDUtil . EMPTYDBIDS , updates ) ; }
Update event .
33,906
private Visualization instantiateVisualization ( VisualizationTask task ) { try { Visualization v = task . getFactory ( ) . makeVisualization ( context , task , this , width , height , item . proj ) ; if ( task . has ( RenderFlag . NO_EXPORT ) ) { v . getLayer ( ) . setAttribute ( NO_EXPORT_ATTRIBUTE , NO_EXPORT_ATTRIBUTE ) ; } return v ; } catch ( Exception e ) { if ( LOG . isDebugging ( ) ) { LOG . warning ( "Visualizer " + task . getFactory ( ) . getClass ( ) . getName ( ) + " failed." , e ) ; } else { LOG . warning ( "Visualizer " + task . getFactory ( ) . getClass ( ) . getName ( ) + " failed - enable debugging to see details: " + e . toString ( ) ) ; } } return null ; }
Instantiate a visualization .
33,907
public void destroy ( ) { context . removeVisualizationListener ( this ) ; context . removeResultListener ( this ) ; for ( Entry < VisualizationTask , Visualization > v : taskmap . entrySet ( ) ) { Visualization vis = v . getValue ( ) ; if ( vis != null ) { vis . destroy ( ) ; } } taskmap . clear ( ) ; }
Cleanup function . To remove listeners .
33,908
private void lazyRefresh ( ) { Runnable pr = new Runnable ( ) { public void run ( ) { if ( pendingRefresh . compareAndSet ( this , null ) ) { refresh ( ) ; } } } ; pendingRefresh . set ( pr ) ; scheduleUpdate ( pr ) ; }
Trigger a refresh .
33,909
public boolean nextLine ( ) throws IOException { while ( reader . readLine ( buf . delete ( 0 , buf . length ( ) ) ) ) { ++ lineNumber ; if ( lengthWithoutLinefeed ( buf ) > 0 ) { return true ; } } return false ; }
Read the next line .
33,910
public static int lengthWithoutLinefeed ( CharSequence line ) { int length = line . length ( ) ; while ( length > 0 ) { char last = line . charAt ( length - 1 ) ; if ( last != '\n' && last != '\r' ) { break ; } -- length ; } return length ; }
Get the length of the string not taking trailing linefeeds into account .
33,911
public synchronized void logAndClearReportedErrors ( ) { for ( ParameterException e : getErrors ( ) ) { if ( LOG . isDebugging ( ) ) { LOG . warning ( e . getMessage ( ) , e ) ; } else { LOG . warning ( e . getMessage ( ) ) ; } } clearErrors ( ) ; }
Log any error that has accumulated .
33,912
public void addParameter ( Object owner , Parameter < ? > param , TrackParameters track ) { this . setBorder ( new SoftBevelBorder ( SoftBevelBorder . LOWERED ) ) ; ParameterConfigurator cfg = null ; { Object cur = owner ; while ( cur != null ) { cfg = childconfig . get ( cur ) ; if ( cfg != null ) { break ; } cur = track . getParent ( cur ) ; } } if ( cfg != null ) { cfg . addParameter ( owner , param , track ) ; return ; } else { cfg = makeConfigurator ( param ) ; cfg . addChangeListener ( this ) ; children . add ( cfg ) ; } }
Add parameter to this panel .
33,913
protected static < E extends MTreeEntry , N extends AbstractMTreeNode < ? , N , E > > double [ ] [ ] computeDistanceMatrix ( AbstractMTree < ? , N , E , ? > tree , N node ) { final int n = node . getNumEntries ( ) ; double [ ] [ ] distancematrix = new double [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { E ei = node . getEntry ( i ) ; double [ ] row_i = distancematrix [ i ] ; for ( int j = i + 1 ; j < n ; j ++ ) { row_i [ j ] = distancematrix [ j ] [ i ] = tree . distance ( ei , node . getEntry ( j ) ) ; } } return distancematrix ; }
Compute the pairwise distances in the given node .
33,914
protected static double sparsity ( final int setsize , final int dbsize , final int k , final double phi ) { final double fK = MathUtil . powi ( 1. / phi , k ) ; return ( setsize - ( dbsize * fK ) ) / FastMath . sqrt ( dbsize * fK * ( 1 - fK ) ) ; }
Method to calculate the sparsity coefficient of .
33,915
protected DBIDs computeSubspace ( int [ ] subspace , ArrayList < ArrayList < DBIDs > > ranges ) { HashSetModifiableDBIDs ids = DBIDUtil . newHashSet ( ranges . get ( subspace [ 0 ] ) . get ( subspace [ 1 ] ) ) ; for ( int i = 2 , e = subspace . length - 1 ; i < e ; i += 2 ) { DBIDs current = ranges . get ( subspace [ i ] ) . get ( subspace [ i + 1 ] - GENE_OFFSET ) ; ids . retainAll ( current ) ; if ( ids . isEmpty ( ) ) { break ; } } return ids ; }
Method to get the ids in the given subspace .
33,916
protected DBIDs computeSubspaceForGene ( short [ ] gene , ArrayList < ArrayList < DBIDs > > ranges ) { HashSetModifiableDBIDs m = null ; for ( int i = 0 ; i < gene . length ; i ++ ) { if ( gene [ i ] != DONT_CARE ) { DBIDs current = ranges . get ( i ) . get ( gene [ i ] - GENE_OFFSET ) ; if ( m == null ) { m = DBIDUtil . newHashSet ( current ) ; } else { m . retainAll ( current ) ; } } } assert ( m != null ) : "All genes set to '*', should not happen!" ; return m ; }
Get the DBIDs in the current subspace .
33,917
private static void updateFilterSDASet ( double mib , List < SteepDownArea > sdaset , double ixi ) { Iterator < SteepDownArea > iter = sdaset . iterator ( ) ; while ( iter . hasNext ( ) ) { SteepDownArea sda = iter . next ( ) ; if ( sda . getMaximum ( ) * ixi <= mib ) { iter . remove ( ) ; } else { if ( mib > sda . getMib ( ) ) { sda . setMib ( mib ) ; } } } }
Update the mib values of SteepDownAreas and remove obsolete areas .
33,918
private static void sort5 ( double [ ] keys , int [ ] vals , final int m1 , final int m2 , final int m3 , final int m4 , final int m5 ) { if ( keys [ m1 ] > keys [ m2 ] ) { swap ( keys , vals , m1 , m2 ) ; } if ( keys [ m3 ] > keys [ m4 ] ) { swap ( keys , vals , m3 , m4 ) ; } if ( keys [ m2 ] > keys [ m4 ] ) { swap ( keys , vals , m2 , m4 ) ; } if ( keys [ m1 ] > keys [ m3 ] ) { swap ( keys , vals , m1 , m3 ) ; } if ( keys [ m2 ] > keys [ m3 ] ) { swap ( keys , vals , m2 , m3 ) ; } if ( keys [ m4 ] > keys [ m5 ] ) { swap ( keys , vals , m4 , m5 ) ; if ( keys [ m3 ] > keys [ m4 ] ) { swap ( keys , vals , m3 , m4 ) ; if ( keys [ m2 ] > keys [ m3 ] ) { swap ( keys , vals , m2 , m3 ) ; if ( keys [ m1 ] > keys [ m1 ] ) { swap ( keys , vals , m1 , m2 ) ; } } } } }
An explicit sort for the five pivot candidates .
33,919
private static void swap ( double [ ] keys , int [ ] vals , int j , int i ) { double td = keys [ j ] ; keys [ j ] = keys [ i ] ; keys [ i ] = td ; int ti = vals [ j ] ; vals [ j ] = vals [ i ] ; vals [ i ] = ti ; }
Swap two entries .
33,920
public EvaluationResult . MeasurementGroup newGroup ( String string ) { EvaluationResult . MeasurementGroup g = new MeasurementGroup ( string ) ; groups . add ( g ) ; return g ; }
Add a new measurement group .
33,921
public EvaluationResult . MeasurementGroup findOrCreateGroup ( String label ) { for ( EvaluationResult . MeasurementGroup g : groups ) { if ( label . equals ( g . getName ( ) ) ) { return g ; } } return newGroup ( label ) ; }
Find or add a new measurement group .
33,922
public int numLines ( ) { int r = header . size ( ) ; for ( MeasurementGroup m : groups ) { r += 1 + m . measurements . size ( ) ; } return r ; }
Number of lines recommended for display .
33,923
public static EvaluationResult findOrCreate ( ResultHierarchy hierarchy , Result parent , String name , String shortname ) { ArrayList < EvaluationResult > ers = ResultUtil . filterResults ( hierarchy , parent , EvaluationResult . class ) ; EvaluationResult ev = null ; for ( EvaluationResult e : ers ) { if ( shortname . equals ( e . getShortName ( ) ) ) { ev = e ; break ; } } if ( ev == null ) { ev = new EvaluationResult ( name , shortname ) ; hierarchy . add ( parent , ev ) ; } return ev ; }
Find or create an evaluation result .
33,924
public Document cloneDocument ( DOMImplementation domImpl , Document document ) { Element root = document . getDocumentElement ( ) ; Document result = domImpl . createDocument ( root . getNamespaceURI ( ) , root . getNodeName ( ) , null ) ; Element rroot = result . getDocumentElement ( ) ; boolean before = true ; for ( Node n = document . getFirstChild ( ) ; n != null ; n = n . getNextSibling ( ) ) { if ( n == root ) { before = false ; copyAttributes ( result , root , rroot ) ; for ( Node c = root . getFirstChild ( ) ; c != null ; c = c . getNextSibling ( ) ) { final Node cl = cloneNode ( result , c ) ; if ( cl != null ) { rroot . appendChild ( cl ) ; } } } else { if ( n . getNodeType ( ) != Node . DOCUMENT_TYPE_NODE ) { final Node cl = cloneNode ( result , n ) ; if ( cl != null ) { if ( before ) { result . insertBefore ( cl , rroot ) ; } else { result . appendChild ( cl ) ; } } } } } return result ; }
Deep - clone a document .
33,925
public Node cloneNode ( Document doc , Node eold ) { return doc . importNode ( eold , true ) ; }
Clone an existing node .
33,926
public void copyAttributes ( Document doc , Element eold , Element enew ) { if ( eold . hasAttributes ( ) ) { NamedNodeMap attr = eold . getAttributes ( ) ; int len = attr . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { enew . setAttributeNode ( ( Attr ) doc . importNode ( attr . item ( i ) , true ) ) ; } } }
Copy the attributes from an existing node to a new node .
33,927
protected String getFilename ( Object result , String filenamepre ) { if ( filenamepre == null || filenamepre . length ( ) == 0 ) { filenamepre = "result" ; } for ( int i = 0 ; ; i ++ ) { String filename = i > 0 ? filenamepre + "-" + i : filenamepre ; Object existing = filenames . get ( filename ) ; if ( existing == null || existing == result ) { filenames . put ( filename , result ) ; return filename ; } } }
Try to find a unique file name .
33,928
@ SuppressWarnings ( "unchecked" ) public void output ( Database db , Result r , StreamFactory streamOpener , Pattern filter ) throws IOException { List < Relation < ? > > ra = new LinkedList < > ( ) ; List < OrderingResult > ro = new LinkedList < > ( ) ; List < Clustering < ? > > rc = new LinkedList < > ( ) ; List < IterableResult < ? > > ri = new LinkedList < > ( ) ; List < SettingsResult > rs = new LinkedList < > ( ) ; List < Result > otherres = new LinkedList < > ( ) ; { List < Result > results = ResultUtil . filterResults ( db . getHierarchy ( ) , r , Result . class ) ; for ( Result res : results ) { if ( filter != null ) { final String nam = res . getShortName ( ) ; if ( nam == null || ! filter . matcher ( nam ) . find ( ) ) { continue ; } } if ( res instanceof Database ) { continue ; } if ( res instanceof Relation ) { ra . add ( ( Relation < ? > ) res ) ; continue ; } if ( res instanceof OrderingResult ) { ro . add ( ( OrderingResult ) res ) ; continue ; } if ( res instanceof Clustering ) { rc . add ( ( Clustering < ? > ) res ) ; continue ; } if ( res instanceof IterableResult ) { ri . add ( ( IterableResult < ? > ) res ) ; continue ; } if ( res instanceof SettingsResult ) { rs . add ( ( SettingsResult ) res ) ; continue ; } otherres . add ( res ) ; } } writeSettingsResult ( streamOpener , rs ) ; for ( IterableResult < ? > rii : ri ) { writeIterableResult ( streamOpener , rii ) ; } for ( Clustering < ? > c : rc ) { NamingScheme naming = new SimpleEnumeratingScheme ( c ) ; for ( Cluster < ? > clus : c . getAllClusters ( ) ) { writeClusterResult ( db , streamOpener , ( Clustering < Model > ) c , ( Cluster < Model > ) clus , ra , naming ) ; } } for ( OrderingResult ror : ro ) { writeOrderingResult ( db , streamOpener , ror , ra ) ; } for ( Result otherr : otherres ) { writeOtherResult ( streamOpener , otherr ) ; } }
Stream output .
33,929
public void writeExternal ( ObjectOutput out ) throws IOException { super . writeExternal ( out ) ; out . writeObject ( approximation ) ; }
Calls the super method and writes the polynomiale approximation of the knn distances of this entry to the specified stream .
33,930
public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { super . readExternal ( in ) ; approximation = ( PolynomialApproximation ) in . readObject ( ) ; }
Calls the super method and reads the the polynomial approximation of the knn distances of this entry from the specified input stream .
33,931
private WritableIntegerDataStore computeSubtreeSizes ( DBIDs order ) { WritableIntegerDataStore siz = DataStoreUtil . makeIntegerStorage ( ids , DataStoreFactory . HINT_HOT | DataStoreFactory . HINT_TEMP , 1 ) ; DBIDVar v1 = DBIDUtil . newVar ( ) ; for ( DBIDIter it = order . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { if ( DBIDUtil . equal ( it , parent . assignVar ( it , v1 ) ) ) { continue ; } siz . increment ( v1 , siz . intValue ( it ) ) ; } return siz ; }
Compute the size of all subtrees .
33,932
private WritableDoubleDataStore computeMaxHeight ( ) { WritableDoubleDataStore maxheight = DataStoreUtil . makeDoubleStorage ( ids , DataStoreFactory . HINT_HOT | DataStoreFactory . HINT_TEMP , 0. ) ; DBIDVar v1 = DBIDUtil . newVar ( ) ; for ( DBIDIter it = ids . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { double d = parentDistance . doubleValue ( it ) ; if ( d > maxheight . doubleValue ( it ) ) { maxheight . putDouble ( it , d ) ; } if ( d > maxheight . doubleValue ( parent . assignVar ( it , v1 ) ) ) { maxheight . putDouble ( v1 , d ) ; } } return maxheight ; }
Compute the maximum height of nodes .
33,933
public ArrayDBIDs topologicalSort ( ) { ArrayModifiableDBIDs ids = DBIDUtil . newArray ( this . ids ) ; if ( mergeOrder != null ) { ids . sort ( new DataStoreUtil . AscendingByIntegerDataStore ( mergeOrder ) ) ; WritableDoubleDataStore maxheight = computeMaxHeight ( ) ; ids . sort ( new Sorter ( maxheight ) ) ; maxheight . destroy ( ) ; } else { ids . sort ( new DataStoreUtil . DescendingByDoubleDataStoreAndId ( parentDistance ) ) ; } final int size = ids . size ( ) ; ModifiableDBIDs seen = DBIDUtil . newHashSet ( size ) ; ArrayModifiableDBIDs order = DBIDUtil . newArray ( size ) ; DBIDVar v1 = DBIDUtil . newVar ( ) , prev = DBIDUtil . newVar ( ) ; for ( DBIDIter it = ids . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { if ( ! seen . add ( it ) ) { continue ; } final int begin = order . size ( ) ; order . add ( it ) ; prev . set ( it ) ; while ( ! DBIDUtil . equal ( prev , parent . assignVar ( prev , v1 ) ) ) { if ( ! seen . add ( v1 ) ) { break ; } order . add ( v1 ) ; prev . set ( v1 ) ; } for ( int i = begin , j = order . size ( ) - 1 ; i < j ; i ++ , j -- ) { order . swap ( i , j ) ; } } for ( int i = 0 , j = size - 1 ; i < j ; i ++ , j -- ) { order . swap ( i , j ) ; } return order ; }
Topological sort the object IDs .
33,934
public static int [ ] range ( int start , int end ) { int [ ] out = new int [ end - start ] ; for ( int i = 0 , j = start ; j < end ; i ++ , j ++ ) { out [ i ] = j ; } return out ; }
Initialize an integer value range .
33,935
private void doReverseKNNQuery ( int k , DBIDRef q , ModifiableDoubleDBIDList result , ModifiableDBIDs candidates ) { final ComparableMinHeap < MTreeSearchCandidate > pq = new ComparableMinHeap < > ( ) ; pq . add ( new MTreeSearchCandidate ( 0. , getRootID ( ) , null , Double . NaN ) ) ; while ( ! pq . isEmpty ( ) ) { MTreeSearchCandidate pqNode = pq . poll ( ) ; MkCoPTreeNode < O > node = getNode ( pqNode . nodeID ) ; if ( ! node . isLeaf ( ) ) { for ( int i = 0 ; i < node . getNumEntries ( ) ; i ++ ) { MkCoPEntry entry = node . getEntry ( i ) ; double distance = distance ( entry . getRoutingObjectID ( ) , q ) ; double minDist = entry . getCoveringRadius ( ) > distance ? 0. : distance - entry . getCoveringRadius ( ) ; double approximatedKnnDist_cons = entry . approximateConservativeKnnDistance ( k ) ; if ( minDist <= approximatedKnnDist_cons ) { pq . add ( new MTreeSearchCandidate ( minDist , getPageID ( entry ) , entry . getRoutingObjectID ( ) , Double . NaN ) ) ; } } } else { for ( int i = 0 ; i < node . getNumEntries ( ) ; i ++ ) { MkCoPLeafEntry entry = ( MkCoPLeafEntry ) node . getEntry ( i ) ; double distance = distance ( entry . getRoutingObjectID ( ) , q ) ; double approximatedKnnDist_prog = entry . approximateProgressiveKnnDistance ( k ) ; if ( distance <= approximatedKnnDist_prog ) { result . add ( distance , entry . getRoutingObjectID ( ) ) ; } else { double approximatedKnnDist_cons = entry . approximateConservativeKnnDistance ( k ) ; double diff = distance - approximatedKnnDist_cons ; if ( diff <= 1E-10 ) { candidates . add ( entry . getRoutingObjectID ( ) ) ; } } } } } }
Performs a reverse knn query .
33,936
protected void expirePage ( P page ) { if ( LOG . isDebuggingFine ( ) ) { LOG . debugFine ( "Write to backing:" + page . getPageID ( ) ) ; } if ( page . isDirty ( ) ) { file . writePage ( page ) ; } }
Write page through to disk .
33,937
public void setCacheSize ( int cacheSize ) { this . cacheSize = cacheSize ; long toDelete = map . size ( ) - this . cacheSize ; if ( toDelete <= 0 ) { return ; } List < Integer > keys = new ArrayList < > ( map . keySet ( ) ) ; Collections . reverse ( keys ) ; for ( Integer id : keys ) { P page = map . remove ( id ) ; file . writePage ( page ) ; } }
Sets the maximum size of this cache .
33,938
public static String getFilenameExtension ( String name ) { if ( name == null ) { return null ; } int index = name . lastIndexOf ( '.' ) ; return index < 0 ? null : name . substring ( index + 1 ) . toLowerCase ( ) ; }
Returns the lower case extension of the selected file .
33,939
public static InputStream tryGzipInput ( InputStream in ) throws IOException { if ( ! in . markSupported ( ) ) { PushbackInputStream pb = new PushbackInputStream ( in , 16 ) ; byte [ ] magic = { 0 , 0 } ; int r = pb . read ( magic ) ; pb . unread ( magic , 0 , r ) ; return ( magic [ 0 ] == 31 && magic [ 1 ] == - 117 ) ? new GZIPInputStream ( pb ) : pb ; } in . mark ( 16 ) ; boolean isgzip = ( ( in . read ( ) << 8 ) | in . read ( ) ) == GZIPInputStream . GZIP_MAGIC ; in . reset ( ) ; return isgzip ? new GZIPInputStream ( in ) : in ; }
Try to open a stream as gzip if it starts with the gzip magic .
33,940
public static File locateFile ( String name , String basedir ) { File f = new File ( name ) ; if ( f . exists ( ) ) { return f ; } if ( basedir != null ) { if ( ( f = new File ( basedir , name ) ) . exists ( ) ) { return f ; } } String name2 ; if ( ! name . equals ( name2 = name . trim ( ) ) ) { if ( ( f = locateFile ( name2 , basedir ) ) != null ) { return f ; } } if ( ! name . equals ( name2 = name . replace ( '/' , File . separatorChar ) ) ) { if ( ( f = locateFile ( name2 , basedir ) ) != null ) { return f ; } } if ( ! name . equals ( name2 = name . replace ( '\\' , File . separatorChar ) ) ) { if ( ( f = locateFile ( name2 , basedir ) ) != null ) { return f ; } } if ( name . length ( ) > 2 && name . charAt ( 0 ) == '"' && name . charAt ( name . length ( ) - 1 ) == '"' ) { if ( ( f = locateFile ( name . substring ( 1 , name . length ( ) - 1 ) , basedir ) ) != null ) { return f ; } } return null ; }
Try to locate an file in the filesystem given a partial name and a prefix .
33,941
protected void addInternal ( double dist , int id ) { if ( size == dists . length ) { grow ( ) ; } dists [ size ] = dist ; ids [ size ] = id ; ++ size ; }
Add an entry consisting of distance and internal index .
33,942
protected void grow ( ) { if ( dists == EMPTY_DISTS ) { dists = new double [ INITIAL_SIZE ] ; ids = new int [ INITIAL_SIZE ] ; return ; } final int len = dists . length ; final int newlength = len + ( len >> 1 ) + 1 ; double [ ] odists = dists ; dists = new double [ newlength ] ; System . arraycopy ( odists , 0 , dists , 0 , odists . length ) ; int [ ] oids = ids ; ids = new int [ newlength ] ; System . arraycopy ( oids , 0 , ids , 0 , oids . length ) ; }
Grow the data storage .
33,943
protected void reverse ( ) { for ( int i = 0 , j = size - 1 ; i < j ; i ++ , j -- ) { double tmpd = dists [ j ] ; dists [ j ] = dists [ i ] ; dists [ i ] = tmpd ; int tmpi = ids [ j ] ; ids [ j ] = ids [ i ] ; ids [ i ] = tmpi ; } }
Reverse the list .
33,944
public void truncate ( int newsize ) { if ( newsize < size ) { double [ ] odists = dists ; dists = new double [ newsize ] ; System . arraycopy ( odists , 0 , dists , 0 , newsize ) ; int [ ] oids = ids ; ids = new int [ newsize ] ; System . arraycopy ( oids , 0 , ids , 0 , newsize ) ; size = newsize ; } }
Truncate the list to the given size freeing the memory .
33,945
private RectangleArranger < PlotItem > arrangeVisualizations ( double width , double height ) { if ( ! ( width > 0. && height > 0. ) ) { LOG . warning ( "No size information during arrange()" , new Throwable ( ) ) ; return new RectangleArranger < > ( 1. , 1. ) ; } RectangleArranger < PlotItem > plotmap = new RectangleArranger < > ( width , height ) ; Hierarchy < Object > vistree = context . getVisHierarchy ( ) ; for ( It < Projector > iter2 = vistree . iterAll ( ) . filter ( Projector . class ) ; iter2 . valid ( ) ; iter2 . advance ( ) ) { Collection < PlotItem > projs = iter2 . get ( ) . arrange ( context ) ; for ( PlotItem it : projs ) { if ( it . w <= 0.0 || it . h <= 0.0 ) { LOG . warning ( "Plot item with improper size information: " + it ) ; continue ; } plotmap . put ( it . w , it . h , it ) ; } } nextTask : for ( It < VisualizationTask > iter2 = vistree . iterAll ( ) . filter ( VisualizationTask . class ) ; iter2 . valid ( ) ; iter2 . advance ( ) ) { VisualizationTask task = iter2 . get ( ) ; if ( ! task . isVisible ( ) ) { continue ; } if ( vistree . iterParents ( task ) . filter ( Projector . class ) . valid ( ) ) { continue nextTask ; } if ( task . getRequestedWidth ( ) <= 0.0 || task . getRequestedHeight ( ) <= 0.0 ) { LOG . warning ( "Task with improper size information: " + task ) ; continue ; } PlotItem it = new PlotItem ( task . getRequestedWidth ( ) , task . getRequestedHeight ( ) , null ) ; it . tasks . add ( task ) ; plotmap . put ( it . w , it . h , it ) ; } return plotmap ; }
Recompute the layout of visualizations .
33,946
public void initialize ( double ratio ) { if ( ! ( ratio > 0 && ratio < Double . POSITIVE_INFINITY ) ) { LOG . warning ( "Invalid ratio: " + ratio , new Throwable ( ) ) ; ratio = 1.4 ; } this . ratio = ratio ; if ( plot != null ) { LOG . warning ( "Already initialized." ) ; lazyRefresh ( ) ; return ; } reinitialize ( ) ; context . addResultListener ( this ) ; context . addVisualizationListener ( this ) ; }
Initialize the plot .
33,947
private void initializePlot ( ) { plot = new VisualizationPlot ( ) ; { CSSClass cls = new CSSClass ( this , "background" ) ; final String bgcol = context . getStyleLibrary ( ) . getBackgroundColor ( StyleLibrary . PAGE ) ; cls . setStatement ( SVGConstants . CSS_FILL_PROPERTY , bgcol ) ; plot . addCSSClassOrLogError ( cls ) ; Element background = plot . svgElement ( SVGConstants . SVG_RECT_TAG ) ; background . setAttribute ( SVGConstants . SVG_X_ATTRIBUTE , "0" ) ; background . setAttribute ( SVGConstants . SVG_Y_ATTRIBUTE , "0" ) ; background . setAttribute ( SVGConstants . SVG_WIDTH_ATTRIBUTE , "100%" ) ; background . setAttribute ( SVGConstants . SVG_HEIGHT_ATTRIBUTE , "100%" ) ; SVGUtil . setCSSClass ( background , cls . getName ( ) ) ; if ( "white" . equals ( bgcol ) ) { background . setAttribute ( SVGPlot . NO_EXPORT_ATTRIBUTE , SVGPlot . NO_EXPORT_ATTRIBUTE ) ; } plot . getRoot ( ) . appendChild ( background ) ; } { selcss = new CSSClass ( this , "s" ) ; if ( DEBUG_LAYOUT ) { selcss . setStatement ( SVGConstants . CSS_STROKE_PROPERTY , SVGConstants . CSS_RED_VALUE ) ; selcss . setStatement ( SVGConstants . CSS_STROKE_WIDTH_PROPERTY , .00001 * StyleLibrary . SCALE ) ; selcss . setStatement ( SVGConstants . CSS_STROKE_OPACITY_PROPERTY , "0.5" ) ; } selcss . setStatement ( SVGConstants . CSS_FILL_PROPERTY , SVGConstants . CSS_RED_VALUE ) ; selcss . setStatement ( SVGConstants . CSS_FILL_OPACITY_PROPERTY , "0" ) ; selcss . setStatement ( SVGConstants . CSS_CURSOR_PROPERTY , SVGConstants . CSS_POINTER_VALUE ) ; plot . addCSSClassOrLogError ( selcss ) ; CSSClass hovcss = new CSSClass ( this , "h" ) ; hovcss . setStatement ( SVGConstants . CSS_FILL_OPACITY_PROPERTY , "0.25" ) ; plot . addCSSClassOrLogError ( hovcss ) ; hoverer = new CSSHoverClass ( hovcss . getName ( ) , null , true ) ; } if ( single ) { plot . setDisableInteractions ( true ) ; } SVGEffects . addShadowFilter ( plot ) ; SVGEffects . addLightGradient ( plot ) ; }
Initialize the SVG plot .
33,948
private Visualization embedOrThumbnail ( final int thumbsize , PlotItem it , VisualizationTask task , Element parent ) { final Visualization vis ; if ( ! single ) { vis = task . getFactory ( ) . makeVisualizationOrThumbnail ( context , task , plot , it . w , it . h , it . proj , thumbsize ) ; } else { vis = task . getFactory ( ) . makeVisualization ( context , task , plot , it . w , it . h , it . proj ) ; } if ( vis == null || vis . getLayer ( ) == null ) { LOG . warning ( "Visualization returned empty layer: " + vis ) ; return vis ; } if ( task . has ( RenderFlag . NO_EXPORT ) ) { vis . getLayer ( ) . setAttribute ( SVGPlot . NO_EXPORT_ATTRIBUTE , SVGPlot . NO_EXPORT_ATTRIBUTE ) ; } parent . appendChild ( vis . getLayer ( ) ) ; return vis ; }
Produce thumbnail for a visualizer .
33,949
protected boolean visibleInOverview ( VisualizationTask task ) { return task . isVisible ( ) && ! task . has ( single ? RenderFlag . NO_EMBED : RenderFlag . NO_THUMBNAIL ) ; }
Test whether a task should be displayed in the overview plot .
33,950
private void recalcViewbox ( ) { final Element root = plot . getRoot ( ) ; SVGUtil . setAtt ( root , SVGConstants . SVG_WIDTH_ATTRIBUTE , "20cm" ) ; SVGUtil . setAtt ( root , SVGConstants . SVG_HEIGHT_ATTRIBUTE , SVGUtil . fmt ( 20 * plotmap . getHeight ( ) / plotmap . getWidth ( ) ) + "cm" ) ; String vb = "0 0 " + SVGUtil . fmt ( plotmap . getWidth ( ) ) + " " + SVGUtil . fmt ( plotmap . getHeight ( ) ) ; SVGUtil . setAtt ( root , SVGConstants . SVG_VIEW_BOX_ATTRIBUTE , vb ) ; }
Recompute the view box of the plot .
33,951
protected void triggerSubplotSelectEvent ( PlotItem it ) { for ( ActionListener actionListener : actionListeners ) { actionListener . actionPerformed ( new DetailViewSelectedEvent ( this , ActionEvent . ACTION_PERFORMED , null , 0 , it ) ) ; } }
When a subplot was selected forward the event to listeners .
33,952
public static double cdf ( double val , double mu , double sigma , double xi ) { val = ( val - mu ) / sigma ; if ( val < 0 ) { return 0. ; } if ( xi < 0 && val > - 1. / xi ) { return 1. ; } return 1 - FastMath . pow ( 1 + xi * val , - 1. / xi ) ; }
CDF of GPD distribution
33,953
public static double quantile ( double val , double mu , double sigma , double xi ) { if ( val < 0.0 || val > 1.0 ) { return Double . NaN ; } if ( xi == 0. ) { return mu - sigma * FastMath . log ( 1 - val ) ; } return mu - sigma / xi * ( 1 - FastMath . pow ( 1 - val , - xi ) ) ; }
Quantile function of GPD distribution
33,954
public Result run ( Database database , Relation < O > relation , Relation < NumberVector > radrel ) { if ( queries != null ) { throw new AbortException ( "This 'run' method will not use the given query set!" ) ; } DistanceQuery < O > distQuery = database . getDistanceQuery ( relation , getDistanceFunction ( ) ) ; RangeQuery < O > rangeQuery = database . getRangeQuery ( distQuery ) ; final DBIDs sample = DBIDUtil . randomSample ( relation . getDBIDs ( ) , sampling , random ) ; FiniteProgress prog = LOG . isVeryVerbose ( ) ? new FiniteProgress ( "kNN queries" , sample . size ( ) , LOG ) : null ; int hash = 0 ; MeanVariance mv = new MeanVariance ( ) ; for ( DBIDIter iditer = sample . iter ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { double r = radrel . get ( iditer ) . doubleValue ( 0 ) ; DoubleDBIDList rres = rangeQuery . getRangeForDBID ( iditer , r ) ; int ichecksum = 0 ; for ( DBIDIter it = rres . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { ichecksum += DBIDUtil . asInteger ( it ) ; } hash = Util . mixHashCodes ( hash , ichecksum ) ; mv . put ( rres . size ( ) ) ; LOG . incrementProcessed ( prog ) ; } LOG . ensureCompleted ( prog ) ; if ( LOG . isStatistics ( ) ) { LOG . statistics ( "Result hashcode: " + hash ) ; LOG . statistics ( "Mean number of results: " + mv . getMean ( ) + " +- " + mv . getNaiveStddev ( ) ) ; } return null ; }
Run the algorithm with separate radius relation
33,955
public static long [ ] random ( int card , int capacity , Random random ) { if ( card < 0 || card > capacity ) { throw new IllegalArgumentException ( "Cannot set " + card + " out of " + capacity + " bits." ) ; } if ( card < capacity >>> 1 ) { long [ ] bitset = BitsUtil . zero ( capacity ) ; for ( int todo = card ; todo > 0 ; todo = ( todo == 1 ) ? ( card - cardinality ( bitset ) ) : ( todo - 1 ) ) { setI ( bitset , random . nextInt ( capacity ) ) ; } return bitset ; } else { long [ ] bitset = BitsUtil . ones ( capacity ) ; for ( int todo = capacity - card ; todo > 0 ; todo = ( todo == 1 ) ? ( cardinality ( bitset ) - card ) : ( todo - 1 ) ) { clearI ( bitset , random . nextInt ( capacity ) ) ; } return bitset ; } }
Creates a new BitSet of fixed cardinality with randomly set bits .
33,956
public static long [ ] copy ( long [ ] v , int mincap ) { int words = ( ( mincap - 1 ) >>> LONG_LOG2_SIZE ) + 1 ; if ( v . length == words ) { return Arrays . copyOf ( v , v . length ) ; } long [ ] ret = new long [ words ] ; System . arraycopy ( v , 0 , ret , 0 , Math . min ( v . length , words ) ) ; return ret ; }
Copy a bitset .
33,957
public static boolean isZero ( long [ ] v ) { for ( int i = 0 ; i < v . length ; i ++ ) { if ( v [ i ] != 0 ) { return false ; } } return true ; }
Test for the bitstring to be all - zero .
33,958
public static long [ ] setI ( long [ ] v , long [ ] o ) { assert ( o . length <= v . length ) : "Bit set sizes do not agree." ; final int max = Math . min ( v . length , o . length ) ; for ( int i = 0 ; i < max ; i ++ ) { v [ i ] = o [ i ] ; } return v ; }
Put o onto v in - place i . e . v = o
33,959
public static void onesI ( long [ ] v , int bits ) { final int fillWords = bits >>> LONG_LOG2_SIZE ; final int fillBits = bits & LONG_LOG2_MASK ; Arrays . fill ( v , 0 , fillWords , LONG_ALL_BITS ) ; if ( fillBits > 0 ) { v [ fillWords ] = ( 1L << fillBits ) - 1 ; } if ( fillWords + 1 < v . length ) { Arrays . fill ( v , fillWords + 1 , v . length , 0L ) ; } }
Fill a vector initialized with bits ones .
33,960
public static long [ ] xorI ( long [ ] v , long [ ] o ) { assert ( o . length <= v . length ) : "Bit set sizes do not agree." ; for ( int i = 0 ; i < o . length ; i ++ ) { v [ i ] ^= o [ i ] ; } return v ; }
XOR o onto v in - place i . e . v ^ = o
33,961
public static long [ ] orI ( long [ ] v , long [ ] o ) { assert ( o . length <= v . length ) : "Bit set sizes do not agree." ; final int max = Math . min ( v . length , o . length ) ; for ( int i = 0 ; i < max ; i ++ ) { v [ i ] |= o [ i ] ; } return v ; }
OR o onto v in - place i . e . v | = o
33,962
public static long [ ] andI ( long [ ] v , long [ ] o ) { int i = 0 ; for ( ; i < o . length ; i ++ ) { v [ i ] &= o [ i ] ; } Arrays . fill ( v , i , v . length , 0 ) ; return v ; }
AND o onto v in - place i . e . v &amp ; = o
33,963
public static long [ ] nandI ( long [ ] v , long [ ] o ) { int i = 0 ; for ( ; i < o . length ; i ++ ) { v [ i ] &= ~ o [ i ] ; } return v ; }
NOTAND o onto v in - place i . e . v &amp ; = ~o
33,964
public static long [ ] invertI ( long [ ] v ) { for ( int i = 0 ; i < v . length ; i ++ ) { v [ i ] = ~ v [ i ] ; } return v ; }
Invert v in - place .
33,965
public static long cycleLeftC ( long v , int shift , int len ) { return shift == 0 ? v : shift < 0 ? cycleRightC ( v , - shift , len ) : ( ( ( v ) << ( shift ) ) | ( ( v ) >>> ( ( len ) - ( shift ) ) ) ) & ( ( 1 << len ) - 1 ) ; }
Rotate a long to the left cyclic with length len
33,966
public static long [ ] cycleLeftI ( long [ ] v , int shift , int len ) { long [ ] t = copy ( v , len , shift ) ; return orI ( shiftRightI ( v , len - shift ) , truncateI ( t , len ) ) ; }
Cycle a bitstring to the right .
33,967
public static int numberOfTrailingZerosSigned ( long [ ] v ) { for ( int p = 0 ; ; p ++ ) { if ( p == v . length ) { return - 1 ; } if ( v [ p ] != 0 ) { return Long . numberOfTrailingZeros ( v [ p ] ) + p * Long . SIZE ; } } }
Find the number of trailing zeros .
33,968
public static int numberOfLeadingZerosSigned ( long [ ] v ) { for ( int p = 0 , ip = v . length - 1 ; p < v . length ; p ++ , ip -- ) { if ( v [ ip ] != 0 ) { return Long . numberOfLeadingZeros ( v [ ip ] ) + p * Long . SIZE ; } } return - 1 ; }
Find the number of leading zeros .
33,969
public static int previousClearBit ( long v , int start ) { if ( start < 0 ) { return - 1 ; } start = start < Long . SIZE ? start : Long . SIZE - 1 ; long cur = ~ v & ( LONG_ALL_BITS >>> - ( start + 1 ) ) ; return cur == 0 ? - 1 : 63 - Long . numberOfLeadingZeros ( cur ) ; }
Find the previous clear bit .
33,970
public static int nextSetBit ( long v , int start ) { if ( start >= Long . SIZE ) { return - 1 ; } start = start < 0 ? 0 : start ; long cur = v & ( LONG_ALL_BITS << start ) ; return cur == 0 ? - 1 : cur == LONG_ALL_BITS ? 0 : Long . numberOfTrailingZeros ( cur ) ; }
Find the next set bit .
33,971
public static boolean intersect ( long [ ] x , long [ ] y ) { final int min = ( x . length < y . length ) ? x . length : y . length ; for ( int i = 0 ; i < min ; i ++ ) { if ( ( x [ i ] & y [ i ] ) != 0L ) { return true ; } } return false ; }
Test whether two Bitsets intersect .
33,972
public static int intersectionSize ( long [ ] x , long [ ] y ) { final int lx = x . length , ly = y . length ; final int min = ( lx < ly ) ? lx : ly ; int res = 0 ; for ( int i = 0 ; i < min ; i ++ ) { res += Long . bitCount ( x [ i ] & y [ i ] ) ; } return res ; }
Compute the intersection size of two Bitsets .
33,973
public static int unionSize ( long [ ] x , long [ ] y ) { final int lx = x . length , ly = y . length ; final int min = ( lx < ly ) ? lx : ly ; int i = 0 , res = 0 ; for ( ; i < min ; i ++ ) { res += Long . bitCount ( x [ i ] | y [ i ] ) ; } for ( ; i < lx ; i ++ ) { res += Long . bitCount ( x [ i ] ) ; } for ( ; i < ly ; i ++ ) { res += Long . bitCount ( y [ i ] ) ; } return res ; }
Compute the union size of two Bitsets .
33,974
public static boolean equal ( long [ ] x , long [ ] y ) { if ( x == null || y == null ) { return ( x == null ) && ( y == null ) ; } int p = Math . min ( x . length , y . length ) - 1 ; for ( int i = x . length - 1 ; i > p ; i -- ) { if ( x [ i ] != 0L ) { return false ; } } for ( int i = y . length - 1 ; i > p ; i -- ) { if ( y [ i ] != 0L ) { return false ; } } for ( ; p >= 0 ; p -- ) { if ( x [ p ] != y [ p ] ) { return false ; } } return true ; }
Test two bitsets for equality
33,975
public static int compare ( long [ ] x , long [ ] y ) { if ( x == null ) { return ( y == null ) ? 0 : - 1 ; } if ( y == null ) { return + 1 ; } int p = Math . min ( x . length , y . length ) - 1 ; for ( int i = x . length - 1 ; i > p ; i -- ) { if ( x [ i ] != 0 ) { return + 1 ; } } for ( int i = y . length - 1 ; i > p ; i -- ) { if ( y [ i ] != 0 ) { return - 1 ; } } for ( ; p >= 0 ; p -- ) { final long xp = x [ p ] , yp = y [ p ] ; if ( xp != yp ) { return xp < 0 ? ( yp < 0 && yp < xp ) ? - 1 : + 1 : ( yp < 0 || xp < yp ) ? - 1 : + 1 ; } } return 0 ; }
Compare two bitsets .
33,976
public int compareTo ( DistanceEntry < E > o ) { int comp = Double . compare ( distance , o . distance ) ; return comp ; }
Compares this object with the specified object for order .
33,977
private double [ ] knnDistances ( O object ) { KNNList knns = knnq . getKNNForObject ( object , getKmax ( ) - 1 ) ; double [ ] distances = new double [ getKmax ( ) ] ; int i = 0 ; for ( DoubleDBIDListIter iter = knns . iter ( ) ; iter . valid ( ) && i < getKmax ( ) ; iter . advance ( ) , i ++ ) { distances [ i ] = iter . doubleValue ( ) ; } return distances ; }
Returns the knn distance of the object with the specified id .
33,978
protected double downsample ( double [ ] data , int start , int end , int size ) { double sum = 0 ; for ( int i = start ; i < end ; i ++ ) { sum += data [ i ] ; } return sum ; }
Perform downsampling on a number of bins .
33,979
public void setRotationZ ( double rotationZ ) { this . rotationZ = rotationZ ; this . cosZ = FastMath . cos ( rotationZ ) ; this . sinZ = FastMath . sin ( rotationZ ) ; fireCameraChangedEvent ( ) ; }
Set the z rotation angle in radians .
33,980
public void apply ( GL2 gl ) { gl . glMatrixMode ( GL2 . GL_PROJECTION ) ; gl . glLoadIdentity ( ) ; glu . gluPerspective ( 35 , ratio , 1 , 1000 ) ; glu . gluLookAt ( distance * sinZ , distance * - cosZ , height , 0 , 0 , .5 , 0 , 0 , 1 ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glLoadIdentity ( ) ; gl . glGetIntegerv ( GL . GL_VIEWPORT , viewp , 0 ) ; gl . glGetDoublev ( GLMatrixFunc . GL_MODELVIEW_MATRIX , modelview , 0 ) ; gl . glGetDoublev ( GLMatrixFunc . GL_PROJECTION_MATRIX , projection , 0 ) ; }
Apply the camera to a GL context .
33,981
public void project ( double x , double y , double z , double [ ] out ) { glu . gluProject ( x , y , z , modelview , 0 , projection , 0 , viewp , 0 , out , 0 ) ; }
Project a coordinate
33,982
public void addCameraListener ( CameraListener lis ) { if ( listeners == null ) { listeners = new ArrayList < > ( 5 ) ; } listeners . add ( lis ) ; }
Add a camera listener .
33,983
public static AffineTransformation axisProjection ( int dim , int ax1 , int ax2 ) { AffineTransformation proj = AffineTransformation . reorderAxesTransformation ( dim , ax1 , ax2 ) ; double [ ] trans = new double [ dim ] ; for ( int i = 0 ; i < dim ; i ++ ) { trans [ i ] = - .5 ; } proj . addTranslation ( trans ) ; proj . addAxisReflection ( 2 ) ; proj . addScaling ( SCALE ) ; return proj ; }
Compute an transformation matrix to show only axis ax1 and ax2 .
33,984
protected ApproximationLine conservativeKnnDistanceApproximation ( int k_max ) { int k_0 = k_max ; double y_1 = Double . NEGATIVE_INFINITY ; double y_kmax = Double . NEGATIVE_INFINITY ; for ( int i = 0 ; i < getNumEntries ( ) ; i ++ ) { MkCoPEntry entry = getEntry ( i ) ; ApproximationLine approx = entry . getConservativeKnnDistanceApproximation ( ) ; k_0 = Math . min ( approx . getK_0 ( ) , k_0 ) ; } for ( int i = 0 ; i < getNumEntries ( ) ; i ++ ) { MkCoPEntry entry = getEntry ( i ) ; ApproximationLine approx = entry . getConservativeKnnDistanceApproximation ( ) ; double entry_y_1 = approx . getValueAt ( k_0 ) ; double entry_y_kmax = approx . getValueAt ( k_max ) ; if ( ! Double . isInfinite ( entry_y_1 ) ) { y_1 = Math . max ( entry_y_1 , y_1 ) ; } if ( ! Double . isInfinite ( entry_y_kmax ) ) { y_kmax = Math . max ( entry_y_kmax , y_kmax ) ; } } double m = ( y_kmax - y_1 ) / ( FastMath . log ( k_max ) - FastMath . log ( k_0 ) ) ; double t = y_1 - m * FastMath . log ( k_0 ) ; return new ApproximationLine ( k_0 , m , t ) ; }
Determines and returns the conservative approximation for the knn distances of this node as the maximum of the conservative approximations of all entries .
33,985
protected ApproximationLine progressiveKnnDistanceApproximation ( int k_max ) { if ( ! isLeaf ( ) ) { throw new UnsupportedOperationException ( "Progressive KNN-distance approximation " + "is only vailable in leaf nodes!" ) ; } int k_0 = 0 ; double y_1 = Double . POSITIVE_INFINITY ; double y_kmax = Double . POSITIVE_INFINITY ; for ( int i = 0 ; i < getNumEntries ( ) ; i ++ ) { MkCoPLeafEntry entry = ( MkCoPLeafEntry ) getEntry ( i ) ; ApproximationLine approx = entry . getProgressiveKnnDistanceApproximation ( ) ; k_0 = Math . max ( approx . getK_0 ( ) , k_0 ) ; } for ( int i = 0 ; i < getNumEntries ( ) ; i ++ ) { MkCoPLeafEntry entry = ( MkCoPLeafEntry ) getEntry ( i ) ; ApproximationLine approx = entry . getProgressiveKnnDistanceApproximation ( ) ; y_1 = Math . min ( approx . getValueAt ( k_0 ) , y_1 ) ; y_kmax = Math . min ( approx . getValueAt ( k_max ) , y_kmax ) ; } double m = ( y_kmax - y_1 ) / ( FastMath . log ( k_max ) - FastMath . log ( k_0 ) ) ; double t = y_1 - m * FastMath . log ( k_0 ) ; return new ApproximationLine ( k_0 , m , t ) ; }
Determines and returns the progressive approximation for the knn distances of this node as the maximum of the progressive approximations of all entries .
33,986
public CSSClass addClass ( CSSClass clss ) throws CSSNamingConflict { CSSClass existing = store . get ( clss . getName ( ) ) ; if ( existing != null && existing . getOwner ( ) != null && existing . getOwner ( ) != clss . getOwner ( ) ) { throw new CSSNamingConflict ( "CSS class naming conflict between " + clss . getOwner ( ) . toString ( ) + " and " + existing . getOwner ( ) . toString ( ) ) ; } return store . put ( clss . getName ( ) , clss ) ; }
Add a single class to the map .
33,987
public synchronized void removeClass ( CSSClass clss ) { CSSClass existing = store . get ( clss . getName ( ) ) ; if ( existing == clss ) { store . remove ( existing . getName ( ) ) ; } }
Remove a single CSS class from the map . Note that classes are removed by reference not by name!
33,988
public CSSClass getClass ( String name , Object owner ) throws CSSNamingConflict { CSSClass existing = store . get ( name ) ; if ( existing == null ) { return null ; } if ( owner != null && existing . getOwner ( ) != owner ) { throw new CSSNamingConflict ( "CSS class naming conflict between " + owner . toString ( ) + " and " + existing . getOwner ( ) . toString ( ) ) ; } return existing ; }
Retrieve a single class by name and owner
33,989
public void serialize ( StringBuilder buf ) { for ( CSSClass clss : store . values ( ) ) { clss . appendCSSDefinition ( buf ) ; } }
Serialize managed CSS classes to rule file .
33,990
public boolean mergeCSSFrom ( CSSClassManager other ) throws CSSNamingConflict { for ( CSSClass clss : other . getClasses ( ) ) { this . addClass ( clss ) ; } return true ; }
Merge CSS classes for example to merge two plots .
33,991
public void updateStyleElement ( Document document , Element style ) { StringBuilder buf = new StringBuilder ( ) ; serialize ( buf ) ; Text cont = document . createTextNode ( buf . toString ( ) ) ; while ( style . hasChildNodes ( ) ) { style . removeChild ( style . getFirstChild ( ) ) ; } style . appendChild ( cont ) ; }
Update the text contents of an existing style element .
33,992
private static double calculate_MDEF_norm ( Node sn , Node cg ) { long sq = sn . getSquareSum ( cg . getLevel ( ) - sn . getLevel ( ) ) ; if ( sq == sn . getCount ( ) ) { return 0.0 ; } long cb = sn . getCubicSum ( cg . getLevel ( ) - sn . getLevel ( ) ) ; double n_hat = ( double ) sq / sn . getCount ( ) ; double sig_n_hat = FastMath . sqrt ( cb * sn . getCount ( ) - ( sq * sq ) ) / sn . getCount ( ) ; if ( sig_n_hat < Double . MIN_NORMAL ) { return 0.0 ; } double mdef = n_hat - cg . getCount ( ) ; return mdef / sig_n_hat ; }
Method for the MDEF calculation
33,993
public void writeBundleStream ( BundleStreamSource source , WritableByteChannel output ) throws IOException { ByteBuffer buffer = ByteBuffer . allocateDirect ( INITIAL_BUFFER ) ; DBIDVar var = DBIDUtil . newVar ( ) ; ByteBufferSerializer < ? > [ ] serializers = null ; loop : while ( true ) { BundleStreamSource . Event ev = source . nextEvent ( ) ; switch ( ev ) { case NEXT_OBJECT : if ( serializers == null ) { serializers = writeHeader ( source , buffer , output ) ; } if ( serializers [ 0 ] != null ) { if ( ! source . assignDBID ( var ) ) { throw new AbortException ( "An object did not have an DBID assigned." ) ; } DBID id = DBIDUtil . deref ( var ) ; @ SuppressWarnings ( "unchecked" ) ByteBufferSerializer < DBID > ser = ( ByteBufferSerializer < DBID > ) serializers [ 0 ] ; int size = ser . getByteSize ( id ) ; buffer = ensureBuffer ( size , buffer , output ) ; ser . toByteBuffer ( buffer , id ) ; } for ( int i = 1 , j = 0 ; i < serializers . length ; ++ i , ++ j ) { @ SuppressWarnings ( "unchecked" ) ByteBufferSerializer < Object > ser = ( ByteBufferSerializer < Object > ) serializers [ i ] ; int size = ser . getByteSize ( source . data ( j ) ) ; buffer = ensureBuffer ( size , buffer , output ) ; ser . toByteBuffer ( buffer , source . data ( j ) ) ; } break ; case META_CHANGED : if ( serializers != null ) { throw new AbortException ( "Meta changes are not supported, once the block header has been written." ) ; } break ; case END_OF_STREAM : break loop ; default : LOG . warning ( "Unknown bundle stream event. API inconsistent? " + ev ) ; break ; } } if ( buffer . position ( ) > 0 ) { flushBuffer ( buffer , output ) ; } }
Write a bundle stream to a file output channel .
33,994
private void flushBuffer ( ByteBuffer buffer , WritableByteChannel output ) throws IOException { buffer . flip ( ) ; output . write ( buffer ) ; buffer . flip ( ) ; buffer . limit ( buffer . capacity ( ) ) ; }
Flush the current write buffer to disk .
33,995
private ByteBuffer ensureBuffer ( int size , ByteBuffer buffer , WritableByteChannel output ) throws IOException { if ( buffer . remaining ( ) >= size ) { return buffer ; } flushBuffer ( buffer , output ) ; if ( buffer . remaining ( ) >= size ) { return buffer ; } return ByteBuffer . allocateDirect ( Math . max ( buffer . capacity ( ) << 1 , buffer . capacity ( ) + size ) ) ; }
Ensure the buffer is large enough .
33,996
private ByteBufferSerializer < ? > [ ] writeHeader ( BundleStreamSource source , ByteBuffer buffer , WritableByteChannel output ) throws IOException { final BundleMeta meta = source . getMeta ( ) ; final int nummeta = meta . size ( ) ; @ SuppressWarnings ( "rawtypes" ) final ByteBufferSerializer [ ] serializers = new ByteBufferSerializer [ 1 + nummeta ] ; assert ( buffer . position ( ) == 0 ) : "Buffer is supposed to be at 0." ; buffer . putInt ( MAGIC ) ; if ( source . hasDBIDs ( ) ) { buffer . putInt ( 1 + nummeta ) ; ByteBufferSerializer < DBID > ser = DBIDFactory . FACTORY . getDBIDSerializer ( ) ; TypeInformationSerializer . STATIC . toByteBuffer ( buffer , new SimpleTypeInformation < > ( DBID . class , ser ) ) ; serializers [ 0 ] = ser ; } else { buffer . putInt ( nummeta ) ; } for ( int i = 0 ; i < nummeta ; i ++ ) { SimpleTypeInformation < ? > type = meta . get ( i ) ; ByteBufferSerializer < ? > ser = type . getSerializer ( ) ; if ( ser == null ) { throw new AbortException ( "Cannot serialize - no serializer found for type: " + type . toString ( ) ) ; } TypeInformationSerializer . STATIC . toByteBuffer ( buffer , type ) ; serializers [ i + 1 ] = ser ; } return serializers ; }
Write the header for the given stream to the stream .
33,997
protected void runDBSCAN ( Relation < O > relation , RangeQuery < O > rangeQuery ) { final int size = relation . size ( ) ; FiniteProgress objprog = LOG . isVerbose ( ) ? new FiniteProgress ( "Processing objects" , size , LOG ) : null ; IndefiniteProgress clusprog = LOG . isVerbose ( ) ? new IndefiniteProgress ( "Number of clusters" , LOG ) : null ; processedIDs = DBIDUtil . newHashSet ( size ) ; ArrayModifiableDBIDs seeds = DBIDUtil . newArray ( ) ; for ( DBIDIter iditer = relation . iterDBIDs ( ) ; iditer . valid ( ) ; iditer . advance ( ) ) { if ( ! processedIDs . contains ( iditer ) ) { expandCluster ( relation , rangeQuery , iditer , seeds , objprog , clusprog ) ; } if ( objprog != null && clusprog != null ) { objprog . setProcessed ( processedIDs . size ( ) , LOG ) ; clusprog . setProcessed ( resultList . size ( ) , LOG ) ; } if ( processedIDs . size ( ) == size ) { break ; } } LOG . ensureCompleted ( objprog ) ; LOG . setCompleted ( clusprog ) ; }
Run the DBSCAN algorithm
33,998
protected void expandCluster ( Relation < O > relation , RangeQuery < O > rangeQuery , DBIDRef startObjectID , ArrayModifiableDBIDs seeds , FiniteProgress objprog , IndefiniteProgress clusprog ) { DoubleDBIDList neighbors = rangeQuery . getRangeForDBID ( startObjectID , epsilon ) ; ncounter += neighbors . size ( ) ; if ( neighbors . size ( ) < minpts ) { noise . add ( startObjectID ) ; processedIDs . add ( startObjectID ) ; if ( objprog != null ) { objprog . incrementProcessed ( LOG ) ; } return ; } ModifiableDBIDs currentCluster = DBIDUtil . newArray ( ) ; currentCluster . add ( startObjectID ) ; processedIDs . add ( startObjectID ) ; assert ( seeds . size ( ) == 0 ) ; seeds . clear ( ) ; processNeighbors ( neighbors . iter ( ) , currentCluster , seeds ) ; DBIDVar o = DBIDUtil . newVar ( ) ; while ( ! seeds . isEmpty ( ) ) { neighbors = rangeQuery . getRangeForDBID ( seeds . pop ( o ) , epsilon ) ; ncounter += neighbors . size ( ) ; if ( neighbors . size ( ) >= minpts ) { processNeighbors ( neighbors . iter ( ) , currentCluster , seeds ) ; } if ( objprog != null ) { objprog . incrementProcessed ( LOG ) ; } } resultList . add ( currentCluster ) ; if ( clusprog != null ) { clusprog . setProcessed ( resultList . size ( ) , LOG ) ; } }
DBSCAN - function expandCluster .
33,999
private void processNeighbors ( DoubleDBIDListIter neighbor , ModifiableDBIDs currentCluster , ArrayModifiableDBIDs seeds ) { final boolean ismetric = getDistanceFunction ( ) . isMetric ( ) ; for ( ; neighbor . valid ( ) ; neighbor . advance ( ) ) { if ( processedIDs . add ( neighbor ) ) { if ( ! ismetric || neighbor . doubleValue ( ) > 0. ) { seeds . add ( neighbor ) ; } } else if ( ! noise . remove ( neighbor ) ) { continue ; } currentCluster . add ( neighbor ) ; } }
Process a single core point .