idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
33,800
public void saveAsPDF ( File file ) throws IOException , TranscoderException , ClassNotFoundException { try { Object t = Class . forName ( "org.apache.fop.svg.PDFTranscoder" ) . newInstance ( ) ; transcode ( file , ( Transcoder ) t ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new ClassNotFoundException ( "Could not instantiate PDF transcoder - is Apache FOP installed?" , e ) ; } }
Transcode file to PDF .
33,801
public void saveAsPNG ( File file , int width , int height ) throws IOException , TranscoderException { PNGTranscoder t = new PNGTranscoder ( ) ; t . addTranscodingHint ( PNGTranscoder . KEY_WIDTH , new Float ( width ) ) ; t . addTranscodingHint ( PNGTranscoder . KEY_HEIGHT , new Float ( height ) ) ; transcode ( file , t ) ; }
Transcode file to PNG .
33,802
public void saveAsANY ( File file , int width , int height , float quality ) throws IOException , TranscoderException , TransformerFactoryConfigurationError , TransformerException , ClassNotFoundException { String extension = FileUtil . getFilenameExtension ( file ) ; if ( "svg" . equals ( extension ) ) { saveAsSVG ( file ) ; } else if ( "pdf" . equals ( extension ) ) { saveAsPDF ( file ) ; } else if ( "ps" . equals ( extension ) ) { saveAsPS ( file ) ; } else if ( "eps" . equals ( extension ) ) { saveAsEPS ( file ) ; } else if ( "png" . equals ( extension ) ) { saveAsPNG ( file , width , height ) ; } else if ( "jpg" . equals ( extension ) || "jpeg" . equals ( extension ) ) { saveAsJPEG ( file , width , height , quality ) ; } else { throw new IOException ( "Unknown file extension: " + extension ) ; } }
Save a file trying to auto - guess the file type .
33,803
public BufferedImage makeAWTImage ( int width , int height ) throws TranscoderException { ThumbnailTranscoder t = new ThumbnailTranscoder ( ) ; t . addTranscodingHint ( PNGTranscoder . KEY_WIDTH , new Float ( width ) ) ; t . addTranscodingHint ( PNGTranscoder . KEY_HEIGHT , new Float ( height ) ) ; TranscoderInput input = new TranscoderInput ( document ) ; t . transcode ( input , null ) ; return t . getLastImage ( ) ; }
Convert the SVG to a thumbnail image .
33,804
public void dumpDebugFile ( ) { try { File f = File . createTempFile ( "elki-debug" , ".svg" ) ; f . deleteOnExit ( ) ; this . saveAsSVG ( f ) ; LoggingUtil . warning ( "Saved debug file to: " + f . getAbsolutePath ( ) ) ; } catch ( Throwable err ) { } }
Dump the SVG plot to a debug file .
33,805
public void putIdElement ( String id , Element obj ) { objWithId . put ( id , new WeakReference < > ( obj ) ) ; }
Add an object id .
33,806
public Element getIdElement ( String id ) { WeakReference < Element > ref = objWithId . get ( id ) ; return ( ref != null ) ? ref . get ( ) : null ; }
Get an element by its id .
33,807
protected ScoreResult computeScore ( DBIDs ids , DBIDs outlierIds , OutlierResult or ) throws IllegalStateException { if ( scaling instanceof OutlierScaling ) { OutlierScaling oscaling = ( OutlierScaling ) scaling ; oscaling . prepare ( or ) ; } final ScalingFunction innerScaling ; double min = scaling . getMin ( ) ; double max = scaling . getMax ( ) ; if ( Double . isInfinite ( min ) || Double . isNaN ( min ) || Double . isInfinite ( max ) || Double . isNaN ( max ) ) { innerScaling = new IdentityScaling ( ) ; LOG . warning ( "JudgeOutlierScores expects values between 0.0 and 1.0, but we don't have such a guarantee by the scaling function: min:" + min + " max:" + max ) ; } else { if ( min == 0.0 && max == 1.0 ) { innerScaling = new IdentityScaling ( ) ; } else { innerScaling = new LinearScaling ( 1.0 / ( max - min ) , - min ) ; } } double posscore = 0.0 ; double negscore = 0.0 ; for ( DBIDIter iter = ids . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { double result = or . getScores ( ) . doubleValue ( iter ) ; result = innerScaling . getScaled ( scaling . getScaled ( result ) ) ; posscore += ( 1.0 - result ) ; } for ( DBIDIter iter = outlierIds . iter ( ) ; iter . valid ( ) ; iter . advance ( ) ) { double result = or . getScores ( ) . doubleValue ( iter ) ; result = innerScaling . getScaled ( scaling . getScaled ( result ) ) ; negscore += result ; } posscore /= ids . size ( ) ; negscore /= outlierIds . size ( ) ; LOG . verbose ( "Scores: " + posscore + " " + negscore ) ; ArrayList < double [ ] > s = new ArrayList < > ( 1 ) ; s . add ( new double [ ] { ( posscore + negscore ) * .5 , posscore , negscore } ) ; return new ScoreResult ( s ) ; }
Evaluate a single outlier score result .
33,808
protected Cluster < SubspaceModel > runDOC ( Database database , Relation < V > relation , ArrayModifiableDBIDs S , int d , int n , int m , int r , int minClusterSize ) { long [ ] D = null ; DBIDVar dV = DBIDUtil . newVar ( ) ; FiniteProgress iprogress = LOG . isVerbose ( ) ? new FiniteProgress ( "Iteration progress for current cluster" , m * n , LOG ) : null ; Random random = rnd . getSingleThreadedRandom ( ) ; DBIDArrayIter iter = S . iter ( ) ; outer : for ( int i = 0 ; i < n ; ++ i ) { iter . seek ( random . nextInt ( S . size ( ) ) ) ; for ( int j = 0 ; j < m ; ++ j ) { DBIDs randomSet = DBIDUtil . randomSample ( S , r , random ) ; long [ ] nD = BitsUtil . zero ( d ) ; for ( int k = 0 ; k < d ; ++ k ) { if ( dimensionIsRelevant ( k , relation , randomSet ) ) { BitsUtil . setI ( nD , k ) ; } } if ( D == null || BitsUtil . cardinality ( nD ) > BitsUtil . cardinality ( D ) ) { D = nD ; dV . set ( iter ) ; if ( BitsUtil . cardinality ( D ) >= d_zero ) { if ( iprogress != null ) { iprogress . setProcessed ( iprogress . getTotal ( ) , LOG ) ; } break outer ; } } LOG . incrementProcessed ( iprogress ) ; } } LOG . ensureCompleted ( iprogress ) ; if ( D == null || BitsUtil . cardinality ( D ) == 0 ) { return null ; } DBIDs C = findNeighbors ( dV , D , S , relation ) ; return ( C . size ( ) >= minClusterSize ) ? makeCluster ( relation , C , D ) : null ; }
Performs a single run of FastDOC finding a single cluster .
33,809
public static SVGPath drawDelaunay ( Projection2D proj , List < SweepHullDelaunay2D . Triangle > delaunay , List < double [ ] > means ) { final SVGPath path = new SVGPath ( ) ; for ( SweepHullDelaunay2D . Triangle del : delaunay ) { path . moveTo ( proj . fastProjectDataToRenderSpace ( means . get ( del . a ) ) ) ; path . drawTo ( proj . fastProjectDataToRenderSpace ( means . get ( del . b ) ) ) ; path . drawTo ( proj . fastProjectDataToRenderSpace ( means . get ( del . c ) ) ) ; path . close ( ) ; } return path ; }
Draw the Delaunay triangulation .
33,810
public static SVGPath drawFakeVoronoi ( Projection2D proj , List < double [ ] > means ) { CanvasSize viewport = proj . estimateViewport ( ) ; final SVGPath path = new SVGPath ( ) ; final double [ ] dirv = VMath . minus ( means . get ( 1 ) , means . get ( 0 ) ) ; VMath . rotate90Equals ( dirv ) ; double [ ] dir = proj . fastProjectRelativeDataToRenderSpace ( dirv ) ; final double [ ] mean = VMath . plus ( means . get ( 0 ) , means . get ( 1 ) ) ; VMath . timesEquals ( mean , 0.5 ) ; double [ ] projmean = proj . fastProjectDataToRenderSpace ( mean ) ; double factor = viewport . continueToMargin ( projmean , dir ) ; path . moveTo ( projmean [ 0 ] + factor * dir [ 0 ] , projmean [ 1 ] + factor * dir [ 1 ] ) ; dir [ 0 ] *= - 1 ; dir [ 1 ] *= - 1 ; factor = viewport . continueToMargin ( projmean , dir ) ; path . drawTo ( projmean [ 0 ] + factor * dir [ 0 ] , projmean [ 1 ] + factor * dir [ 1 ] ) ; return path ; }
Fake Voronoi diagram . For two means only
33,811
public void select ( Segment segment , boolean addToSelection ) { if ( segment . isNone ( ) ) { return ; } if ( ! addToSelection ) { deselectAllSegments ( ) ; } if ( segment . isUnpaired ( ) ) { if ( addToSelection ) { boolean allSegmentsSelected = true ; for ( Segment other : segments . getPairedSegments ( segment ) ) { if ( ! isSelected ( other ) ) { allSegmentsSelected = false ; break ; } } if ( allSegmentsSelected ) { deselectSegment ( segment ) ; return ; } } if ( isSelected ( segment ) ) { deselectSegment ( segment ) ; } else { selectSegment ( segment ) ; } } else { if ( isSelected ( segment ) ) { deselectSegment ( segment ) ; } else { selectSegment ( segment ) ; } } }
Adds or removes the given segment to the selection . Depending on the clustering and cluster selected and the addToSelection option given the current selection will be modified . This method is called by clicking on a segment and ring and the CTRL - button status .
33,812
protected void deselectSegment ( Segment segment ) { if ( segment . isUnpaired ( ) ) { ArrayList < Segment > remove = new ArrayList < > ( ) ; for ( Entry < Segment , Segment > entry : indirectSelections . entrySet ( ) ) { if ( entry . getValue ( ) == segment ) { remove . add ( entry . getKey ( ) ) ; } } for ( Segment other : remove ) { indirectSelections . remove ( other ) ; deselectSegment ( other ) ; } } else { Segment unpaired = indirectSelections . get ( segment ) ; if ( unpaired != null ) { deselectSegment ( unpaired ) ; } if ( selectedSegments . remove ( segment ) && segment . getDBIDs ( ) != null ) { unselectedObjects . addDBIDs ( segment . getDBIDs ( ) ) ; } } }
Deselect a segment
33,813
protected void selectSegment ( Segment segment ) { if ( segment . isUnpaired ( ) ) { for ( Segment other : segments . getPairedSegments ( segment ) ) { indirectSelections . put ( other , segment ) ; selectSegment ( other ) ; } } else { if ( ! selectedSegments . contains ( segment ) ) { selectedSegments . add ( segment ) ; if ( segment . getDBIDs ( ) != null ) { unselectedObjects . removeDBIDs ( segment . getDBIDs ( ) ) ; } } } }
Select a segment
33,814
private boolean checkSupertypes ( Class < ? > cls ) { for ( Class < ? > c : knownParameterizables ) { if ( c . isAssignableFrom ( cls ) ) { return true ; } } return false ; }
Check all supertypes of a class .
33,815
private State checkV3Parameterization ( Class < ? > cls , State state ) throws NoClassDefFoundError { for ( Class < ? > inner : cls . getDeclaredClasses ( ) ) { if ( AbstractParameterizer . class . isAssignableFrom ( inner ) ) { try { Class < ? extends AbstractParameterizer > pcls = inner . asSubclass ( AbstractParameterizer . class ) ; pcls . newInstance ( ) ; if ( checkParameterizer ( cls , pcls ) ) { if ( state == State . INSTANTIABLE ) { LOG . warning ( "More than one parameterization method in class " + cls . getName ( ) ) ; } state = State . INSTANTIABLE ; } } catch ( Exception | Error e ) { LOG . verbose ( "Could not run Parameterizer: " + inner . getName ( ) + ": " + e . getMessage ( ) ) ; } } } return state ; }
Check for a V3 constructor .
33,816
private State checkDefaultConstructor ( Class < ? > cls , State state ) throws NoClassDefFoundError { try { cls . getConstructor ( ) ; return State . DEFAULT_INSTANTIABLE ; } catch ( Exception e ) { } return state ; }
Check for a default constructor .
33,817
public static double logpdf ( double x , double k , double theta , double shift ) { x = ( x - shift ) ; if ( x <= 0. ) { return Double . NEGATIVE_INFINITY ; } final double log1px = FastMath . log1p ( x ) ; return k * FastMath . log ( theta ) - GammaDistribution . logGamma ( k ) - ( theta + 1. ) * log1px + ( k - 1 ) * FastMath . log ( log1px ) ; }
LogGamma distribution logPDF
33,818
protected void plotGray ( SVGPlot plot , Element parent , double x , double y , double size ) { Element marker = plot . svgCircle ( x , y , size * .5 ) ; SVGUtil . setStyle ( marker , SVGConstants . CSS_FILL_PROPERTY + ":" + greycolor ) ; parent . appendChild ( marker ) ; }
Plot a replacement marker when an object is to be plotted as disabled usually gray .
33,819
protected void plotUncolored ( SVGPlot plot , Element parent , double x , double y , double size ) { Element marker = plot . svgCircle ( x , y , size * .5 ) ; SVGUtil . setStyle ( marker , SVGConstants . CSS_FILL_PROPERTY + ":" + dotcolor ) ; parent . appendChild ( marker ) ; }
Plot a replacement marker when no color is set ; usually black
33,820
public int truePositives ( ) { int tp = 0 ; for ( int i = 0 ; i < confusion . length ; i ++ ) { tp += truePositives ( i ) ; } return tp ; }
The number of correctly classified instances .
33,821
public int trueNegatives ( int classindex ) { int tn = 0 ; for ( int i = 0 ; i < confusion . length ; i ++ ) { for ( int j = 0 ; j < confusion [ i ] . length ; j ++ ) { if ( i != classindex && j != classindex ) { tn += confusion [ i ] [ j ] ; } } } return tn ; }
The number of true negatives of the specified class .
33,822
public int falsePositives ( int classindex ) { int fp = 0 ; for ( int i = 0 ; i < confusion [ classindex ] . length ; i ++ ) { if ( i != classindex ) { fp += confusion [ classindex ] [ i ] ; } } return fp ; }
The false positives for the specified class .
33,823
public int falseNegatives ( int classindex ) { int fn = 0 ; for ( int i = 0 ; i < confusion . length ; i ++ ) { if ( i != classindex ) { fn += confusion [ i ] [ classindex ] ; } } return fn ; }
The false negatives for the specified class .
33,824
public int totalInstances ( ) { int total = 0 ; for ( int i = 0 ; i < confusion . length ; i ++ ) { for ( int j = 0 ; j < confusion [ i ] . length ; j ++ ) { total += confusion [ i ] [ j ] ; } } return total ; }
The total number of instances covered by this confusion matrix .
33,825
protected static < A > double [ ] computeDistances ( NumberArrayAdapter < ? , A > adapter , A data ) { final int size = adapter . size ( data ) ; double [ ] dMatrix = new double [ ( size * ( size + 1 ) ) >> 1 ] ; for ( int i = 0 , c = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { double dx = adapter . getDouble ( data , i ) - adapter . getDouble ( data , j ) ; dMatrix [ c ++ ] = ( dx < 0 ) ? - dx : dx ; } c ++ ; } doubleCenterMatrix ( dMatrix , size ) ; return dMatrix ; }
Compute the double - centered delta matrix .
33,826
public static void doubleCenterMatrix ( double [ ] dMatrix , int size ) { double [ ] rowMean = new double [ size ] ; for ( int i = 0 , c = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { double v = dMatrix [ c ++ ] ; rowMean [ i ] += v ; rowMean [ j ] += v ; } assert ( dMatrix [ c ] == 0. ) ; c ++ ; } double matrixMean = 0. ; for ( int i = 0 ; i < size ; i ++ ) { matrixMean += rowMean [ i ] ; rowMean [ i ] /= size ; } matrixMean /= size * size ; for ( int o = 0 , c = 0 ; o < size ; o ++ ) { for ( int p = 0 ; p <= o ; p ++ ) { dMatrix [ c ++ ] -= rowMean [ o ] + rowMean [ p ] - matrixMean ; } } }
Computes the distance variance matrix of one axis .
33,827
public HyperBoundingBox determineAlphaMinMax ( HyperBoundingBox interval ) { final int dim = vec . getDimensionality ( ) ; if ( interval . getDimensionality ( ) != dim - 1 ) { throw new IllegalArgumentException ( "Interval needs to have dimensionality d=" + ( dim - 1 ) + ", read: " + interval . getDimensionality ( ) ) ; } if ( extremumType . equals ( ExtremumType . CONSTANT ) ) { double [ ] centroid = SpatialUtil . centroid ( interval ) ; return new HyperBoundingBox ( centroid , centroid ) ; } double [ ] alpha_min = new double [ dim - 1 ] ; double [ ] alpha_max = new double [ dim - 1 ] ; if ( SpatialUtil . contains ( interval , alphaExtremum ) ) { if ( extremumType . equals ( ExtremumType . MINIMUM ) ) { alpha_min = alphaExtremum ; for ( int d = dim - 2 ; d >= 0 ; d -- ) { alpha_max [ d ] = determineAlphaMax ( d , alpha_max , interval ) ; } } else { alpha_max = alphaExtremum ; for ( int d = dim - 2 ; d >= 0 ; d -- ) { alpha_min [ d ] = determineAlphaMin ( d , alpha_min , interval ) ; } } } else { for ( int d = dim - 2 ; d >= 0 ; d -- ) { alpha_min [ d ] = determineAlphaMin ( d , alpha_min , interval ) ; alpha_max [ d ] = determineAlphaMax ( d , alpha_max , interval ) ; } } return new HyperBoundingBox ( alpha_min , alpha_max ) ; }
Determines the alpha values where this function has a minumum and maximum value in the given interval .
33,828
private ExtremumType extremumType ( int n , double [ ] alpha_extreme , HyperBoundingBox interval ) { if ( n == alpha_extreme . length - 1 ) { return extremumType ; } double [ ] alpha_extreme_l = new double [ alpha_extreme . length ] ; double [ ] alpha_extreme_r = new double [ alpha_extreme . length ] ; double [ ] alpha_extreme_c = new double [ alpha_extreme . length ] ; System . arraycopy ( alpha_extreme , 0 , alpha_extreme_l , 0 , alpha_extreme . length ) ; System . arraycopy ( alpha_extreme , 0 , alpha_extreme_r , 0 , alpha_extreme . length ) ; System . arraycopy ( alpha_extreme , 0 , alpha_extreme_c , 0 , alpha_extreme . length ) ; double [ ] centroid = SpatialUtil . centroid ( interval ) ; for ( int i = 0 ; i < n ; i ++ ) { alpha_extreme_l [ i ] = centroid [ i ] ; alpha_extreme_r [ i ] = centroid [ i ] ; alpha_extreme_c [ i ] = centroid [ i ] ; } double intervalLength = interval . getMax ( n ) - interval . getMin ( n ) ; alpha_extreme_l [ n ] = Math . random ( ) * intervalLength + interval . getMin ( n ) ; alpha_extreme_r [ n ] = Math . random ( ) * intervalLength + interval . getMin ( n ) ; double f_c = function ( alpha_extreme_c ) ; double f_l = function ( alpha_extreme_l ) ; double f_r = function ( alpha_extreme_r ) ; if ( f_l < f_c ) { if ( f_r < f_c || Math . abs ( f_r - f_c ) < DELTA ) { return ExtremumType . MAXIMUM ; } } if ( f_r < f_c ) { if ( f_l < f_c || Math . abs ( f_l - f_c ) < DELTA ) { return ExtremumType . MAXIMUM ; } } if ( f_l > f_c ) { if ( f_r > f_c || Math . abs ( f_r - f_c ) < DELTA ) { return ExtremumType . MINIMUM ; } } if ( f_r > f_c ) { if ( f_l > f_c || Math . abs ( f_l - f_c ) < DELTA ) { return ExtremumType . MINIMUM ; } } if ( Math . abs ( f_l - f_c ) < DELTA && Math . abs ( f_r - f_c ) < DELTA ) { return ExtremumType . CONSTANT ; } throw new IllegalArgumentException ( "Houston, we have a problem!\n" + this + "\nf_l " + f_l + "\nf_c " + f_c + "\nf_r " + f_r + "\np " + vec + "\nalpha " + FormatUtil . format ( alpha_extreme_c ) + "\nalpha_l " + FormatUtil . format ( alpha_extreme_l ) + "\nalpha_r " + FormatUtil . format ( alpha_extreme_r ) + "\nn " + n ) ; }
Returns the type of the extremum at the specified alpha values .
33,829
private double determineAlphaMin ( int n , double [ ] alpha_min , HyperBoundingBox interval ) { double alpha_n = extremum_alpha_n ( n , alpha_min ) ; double lower = interval . getMin ( n ) ; double upper = interval . getMax ( n ) ; double [ ] alpha_extreme = new double [ alpha_min . length ] ; System . arraycopy ( alpha_min , n , alpha_extreme , n , alpha_extreme . length - n ) ; alpha_extreme [ n ] = alpha_n ; ExtremumType type = extremumType ( n , alpha_extreme , interval ) ; if ( type . equals ( ExtremumType . MINIMUM ) || type . equals ( ExtremumType . CONSTANT ) ) { if ( lower <= alpha_n && alpha_n <= upper ) { return alpha_n ; } else if ( alpha_n < lower ) { return lower ; } else { if ( alpha_n <= upper ) { throw new IllegalStateException ( "Should never happen!" ) ; } return upper ; } } else { if ( lower <= alpha_n && alpha_n <= upper ) { if ( alpha_n - lower <= upper - alpha_n ) { return upper ; } else { return lower ; } } else if ( alpha_n < lower ) { return upper ; } else { if ( alpha_n <= upper ) { throw new IllegalStateException ( "Should never happen!" ) ; } return lower ; } } }
Determines the n - th alpha value where this function has a minimum in the specified interval .
33,830
public static double sinusProduct ( int start , int end , double [ ] alpha ) { double result = 1 ; for ( int j = start ; j < end ; j ++ ) { result *= FastMath . sin ( alpha [ j ] ) ; } return result ; }
Computes the product of all sinus values of the specified angles from start to end index .
33,831
private void determineGlobalExtremum ( ) { alphaExtremum = new double [ vec . getDimensionality ( ) - 1 ] ; for ( int n = alphaExtremum . length - 1 ; n >= 0 ; n -- ) { alphaExtremum [ n ] = extremum_alpha_n ( n , alphaExtremum ) ; if ( Double . isNaN ( alphaExtremum [ n ] ) ) { throw new IllegalStateException ( "Houston, we have a problem!\n" + this + "\n" + vec + "\n" + FormatUtil . format ( alphaExtremum ) ) ; } } determineGlobalExtremumType ( ) ; }
Determines the global extremum of this parameterization function .
33,832
private void determineGlobalExtremumType ( ) { final double f = function ( alphaExtremum ) ; double [ ] alpha_1 = new double [ alphaExtremum . length ] ; double [ ] alpha_2 = new double [ alphaExtremum . length ] ; for ( int i = 0 ; i < alphaExtremum . length ; i ++ ) { alpha_1 [ i ] = Math . random ( ) * Math . PI ; alpha_2 [ i ] = Math . random ( ) * Math . PI ; } double f1 = function ( alpha_1 ) ; double f2 = function ( alpha_2 ) ; if ( f1 < f && f2 < f ) { extremumType = ExtremumType . MAXIMUM ; } else if ( f1 > f && f2 > f ) { extremumType = ExtremumType . MINIMUM ; } else if ( Math . abs ( f1 - f ) < DELTA && Math . abs ( f2 - f ) < DELTA ) { extremumType = ExtremumType . CONSTANT ; } else { throw new IllegalStateException ( "Houston, we have a problem:" + "\n" + this + "\nextremum at " + FormatUtil . format ( alphaExtremum ) + "\nf " + f + "\nf1 " + f1 + "\nf2 " + f2 ) ; } }
Determines the type of the global extremum .
33,833
public void setParameters ( Parameterization config ) { TrackParameters track = new TrackParameters ( config ) ; configureStep ( track ) ; { parameterTable . setEnabled ( false ) ; parameterTable . clear ( ) ; for ( TrackedParameter pair : track . getAllParameters ( ) ) { parameterTable . addParameter ( pair . getOwner ( ) , pair . getParameter ( ) , track ) ; } parameterTable . revalidate ( ) ; parameterTable . setEnabled ( true ) ; } updateStatus ( ) ; firePanelUpdated ( ) ; }
Do the actual setParameters invocation .
33,834
protected void reportErrors ( Parameterization config ) { StringBuilder buf = new StringBuilder ( ) ; for ( ParameterException e : config . getErrors ( ) ) { if ( e instanceof UnspecifiedParameterException ) { continue ; } buf . append ( e . getMessage ( ) ) . append ( FormatUtil . NEWLINE ) ; } if ( buf . length ( ) > 0 ) { LOG . warning ( "Configuration errors:" + FormatUtil . NEWLINE + FormatUtil . NEWLINE + buf . toString ( ) ) ; } }
Report errors in a single error log record .
33,835
public boolean canRun ( ) { Status status = getStatus ( ) ; return Status . STATUS_READY . equals ( status ) || Status . STATUS_COMPLETE . equals ( status ) ; }
Test if this tab is ready - to - run
33,836
public SVGPath lineTo ( double x , double y ) { return append ( PATH_LINE_TO ) . append ( x ) . append ( y ) ; }
Draw a line to the given coordinates .
33,837
public SVGPath relativeLineTo ( double x , double y ) { return append ( PATH_LINE_TO_RELATIVE ) . append ( x ) . append ( y ) ; }
Draw a line to the given relative coordinates .
33,838
public SVGPath moveTo ( double x , double y ) { return append ( PATH_MOVE ) . append ( x ) . append ( y ) ; }
Move to the given coordinates .
33,839
public SVGPath relativeMoveTo ( double x , double y ) { return append ( PATH_MOVE_RELATIVE ) . append ( x ) . append ( y ) ; }
Move to the given relative coordinates .
33,840
public SVGPath smoothQuadTo ( double x , double y ) { return append ( PATH_SMOOTH_QUAD_TO ) . append ( x ) . append ( y ) ; }
Smooth quadratic Bezier line to the given coordinates .
33,841
public SVGPath relativeSmoothQuadTo ( double x , double y ) { return append ( PATH_SMOOTH_QUAD_TO_RELATIVE ) . append ( x ) . append ( y ) ; }
Smooth quadratic Bezier line to the given relative coordinates .
33,842
private SVGPath append ( char action ) { assert lastaction != 0 || action == PATH_MOVE : "Paths must begin with a move to the initial position!" ; if ( lastaction != action ) { buf . append ( action ) ; lastaction = action ; } return this ; }
Append an action to the current path .
33,843
private SVGPath append ( double x ) { if ( ! Double . isFinite ( x ) ) { throw new IllegalArgumentException ( "Cannot draw an infinite/NaN position." ) ; } if ( x >= 0 ) { final int l = buf . length ( ) ; if ( l > 0 ) { char c = buf . charAt ( l - 1 ) ; assert c != 'e' && c != 'E' : "Invalid exponential in path" ; if ( c >= '0' && c <= '9' ) buf . append ( ' ' ) ; } } buf . append ( SVGUtil . FMT . format ( x ) ) ; return this ; }
Append a value to the current path .
33,844
public SVGPath close ( ) { assert lastaction != 0 : "Paths must begin with a move to the initial position!" ; if ( lastaction != PATH_CLOSE ) { buf . append ( ' ' ) . append ( PATH_CLOSE ) ; lastaction = PATH_CLOSE ; } return this ; }
Close the path .
33,845
public Element makeElement ( SVGPlot plot ) { Element elem = plot . svgElement ( SVGConstants . SVG_PATH_TAG ) ; elem . setAttribute ( SVGConstants . SVG_D_ATTRIBUTE , buf . toString ( ) ) ; return elem ; }
Turn the path buffer into an SVG element .
33,846
public void setParameters ( Parameterization config ) { logTab . setParameters ( config ) ; inputTab . setParameters ( config ) ; algTab . setParameters ( config ) ; evalTab . setParameters ( config ) ; outTab . setParameters ( config ) ; }
Set the parameters .
33,847
public ArrayList < String > serializeParameters ( ) { ListParameterization params = new ListParameterization ( ) ; logTab . appendParameters ( params ) ; inputTab . appendParameters ( params ) ; algTab . appendParameters ( params ) ; evalTab . appendParameters ( params ) ; outTab . appendParameters ( params ) ; return params . serialize ( ) ; }
Get the serialized parameters
33,848
public static void main ( final String [ ] args ) { GUIUtil . logUncaughtExceptions ( LOG ) ; GUIUtil . setLookAndFeel ( ) ; OutputStep . setDefaultHandlerVisualizer ( ) ; javax . swing . SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { try { final MultiStepGUI gui = new MultiStepGUI ( ) ; gui . run ( ) ; if ( args != null && args . length > 0 ) { gui . setParameters ( new SerializedParameterization ( args ) ) ; } else { gui . setParameters ( new SerializedParameterization ( ) ) ; } } catch ( Exception | Error e ) { LoggingConfiguration . replaceDefaultHandler ( new CLISmartHandler ( ) ) ; LOG . exception ( e ) ; } } } ) ; }
Main method that just spawns the UI .
33,849
protected static boolean match ( Object ref , Object test ) { if ( ref == null ) { return false ; } if ( ref == test ) { return true ; } if ( ref instanceof LabelList && test instanceof LabelList ) { final LabelList lref = ( LabelList ) ref ; final LabelList ltest = ( LabelList ) test ; final int s1 = lref . size ( ) , s2 = ltest . size ( ) ; if ( s1 == 0 || s2 == 0 ) { return false ; } for ( int i = 0 ; i < s1 ; i ++ ) { String l1 = lref . get ( i ) ; if ( l1 == null ) { continue ; } for ( int j = 0 ; j < s2 ; j ++ ) { if ( l1 . equals ( ltest . get ( j ) ) ) { return true ; } } } } return ref . equals ( test ) ; }
Test whether two relation agree .
33,850
private void findMatches ( ModifiableDBIDs posn , Relation < ? > lrelation , Object label ) { posn . clear ( ) ; for ( DBIDIter ri = lrelation . iterDBIDs ( ) ; ri . valid ( ) ; ri . advance ( ) ) { if ( match ( label , lrelation . get ( ri ) ) ) { posn . add ( ri ) ; } } }
Find all matching objects .
33,851
private void computeDistances ( ModifiableDoubleDBIDList nlist , DBIDIter query , final DistanceQuery < O > distQuery , Relation < O > relation ) { nlist . clear ( ) ; O qo = relation . get ( query ) ; for ( DBIDIter ri = relation . iterDBIDs ( ) ; ri . valid ( ) ; ri . advance ( ) ) { if ( ! includeSelf && DBIDUtil . equal ( ri , query ) ) { continue ; } double dist = distQuery . distance ( qo , ri ) ; if ( dist != dist ) { dist = Double . POSITIVE_INFINITY ; } nlist . add ( dist , ri ) ; } nlist . sort ( ) ; }
Compute the distances to the neighbor objects .
33,852
private PrintStream newStream ( String name ) throws IOException { if ( LOG . isDebuggingFiner ( ) ) { LOG . debugFiner ( "Requested stream: " + name ) ; } if ( ! basename . exists ( ) ) { basename . mkdirs ( ) ; } String fn = basename . getAbsolutePath ( ) + File . separator + name + EXTENSION ; fn = usegzip ? fn + GZIP_EXTENSION : fn ; OutputStream os = new FileOutputStream ( fn ) ; if ( usegzip ) { os = new GZIPOutputStream ( os ) ; } PrintStream res = new PrintStream ( os ) ; if ( LOG . isDebuggingFiner ( ) ) { LOG . debugFiner ( "Opened new output stream:" + fn ) ; } return res ; }
Open a new stream of the given name
33,853
protected < N extends Page & Externalizable > PageFile < N > makePageFile ( Class < N > cls ) { @ SuppressWarnings ( "unchecked" ) final PageFileFactory < N > castFactory = ( PageFileFactory < N > ) pageFileFactory ; return castFactory . newPageFile ( cls ) ; }
Make the page file for this index .
33,854
public static boolean isAngularDistance ( AbstractMaterializeKNNPreprocessor < ? > kNN ) { DistanceFunction < ? > distanceFunction = kNN . getDistanceQuery ( ) . getDistanceFunction ( ) ; return CosineDistanceFunction . class . isInstance ( distanceFunction ) || ArcCosineDistanceFunction . class . isInstance ( distanceFunction ) ; }
Test whether the given preprocessor used an angular distance function
33,855
public static Element drawCosine ( SVGPlot svgp , Projection2D proj , NumberVector mid , double angle ) { double [ ] pointOfOrigin = proj . fastProjectDataToRenderSpace ( new double [ proj . getInputDimensionality ( ) ] ) ; double [ ] selPoint = proj . fastProjectDataToRenderSpace ( mid ) ; double [ ] range1 , range2 ; { double [ ] pm = mid . toArray ( ) ; double [ ] p1 = minusEquals ( proj . fastProjectRenderToDataSpace ( selPoint [ 0 ] + 10 , selPoint [ 1 ] ) , pm ) ; double [ ] p2 = minusEquals ( proj . fastProjectRenderToDataSpace ( selPoint [ 0 ] , selPoint [ 1 ] + 10 ) , pm ) ; timesEquals ( p1 , 1. / euclideanLength ( p1 ) ) ; timesEquals ( p2 , 1. / euclideanLength ( p2 ) ) ; if ( Math . abs ( scalarProduct ( p1 , p2 ) ) > 1E-10 ) { LoggingUtil . warning ( "Projection does not seem to be orthogonal?" ) ; } double l1 = scalarProduct ( pm , p1 ) , l2 = scalarProduct ( pm , p2 ) ; final DoubleWrapper tmp = new DoubleWrapper ( ) ; final double sangle = FastMath . sinAndCos ( angle , tmp ) , cangle = tmp . value ; double r11 = + cangle * l1 - sangle * l2 , r12 = + sangle * l1 + cangle * l2 ; double r21 = + cangle * l1 + sangle * l2 , r22 = - sangle * l1 + cangle * l2 ; double [ ] r1 = plusTimesEquals ( plusTimes ( pm , p1 , - l1 + r11 ) , p2 , - l2 + r12 ) ; double [ ] r2 = plusTimesEquals ( plusTimes ( pm , p1 , - l1 + r21 ) , p2 , - l2 + r22 ) ; range1 = proj . fastProjectDataToRenderSpace ( r1 ) ; range2 = proj . fastProjectDataToRenderSpace ( r2 ) ; } { CanvasSize viewport = proj . estimateViewport ( ) ; minusEquals ( range1 , pointOfOrigin ) ; plusEquals ( timesEquals ( range1 , viewport . continueToMargin ( pointOfOrigin , range1 ) ) , pointOfOrigin ) ; minusEquals ( range2 , pointOfOrigin ) ; plusEquals ( timesEquals ( range2 , viewport . continueToMargin ( pointOfOrigin , range2 ) ) , pointOfOrigin ) ; double [ ] start1 = minus ( pointOfOrigin , range1 ) ; plusEquals ( timesEquals ( start1 , viewport . continueToMargin ( range1 , start1 ) ) , range1 ) ; double [ ] start2 = minus ( pointOfOrigin , range2 ) ; plusEquals ( timesEquals ( start2 , viewport . continueToMargin ( range2 , start2 ) ) , range2 ) ; return new SVGPath ( ) . moveTo ( start1 ) . lineTo ( range1 ) . moveTo ( start2 ) . lineTo ( range2 ) . makeElement ( svgp ) ; } }
Visualizes Cosine and ArcCosine distance functions
33,856
public void splitupNoSort ( ArrayModifiableDBIDs ind , int begin , int end , int dim , Random rand ) { final int nele = end - begin ; dim = dim % projectedPoints . length ; DoubleDataStore tpro = projectedPoints [ dim ] ; if ( nele > minSplitSize * ( 1 - sizeTolerance ) && nele < minSplitSize * ( 1 + sizeTolerance ) ) { ind . sort ( begin , end , new DataStoreUtil . AscendingByDoubleDataStore ( tpro ) ) ; splitsets . add ( DBIDUtil . newArray ( ind . slice ( begin , end ) ) ) ; } if ( nele > minSplitSize ) { int minInd = splitRandomly ( ind , begin , end , tpro , rand ) ; int splitpos = minInd + 1 ; splitupNoSort ( ind , begin , splitpos , dim + 1 , rand ) ; splitupNoSort ( ind , splitpos , end , dim + 1 , rand ) ; } }
Recursively splits entire point set until the set is below a threshold
33,857
public int splitRandomly ( ArrayModifiableDBIDs ind , int begin , int end , DoubleDataStore tpro , Random rand ) { final int nele = end - begin ; DBIDArrayIter it = ind . iter ( ) ; double rs = tpro . doubleValue ( it . seek ( begin + rand . nextInt ( nele ) ) ) ; int minInd = begin , maxInd = end - 1 ; while ( minInd < maxInd ) { double currEle = tpro . doubleValue ( it . seek ( minInd ) ) ; if ( currEle > rs ) { while ( minInd < maxInd && tpro . doubleValue ( it . seek ( maxInd ) ) > rs ) { maxInd -- ; } if ( minInd == maxInd ) { break ; } ind . swap ( minInd , maxInd ) ; maxInd -- ; } minInd ++ ; } if ( minInd == end - 1 ) { minInd = ( begin + end ) >>> 1 ; } return minInd ; }
Split the data set randomly .
33,858
public int splitByDistance ( ArrayModifiableDBIDs ind , int begin , int end , DoubleDataStore tpro , Random rand ) { DBIDArrayIter it = ind . iter ( ) ; double rmin = Double . MAX_VALUE * .5 , rmax = - Double . MAX_VALUE * .5 ; int minInd = begin , maxInd = end - 1 ; for ( it . seek ( begin ) ; it . getOffset ( ) < end ; it . advance ( ) ) { double currEle = tpro . doubleValue ( it ) ; rmin = Math . min ( currEle , rmin ) ; rmax = Math . max ( currEle , rmax ) ; } if ( rmin != rmax ) { double rs = rmin + rand . nextDouble ( ) * ( rmax - rmin ) ; while ( minInd < maxInd ) { double currEle = tpro . doubleValue ( it . seek ( minInd ) ) ; if ( currEle > rs ) { while ( minInd < maxInd && tpro . doubleValue ( it . seek ( maxInd ) ) > rs ) { maxInd -- ; } if ( minInd == maxInd ) { break ; } ind . swap ( minInd , maxInd ) ; maxInd -- ; } minInd ++ ; } } else { minInd = ( begin + end ) >>> 1 ; } return minInd ; }
Split the data set by distances .
33,859
public DataStore < ? extends DBIDs > getNeighs ( ) { final DBIDs ids = points . getDBIDs ( ) ; WritableDataStore < ModifiableDBIDs > neighs = DataStoreUtil . makeStorage ( ids , DataStoreFactory . HINT_HOT , ModifiableDBIDs . class ) ; for ( DBIDIter it = ids . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { neighs . put ( it , DBIDUtil . newHashSet ( ) ) ; } FiniteProgress splitp = LOG . isVerbose ( ) ? new FiniteProgress ( "Processing splits for neighborhoods" , splitsets . size ( ) , LOG ) : null ; Iterator < ArrayDBIDs > it1 = splitsets . iterator ( ) ; DBIDVar v = DBIDUtil . newVar ( ) ; while ( it1 . hasNext ( ) ) { ArrayDBIDs pinSet = it1 . next ( ) ; final int indoff = pinSet . size ( ) >> 1 ; pinSet . assignVar ( indoff , v ) ; neighs . get ( v ) . addDBIDs ( pinSet ) ; for ( DBIDIter it = pinSet . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { neighs . get ( it ) . add ( v ) ; } LOG . incrementProcessed ( splitp ) ; } LOG . ensureCompleted ( splitp ) ; return neighs ; }
Compute list of neighbors for each point from sets resulting from projection
33,860
public DoubleDataStore computeAverageDistInSet ( ) { WritableDoubleDataStore davg = DataStoreUtil . makeDoubleStorage ( points . getDBIDs ( ) , DataStoreFactory . HINT_HOT ) ; WritableIntegerDataStore nDists = DataStoreUtil . makeIntegerStorage ( points . getDBIDs ( ) , DataStoreFactory . HINT_HOT | DataStoreFactory . HINT_TEMP ) ; FiniteProgress splitp = LOG . isVerbose ( ) ? new FiniteProgress ( "Processing splits for density estimation" , splitsets . size ( ) , LOG ) : null ; DBIDVar v = DBIDUtil . newVar ( ) ; for ( Iterator < ArrayDBIDs > it1 = splitsets . iterator ( ) ; it1 . hasNext ( ) ; ) { ArrayDBIDs pinSet = it1 . next ( ) ; final int len = pinSet . size ( ) ; final int indoff = len >> 1 ; pinSet . assignVar ( indoff , v ) ; V midpoint = points . get ( v ) ; for ( DBIDArrayIter it = pinSet . iter ( ) ; it . getOffset ( ) < len ; it . advance ( ) ) { if ( DBIDUtil . equal ( it , v ) ) { continue ; } double dist = EuclideanDistanceFunction . STATIC . distance ( points . get ( it ) , midpoint ) ; ++ distanceComputations ; davg . increment ( v , dist ) ; nDists . increment ( v , 1 ) ; davg . increment ( it , dist ) ; nDists . increment ( it , 1 ) ; } LOG . incrementProcessed ( splitp ) ; } LOG . ensureCompleted ( splitp ) ; for ( DBIDIter it = points . getDBIDs ( ) . iter ( ) ; it . valid ( ) ; it . advance ( ) ) { int count = nDists . intValue ( it ) ; double val = ( count == 0 ) ? FastOPTICS . UNDEFINED_DISTANCE : ( davg . doubleValue ( it ) / count ) ; davg . put ( it , val ) ; } nDists . destroy ( ) ; return davg ; }
Compute for each point a density estimate as inverse of average distance to a point in a projected set
33,861
public boolean containedIn ( SparseNumberVector bv ) { int i1 = this . iter ( ) , i2 = bv . iter ( ) ; while ( this . iterValid ( i1 ) ) { if ( ! bv . iterValid ( i2 ) ) { return false ; } int d1 = this . iterDim ( i1 ) , d2 = bv . iterDim ( i2 ) ; if ( d1 < d2 ) { return false ; } if ( d1 == d2 ) { if ( bv . iterDoubleValue ( i2 ) == 0. ) { return false ; } i1 = this . iterAdvance ( i1 ) ; } i2 = bv . iterAdvance ( i2 ) ; } return true ; }
Test whether the itemset is contained in a bit vector .
33,862
public static long [ ] toBitset ( Itemset i , long [ ] bits ) { for ( int it = i . iter ( ) ; i . iterValid ( it ) ; it = i . iterAdvance ( it ) ) { BitsUtil . setI ( bits , i . iterDim ( it ) ) ; } return bits ; }
Get the items .
33,863
protected static int compareLexicographical ( Itemset a , Itemset o ) { int i1 = a . iter ( ) , i2 = o . iter ( ) ; while ( a . iterValid ( i1 ) && o . iterValid ( i2 ) ) { int v1 = a . iterDim ( i1 ) , v2 = o . iterDim ( i2 ) ; if ( v1 < v2 ) { return - 1 ; } if ( v2 < v1 ) { return + 1 ; } i1 = a . iterAdvance ( i1 ) ; i2 = o . iterAdvance ( i2 ) ; } return a . iterValid ( i1 ) ? 1 : o . iterValid ( i2 ) ? - 1 : 0 ; }
Robust compare using the iterators lexicographical only!
33,864
public final StringBuilder appendTo ( StringBuilder buf , VectorFieldTypeInformation < BitVector > meta ) { appendItemsTo ( buf , meta ) ; return buf . append ( ": " ) . append ( support ) ; }
Append items and support to a string buffer .
33,865
public StringBuilder appendItemsTo ( StringBuilder buf , VectorFieldTypeInformation < BitVector > meta ) { int it = this . iter ( ) ; if ( this . iterValid ( it ) ) { while ( true ) { int v = this . iterDim ( it ) ; String lbl = ( meta != null ) ? meta . getLabel ( v ) : null ; if ( lbl == null ) { buf . append ( v ) ; } else { buf . append ( lbl ) ; } it = this . iterAdvance ( it ) ; if ( ! this . iterValid ( it ) ) { break ; } buf . append ( ", " ) ; } } return buf ; }
Only append the items to a string buffer .
33,866
public double getWeight ( double distance , double max , double stddev ) { if ( max <= 0 ) { return 1.0 ; } double relativedistance = distance / max ; return FastMath . exp ( - 2.3025850929940455 * relativedistance * relativedistance ) ; }
Get Gaussian weight . stddev is not used scaled using max .
33,867
public void writePage ( int pageID , P page ) { if ( page . isDirty ( ) ) { try { countWrite ( ) ; byte [ ] array = pageToByteArray ( page ) ; file . getRecordBuffer ( pageID ) . put ( array ) ; page . setDirty ( false ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } }
Write page to disk .
33,868
private byte [ ] pageToByteArray ( P page ) { try { if ( page == null ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( baos ) ; oos . writeInt ( EMPTY_PAGE ) ; oos . close ( ) ; baos . close ( ) ; byte [ ] array = baos . toByteArray ( ) ; byte [ ] result = new byte [ pageSize ] ; System . arraycopy ( array , 0 , result , 0 , array . length ) ; return result ; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( baos ) ; oos . writeInt ( FILLED_PAGE ) ; oos . writeObject ( page ) ; oos . close ( ) ; baos . close ( ) ; byte [ ] array = baos . toByteArray ( ) ; if ( array . length > this . pageSize ) { throw new IllegalArgumentException ( "Size of page " + page + " is greater than specified" + " pagesize: " + array . length + " > " + pageSize ) ; } else if ( array . length == this . pageSize ) { return array ; } else { byte [ ] result = new byte [ pageSize ] ; System . arraycopy ( array , 0 , result , 0 , array . length ) ; return result ; } } } catch ( IOException e ) { throw new RuntimeException ( "IOException occurred! " , e ) ; } }
Serializes an object into a byte array .
33,869
public static SinCosTable make ( int steps ) { if ( ( steps & 0x3 ) == 0 ) { return new QuarterTable ( steps ) ; } if ( ( steps & 0x1 ) == 0 ) { return new HalfTable ( steps ) ; } return new FullTable ( steps ) ; }
Make a table for the given number of steps .
33,870
protected void process ( DBIDRef id , ArrayDBIDs ids , DBIDArrayIter it , int n , WritableDBIDDataStore pi , WritableDoubleDataStore lambda , WritableDoubleDataStore m ) { clinkstep3 ( id , it , n , pi , lambda , m ) ; clinkstep4567 ( id , ids , it , n , pi , lambda , m ) ; clinkstep8 ( id , it , n , pi , lambda , m ) ; }
CLINK main loop based on the SLINK main loop .
33,871
private void clinkstep8 ( DBIDRef id , DBIDArrayIter it , int n , WritableDBIDDataStore pi , WritableDoubleDataStore lambda , WritableDoubleDataStore m ) { DBIDVar p_i = DBIDUtil . newVar ( ) , pp_i = DBIDUtil . newVar ( ) ; for ( it . seek ( 0 ) ; it . getOffset ( ) < n ; it . advance ( ) ) { p_i . from ( pi , it ) ; pp_i . from ( pi , p_i ) ; if ( DBIDUtil . equal ( pp_i , id ) && lambda . doubleValue ( it ) >= lambda . doubleValue ( p_i ) ) { pi . putDBID ( it , id ) ; } } }
Update hierarchy .
33,872
public static int levenshteinDistance ( String o1 , String o2 ) { if ( o1 . length ( ) > o2 . length ( ) ) { return levenshteinDistance ( o2 , o1 ) ; } final int l1 = o1 . length ( ) , l2 = o2 . length ( ) ; if ( l1 == l2 && o1 . hashCode ( ) == o2 . hashCode ( ) && o1 . equals ( o2 ) ) { return 0 ; } final int prefix = prefixLen ( o1 , o2 ) ; if ( prefix == l1 || prefix == l2 ) { return Math . abs ( l1 - l2 ) ; } final int postfix = postfixLen ( o1 , o2 , prefix ) ; return ( prefix + postfix == l1 || prefix + postfix == l2 ) ? Math . abs ( l1 - l2 ) : ( l1 == l2 && prefix + postfix + 1 == l1 ) ? 1 : levenshteinDistance ( o1 , o2 , prefix , postfix ) ; }
Levenshtein distance for two strings .
33,873
private static int prefixLen ( String o1 , String o2 ) { final int l1 = o1 . length ( ) , l2 = o2 . length ( ) , l = l1 < l2 ? l1 : l2 ; int prefix = 0 ; while ( prefix < l && ( o1 . charAt ( prefix ) == o2 . charAt ( prefix ) ) ) { prefix ++ ; } return prefix ; }
Compute the length of the prefix .
33,874
private static int postfixLen ( String o1 , String o2 , int prefix ) { int postfix = 0 ; int p1 = o1 . length ( ) , p2 = o2 . length ( ) ; while ( p1 > prefix && p2 > prefix && ( o1 . charAt ( -- p1 ) == o2 . charAt ( -- p2 ) ) ) { ++ postfix ; } return postfix ; }
Compute the postfix length .
33,875
public static int levenshteinDistance ( String o1 , String o2 , int prefix , int postfix ) { final int l1 = o1 . length ( ) , l2 = o2 . length ( ) ; int [ ] buf = new int [ ( l2 + 1 - ( prefix + postfix ) ) << 1 ] ; for ( int j = 0 ; j < buf . length ; j += 2 ) { buf [ j ] = j >> 1 ; } int inter = 1 ; for ( int i = prefix , e1 = l1 - postfix ; i < e1 ; i ++ , inter ^= 1 ) { final char chr = o1 . charAt ( i ) ; buf [ inter ] = i + 1 - prefix ; for ( int c = 2 + inter , p = 3 - inter , j = prefix ; c < buf . length ; c += 2 , p += 2 ) { buf [ c ] = min ( buf [ p ] + 1 , buf [ c - 2 ] + 1 , buf [ p - 2 ] + ( ( chr == o2 . charAt ( j ++ ) ) ? 0 : 1 ) ) ; } } return buf [ buf . length - 2 + ( inter ^ 1 ) ] ; }
Compute the Levenshtein distance except for prefix and postfix .
33,876
private static int nextSep ( String str , int start ) { int next = str . indexOf ( ',' , start ) ; return next == - 1 ? str . length ( ) : next ; }
Find the next separator .
33,877
public static double [ ] [ ] computeWeightMatrix ( final int quanth , final int quants , final int quantb ) { final int dim = quanth * quants * quantb ; final DoubleWrapper tmp = new DoubleWrapper ( ) ; assert ( dim > 0 ) ; final double [ ] [ ] m = new double [ dim ] [ dim ] ; for ( int x = 0 ; x < dim ; x ++ ) { final int hx = x / ( quantb * quants ) ; final int sx = ( x / quantb ) % quants ; final int bx = x % quantb ; for ( int y = x ; y < dim ; y ++ ) { final int hy = y / ( quantb * quants ) ; final int sy = ( y / quantb ) % quants ; final int by = y % quantb ; final double shx = FastMath . sinAndCos ( ( hx + .5 ) / quanth * MathUtil . TWOPI , tmp ) ; final double chx = tmp . value ; final double shy = FastMath . sinAndCos ( ( hy + .5 ) / quanth * MathUtil . TWOPI , tmp ) ; final double chy = tmp . value ; final double cos = chx * ( sx + .5 ) / quants - chy * ( sy + .5 ) / quants ; final double sin = shx * ( sx + .5 ) / quants - shy * ( sy + .5 ) / quants ; final double db = ( bx - by ) / ( double ) quantb ; final double val = 1. - FastMath . sqrt ( ( db * db + sin * sin + cos * cos ) / 5 ) ; m [ x ] [ y ] = m [ y ] [ x ] = val ; } } return m ; }
Compute the weight matrix for HSB similarity .
33,878
public static double [ ] plus ( final double [ ] v1 , final double [ ] v2 ) { assert v1 . length == v2 . length : ERR_VEC_DIMENSIONS ; final double [ ] result = new double [ v1 . length ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = v1 [ i ] + v2 [ i ] ; } return result ; }
Computes component - wise v1 + v2 for vectors .
33,879
public static double [ ] plusEquals ( final double [ ] v1 , final double [ ] v2 ) { assert v1 . length == v2 . length : ERR_VEC_DIMENSIONS ; for ( int i = 0 ; i < v1 . length ; i ++ ) { v1 [ i ] += v2 [ i ] ; } return v1 ; }
Computes component - wise v1 = v1 + v2 overwriting the vector v1 .
33,880
public static double [ ] plus ( final double [ ] v1 , final double s1 ) { final double [ ] result = new double [ v1 . length ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = v1 [ i ] + s1 ; } return result ; }
Computes component - wise v1 + s1 .
33,881
public static double [ ] plusEquals ( final double [ ] v1 , final double s1 ) { for ( int i = 0 ; i < v1 . length ; i ++ ) { v1 [ i ] += s1 ; } return v1 ; }
Computes component - wise v1 = v1 + s1 overwriting the vector v1 .
33,882
public static double [ ] minus ( final double [ ] v1 , final double [ ] v2 ) { assert v1 . length == v2 . length : ERR_VEC_DIMENSIONS ; final double [ ] sub = new double [ v1 . length ] ; for ( int i = 0 ; i < v1 . length ; i ++ ) { sub [ i ] = v1 [ i ] - v2 [ i ] ; } return sub ; }
Computes component - wise v1 - v2 .
33,883
public static double [ ] minusEquals ( final double [ ] v1 , final double [ ] v2 ) { assert v1 . length == v2 . length : ERR_VEC_DIMENSIONS ; for ( int i = 0 ; i < v1 . length ; i ++ ) { v1 [ i ] -= v2 [ i ] ; } return v1 ; }
Computes component - wise v1 = v1 - v2 overwriting the vector v1 .
33,884
public static double [ ] minus ( final double [ ] v1 , final double s1 ) { final double [ ] result = new double [ v1 . length ] ; for ( int i = 0 ; i < v1 . length ; i ++ ) { result [ i ] = v1 [ i ] - s1 ; } return result ; }
Subtract component - wise v1 - s1 .
33,885
public static double [ ] minusEquals ( final double [ ] v1 , final double s1 ) { for ( int i = 0 ; i < v1 . length ; i ++ ) { v1 [ i ] -= s1 ; } return v1 ; }
Subtract component - wise in - place v1 = v1 - s1 overwriting the vector v1 .
33,886
public static double sum ( final double [ ] v1 ) { double acc = 0. ; for ( int row = 0 ; row < v1 . length ; row ++ ) { acc += v1 [ row ] ; } return acc ; }
Sum of the vector components .
33,887
public static int argmax ( double [ ] v ) { assert ( v . length > 0 ) ; int maxIndex = 0 ; double currentMax = v [ 0 ] ; for ( int i = 1 ; i < v . length ; i ++ ) { final double x = v [ i ] ; if ( x > currentMax ) { maxIndex = i ; currentMax = x ; } } return maxIndex ; }
Find the maximum value .
33,888
public static double [ ] normalize ( final double [ ] v1 ) { final double norm = 1. / euclideanLength ( v1 ) ; double [ ] re = new double [ v1 . length ] ; if ( norm < Double . POSITIVE_INFINITY ) { for ( int row = 0 ; row < v1 . length ; row ++ ) { re [ row ] = v1 [ row ] * norm ; } } return re ; }
Normalizes v1 to the length of 1 . 0 .
33,889
public static double [ ] normalizeEquals ( final double [ ] v1 ) { final double norm = 1. / euclideanLength ( v1 ) ; if ( norm < Double . POSITIVE_INFINITY ) { for ( int row = 0 ; row < v1 . length ; row ++ ) { v1 [ row ] *= norm ; } } return v1 ; }
Normalizes v1 to the length of 1 . 0 in place .
33,890
public static void clear ( final double [ ] [ ] m ) { for ( int i = 0 ; i < m . length ; i ++ ) { Arrays . fill ( m [ i ] , 0.0 ) ; } }
Reset the matrix to 0 .
33,891
public static double [ ] rotate90Equals ( final double [ ] v1 ) { assert v1 . length == 2 : "rotate90Equals is only valid for 2d vectors." ; final double temp = v1 [ 0 ] ; v1 [ 0 ] = v1 [ 1 ] ; v1 [ 1 ] = - temp ; return v1 ; }
Rotate the two - dimensional vector by 90 degrees .
33,892
public static double [ ] [ ] diagonal ( final double [ ] v1 ) { final int dim = v1 . length ; final double [ ] [ ] result = new double [ dim ] [ dim ] ; for ( int i = 0 ; i < dim ; i ++ ) { result [ i ] [ i ] = v1 [ i ] ; } return result ; }
Returns a quadratic matrix consisting of zeros and of the given values on the diagonal .
33,893
public static double [ ] [ ] copy ( final double [ ] [ ] m1 ) { final int rowdim = m1 . length , coldim = getColumnDimensionality ( m1 ) ; final double [ ] [ ] X = new double [ rowdim ] [ coldim ] ; for ( int i = 0 ; i < rowdim ; i ++ ) { System . arraycopy ( m1 [ i ] , 0 , X [ i ] , 0 , coldim ) ; } return X ; }
Make a deep copy of a matrix .
33,894
public static double [ ] getCol ( double [ ] [ ] m1 , int col ) { double [ ] ret = new double [ m1 . length ] ; for ( int i = 0 ; i < ret . length ; i ++ ) { ret [ i ] = m1 [ i ] [ col ] ; } return ret ; }
Get a column from a matrix as vector .
33,895
public static double [ ] getDiagonal ( final double [ ] [ ] m1 ) { final int dim = Math . min ( getColumnDimensionality ( m1 ) , m1 . length ) ; final double [ ] diagonal = new double [ dim ] ; for ( int i = 0 ; i < dim ; i ++ ) { diagonal [ i ] = m1 [ i ] [ i ] ; } return diagonal ; }
getDiagonal returns array of diagonal - elements .
33,896
public static void normalizeColumns ( final double [ ] [ ] m1 ) { final int columndimension = getColumnDimensionality ( m1 ) ; for ( int col = 0 ; col < columndimension ; col ++ ) { double norm = 0.0 ; for ( int row = 0 ; row < m1 . length ; row ++ ) { final double v = m1 [ row ] [ col ] ; norm += v * v ; } if ( norm > 0 ) { norm = FastMath . sqrt ( norm ) ; for ( int row = 0 ; row < m1 . length ; row ++ ) { m1 [ row ] [ col ] /= norm ; } } } }
Normalizes the columns of this matrix to length of 1 . 0 .
33,897
public static double [ ] [ ] appendColumns ( final double [ ] [ ] m1 , final double [ ] [ ] m2 ) { final int columndimension = getColumnDimensionality ( m1 ) ; final int ccolumndimension = getColumnDimensionality ( m2 ) ; assert m1 . length == m2 . length : "m.getRowDimension() != column.getRowDimension()" ; final int rcolumndimension = columndimension + ccolumndimension ; final double [ ] [ ] result = new double [ m1 . length ] [ rcolumndimension ] ; for ( int i = 0 ; i < rcolumndimension ; i ++ ) { if ( i < columndimension ) { setCol ( result , i , getCol ( m1 , i ) ) ; } else { setCol ( result , i , getCol ( m2 , i - columndimension ) ) ; } } return result ; }
Returns a matrix which consists of this matrix and the specified columns .
33,898
public static double [ ] [ ] orthonormalize ( final double [ ] [ ] m1 ) { final int columndimension = getColumnDimensionality ( m1 ) ; final double [ ] [ ] v = copy ( m1 ) ; for ( int i = 1 ; i < columndimension ; i ++ ) { final double [ ] u_i = getCol ( m1 , i ) ; final double [ ] sum = new double [ m1 . length ] ; for ( int j = 0 ; j < i ; j ++ ) { final double [ ] v_j = getCol ( v , j ) ; final double scalar = scalarProduct ( u_i , v_j ) / scalarProduct ( v_j , v_j ) ; plusEquals ( sum , times ( v_j , scalar ) ) ; } final double [ ] v_i = minus ( u_i , sum ) ; setCol ( v , i , v_i ) ; } normalizeColumns ( v ) ; return v ; }
Returns an orthonormalization of this matrix .
33,899
public static double [ ] [ ] inverse ( double [ ] [ ] A ) { final int rows = A . length , cols = A [ 0 ] . length ; return rows == cols ? ( new LUDecomposition ( A , rows , cols ) ) . inverse ( ) : ( new QRDecomposition ( A , rows , cols ) ) . inverse ( ) ; }
Matrix inverse or pseudoinverse