idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
149,000
public void process ( DMatrixSparseCSC A , int parent [ ] , int post [ ] , int counts [ ] ) { if ( counts . length < A . numCols ) throw new IllegalArgumentException ( "counts must be at least of length A.numCols" ) ; initialize ( A ) ; int delta [ ] = counts ; findFirstDescendant ( parent , post , delta ) ; if ( ata ) { init_ata ( post ) ; } for ( int i = 0 ; i < n ; i ++ ) w [ ancestor + i ] = i ; int [ ] ATp = At . col_idx ; int [ ] ATi = At . nz_rows ; for ( int k = 0 ; k < n ; k ++ ) { int j = post [ k ] ; if ( parent [ j ] != - 1 ) delta [ parent [ j ] ] -- ; // j is not a root for ( int J = HEAD ( k , j ) ; J != - 1 ; J = NEXT ( J ) ) { for ( int p = ATp [ J ] ; p < ATp [ J + 1 ] ; p ++ ) { int i = ATi [ p ] ; int q = isLeaf ( i , j ) ; if ( jleaf >= 1 ) delta [ j ] ++ ; if ( jleaf == 2 ) delta [ q ] -- ; } } if ( parent [ j ] != - 1 ) w [ ancestor + j ] = parent [ j ] ; } // sum up delta's of each child for ( int j = 0 ; j < n ; j ++ ) { if ( parent [ j ] != - 1 ) counts [ parent [ j ] ] += counts [ j ] ; } }
Processes and computes column counts of A
370
9
149,001
public static void show ( DMatrixD1 A , String title ) { JFrame frame = new JFrame ( title ) ; int width = 300 ; int height = 300 ; if ( A . numRows > A . numCols ) { width = width * A . numCols / A . numRows ; } else { height = height * A . numRows / A . numCols ; } DMatrixComponent panel = new DMatrixComponent ( width , height ) ; panel . setMatrix ( A ) ; frame . add ( panel , BorderLayout . CENTER ) ; frame . pack ( ) ; frame . setVisible ( true ) ; }
Creates a window visually showing the matrix s state . Block means an element is zero . Red positive and blue negative . More intense the color larger the element s absolute value is .
142
36
149,002
public void value2x2 ( double a11 , double a12 , double a21 , double a22 ) { // apply a rotators such that th a11 and a22 elements are the same double c , s ; if ( a12 + a21 == 0 ) { // is this pointless since c = s = 1.0 / Math . sqrt ( 2 ) ; } else { double aa = ( a11 - a22 ) ; double bb = ( a12 + a21 ) ; double t_hat = aa / bb ; double t = t_hat / ( 1.0 + Math . sqrt ( 1.0 + t_hat * t_hat ) ) ; c = 1.0 / Math . sqrt ( 1.0 + t * t ) ; s = c * t ; } double c2 = c * c ; double s2 = s * s ; double cs = c * s ; double b11 = c2 * a11 + s2 * a22 - cs * ( a12 + a21 ) ; double b12 = c2 * a12 - s2 * a21 + cs * ( a11 - a22 ) ; double b21 = c2 * a21 - s2 * a12 + cs * ( a11 - a22 ) ; // double b22 = c2*a22 + s2*a11 + cs*(a12+a21); // apply second rotator to make A upper triangular if real eigenvalues if ( b21 * b12 >= 0 ) { if ( b12 == 0 ) { c = 0 ; s = 1 ; } else { s = Math . sqrt ( b21 / ( b12 + b21 ) ) ; c = Math . sqrt ( b12 / ( b12 + b21 ) ) ; } // c2 = b12;//c*c; // s2 = b21;//s*s; cs = c * s ; a11 = b11 - cs * ( b12 + b21 ) ; // a12 = c2*b12 - s2*b21; // a21 = c2*b21 - s2*b12; a22 = b11 + cs * ( b12 + b21 ) ; value0 . real = a11 ; value1 . real = a22 ; value0 . imaginary = value1 . imaginary = 0 ; } else { value0 . real = value1 . real = b11 ; value0 . imaginary = Math . sqrt ( - b21 * b12 ) ; value1 . imaginary = - value0 . imaginary ; } }
if |a11 - a22| >> |a12 + a21| there might be a better way . see pg371
554
26
149,003
public void value2x2_fast ( double a11 , double a12 , double a21 , double a22 ) { double left = ( a11 + a22 ) / 2.0 ; double inside = 4.0 * a12 * a21 + ( a11 - a22 ) * ( a11 - a22 ) ; if ( inside < 0 ) { value0 . real = value1 . real = left ; value0 . imaginary = Math . sqrt ( - inside ) / 2.0 ; value1 . imaginary = - value0 . imaginary ; } else { double right = Math . sqrt ( inside ) / 2.0 ; value0 . real = ( left + right ) ; value1 . real = ( left - right ) ; value0 . imaginary = value1 . imaginary = 0.0 ; } }
Computes the eigenvalues of a 2 by 2 matrix using a faster but more prone to errors method . This is the typical method .
174
28
149,004
public void symm2x2_fast ( double a11 , double a12 , double a22 ) { // double p = (a11 - a22)*0.5; // double r = Math.sqrt(p*p + a12*a12); // // value0.real = a22 + a12*a12/(r-p); // value1.real = a22 - a12*a12/(r+p); // } // // public void symm2x2_std( double a11 , double a12, double a22 ) // { double left = ( a11 + a22 ) * 0.5 ; double b = ( a11 - a22 ) * 0.5 ; double right = Math . sqrt ( b * b + a12 * a12 ) ; value0 . real = left + right ; value1 . real = left - right ; }
See page 385 of Fundamentals of Matrix Computations 2nd
190
13
149,005
public static long wrapped ( DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c ) { long timeBefore = System . currentTimeMillis ( ) ; double valA ; int indexCbase = 0 ; int endOfKLoop = b . numRows * b . numCols ; for ( int i = 0 ; i < a . numRows ; i ++ ) { int indexA = i * a . numCols ; // need to assign dataC to a value initially int indexB = 0 ; int indexC = indexCbase ; int end = indexB + b . numCols ; valA = a . get ( indexA ++ ) ; while ( indexB < end ) { c . set ( indexC ++ , valA * b . get ( indexB ++ ) ) ; } // now add to it while ( indexB != endOfKLoop ) { // k loop indexC = indexCbase ; end = indexB + b . numCols ; valA = a . get ( indexA ++ ) ; while ( indexB < end ) { // j loop c . plus ( indexC ++ , valA * b . get ( indexB ++ ) ) ; } } indexCbase += c . numCols ; } return System . currentTimeMillis ( ) - timeBefore ; }
Wrapper functions with no bounds checking are used to access matrix internals
286
14
149,006
public static long access2d ( DMatrixRMaj a , DMatrixRMaj b , DMatrixRMaj c ) { long timeBefore = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < a . numRows ; i ++ ) { for ( int j = 0 ; j < b . numCols ; j ++ ) { c . set ( i , j , a . get ( i , 0 ) * b . get ( 0 , j ) ) ; } for ( int k = 1 ; k < b . numRows ; k ++ ) { for ( int j = 0 ; j < b . numCols ; j ++ ) { // c.set(i,j, c.get(i,j) + a.get(i,k)*b.get(k,j)); c . data [ i * b . numCols + j ] += a . get ( i , k ) * b . get ( k , j ) ; } } } return System . currentTimeMillis ( ) - timeBefore ; }
Only sets and gets that are by row and column are used .
230
13
149,007
public String p ( double value ) { return UtilEjml . fancyString ( value , format , false , length , significant ) ; }
Fancy print without a space added to positive numbers
30
10
149,008
public boolean process ( int sideLength , double diag [ ] , double off [ ] , double eigenvalues [ ] ) { if ( diag != null ) helper . init ( diag , off , sideLength ) ; if ( Q == null ) Q = CommonOps_DDRM . identity ( helper . N ) ; helper . setQ ( Q ) ; this . followingScript = true ; this . eigenvalues = eigenvalues ; this . fastEigenvalues = false ; return _process ( ) ; }
Computes the eigenvalue of the provided tridiagonal matrix . Note that only the upper portion needs to be tridiagonal . The bottom diagonal is assumed to be the same as the top .
110
40
149,009
public void performStep ( ) { // check for zeros for ( int i = helper . x2 - 1 ; i >= helper . x1 ; i -- ) { if ( helper . isZero ( i ) ) { helper . splits [ helper . numSplits ++ ] = i ; helper . x1 = i + 1 ; return ; } } double lambda ; if ( followingScript ) { if ( helper . steps > 10 ) { followingScript = false ; return ; } else { // Using the true eigenvalues will in general lead to the fastest convergence // typically takes 1 or 2 steps lambda = eigenvalues [ helper . x2 ] ; } } else { // the current eigenvalue isn't working so try something else lambda = helper . computeShift ( ) ; } // similar transforms helper . performImplicitSingleStep ( lambda , false ) ; }
First looks for zeros and then performs the implicit single step in the QR Algorithm .
179
18
149,010
public static void block ( DMatrix1Row A , DMatrix1Row A_tran , final int blockLength ) { for ( int i = 0 ; i < A . numRows ; i += blockLength ) { int blockHeight = Math . min ( blockLength , A . numRows - i ) ; int indexSrc = i * A . numCols ; int indexDst = i ; for ( int j = 0 ; j < A . numCols ; j += blockLength ) { int blockWidth = Math . min ( blockLength , A . numCols - j ) ; // int indexSrc = i*A.numCols + j; // int indexDst = j*A_tran.numCols + i; int indexSrcEnd = indexSrc + blockWidth ; // for( int l = 0; l < blockWidth; l++ , indexSrc++ ) { for ( ; indexSrc < indexSrcEnd ; indexSrc ++ ) { int rowSrc = indexSrc ; int rowDst = indexDst ; int end = rowDst + blockHeight ; // for( int k = 0; k < blockHeight; k++ , rowSrc += A.numCols ) { for ( ; rowDst < end ; rowSrc += A . numCols ) { // faster to write in sequence than to read in sequence A_tran . data [ rowDst ++ ] = A . data [ rowSrc ] ; } indexDst += A_tran . numCols ; } } } }
Performs a transpose across block sub - matrices . Reduces the number of cache misses on larger matrices .
344
24
149,011
public static boolean isIdentity ( DMatrix a , double tol ) { for ( int i = 0 ; i < a . getNumRows ( ) ; i ++ ) { for ( int j = 0 ; j < a . getNumCols ( ) ; j ++ ) { if ( i == j ) { if ( Math . abs ( a . get ( i , j ) - 1.0 ) > tol ) return false ; } else { if ( Math . abs ( a . get ( i , j ) ) > tol ) return false ; } } } return true ; }
Returns true if the provided matrix is has a value of 1 along the diagonal elements and zero along all the other elements .
126
24
149,012
public static double computeHouseholder ( double [ ] x , int xStart , int xEnd , double max , DScalar gamma ) { double tau = 0 ; for ( int i = xStart ; i < xEnd ; i ++ ) { double val = x [ i ] /= max ; tau += val * val ; } tau = Math . sqrt ( tau ) ; if ( x [ xStart ] < 0 ) { tau = - tau ; } double u_0 = x [ xStart ] + tau ; gamma . value = u_0 / tau ; x [ xStart ] = 1 ; for ( int i = xStart + 1 ; i < xEnd ; i ++ ) { x [ i ] /= u_0 ; } return - tau * max ; }
Creates a householder reflection .
174
7
149,013
public static long get1D ( DMatrixRMaj A , int n ) { long before = System . currentTimeMillis ( ) ; double total = 0 ; for ( int iter = 0 ; iter < n ; iter ++ ) { int index = 0 ; for ( int i = 0 ; i < A . numRows ; i ++ ) { int end = index + A . numCols ; while ( index != end ) { total += A . get ( index ++ ) ; } } } long after = System . currentTimeMillis ( ) ; // print to ensure that ensure that an overly smart compiler does not optimize out // the whole function and to show that both produce the same results. System . out . println ( total ) ; return after - before ; }
Get by index is used here .
161
7
149,014
public static DMatrixRBlock initializeQ ( DMatrixRBlock Q , int numRows , int numCols , int blockLength , boolean compact ) { int minLength = Math . min ( numRows , numCols ) ; if ( compact ) { if ( Q == null ) { Q = new DMatrixRBlock ( numRows , minLength , blockLength ) ; MatrixOps_DDRB . setIdentity ( Q ) ; } else { if ( Q . numRows != numRows || Q . numCols != minLength ) { throw new IllegalArgumentException ( "Unexpected matrix dimension. Found " + Q . numRows + " " + Q . numCols ) ; } else { MatrixOps_DDRB . setIdentity ( Q ) ; } } } else { if ( Q == null ) { Q = new DMatrixRBlock ( numRows , numRows , blockLength ) ; MatrixOps_DDRB . setIdentity ( Q ) ; } else { if ( Q . numRows != numRows || Q . numCols != numRows ) { throw new IllegalArgumentException ( "Unexpected matrix dimension. Found " + Q . numRows + " " + Q . numCols ) ; } else { MatrixOps_DDRB . setIdentity ( Q ) ; } } } return Q ; }
Sanity checks the input or declares a new matrix . Return matrix is an identity matrix .
301
18
149,015
private void setup ( DMatrixRBlock orig ) { blockLength = orig . blockLength ; dataW . blockLength = blockLength ; dataWTA . blockLength = blockLength ; this . dataA = orig ; A . original = dataA ; int l = Math . min ( blockLength , orig . numCols ) ; dataW . reshape ( orig . numRows , l , false ) ; dataWTA . reshape ( l , orig . numRows , false ) ; Y . original = orig ; Y . row1 = W . row1 = orig . numRows ; if ( temp . length < blockLength ) temp = new double [ blockLength ] ; if ( gammas . length < orig . numCols ) gammas = new double [ orig . numCols ] ; if ( saveW ) { dataW . reshape ( orig . numRows , orig . numCols , false ) ; } }
Adjust submatrices and helper data structures for the input matrix . Must be called before the decomposition can be computed .
200
24
149,016
private void setW ( ) { if ( saveW ) { W . col0 = Y . col0 ; W . col1 = Y . col1 ; W . row0 = Y . row0 ; W . row1 = Y . row1 ; } else { W . col1 = Y . col1 - Y . col0 ; W . row0 = Y . row0 ; } }
Sets the submatrix of W up give Y is already configured and if it is being cached or not .
83
23
149,017
private void solveInternalL ( ) { // This takes advantage of the diagonal elements always being real numbers // solve L*y=b storing y in x TriangularSolver_ZDRM . solveL_diagReal ( t , vv , n ) ; // solve L^T*x=y TriangularSolver_ZDRM . solveConjTranL_diagReal ( t , vv , n ) ; }
Used internally to find the solution to a single column vector .
93
12
149,018
@ Override public void invert ( ZMatrixRMaj inv ) { if ( inv . numRows != n || inv . numCols != n ) { throw new RuntimeException ( "Unexpected matrix dimension" ) ; } if ( inv . data == t ) { throw new IllegalArgumentException ( "Passing in the same matrix that was decomposed." ) ; } if ( decomposer . isLower ( ) ) { setToInverseL ( inv . data ) ; } else { throw new RuntimeException ( "Implement" ) ; } }
Sets the matrix inv equal to the inverse of the matrix that was decomposed .
118
17
149,019
public void declareInternalData ( int maxRows , int maxCols ) { this . maxRows = maxRows ; this . maxCols = maxCols ; U_tran = new DMatrixRMaj ( maxRows , maxRows ) ; Qm = new DMatrixRMaj ( maxRows , maxRows ) ; r_row = new double [ maxCols ] ; }
Declares the internal data structures so that it can process matrices up to the specified size .
90
19
149,020
private void setQR ( DMatrixRMaj Q , DMatrixRMaj R , int growRows ) { if ( Q . numRows != Q . numCols ) { throw new IllegalArgumentException ( "Q should be square." ) ; } this . Q = Q ; this . R = R ; m = Q . numRows ; n = R . numCols ; if ( m + growRows > maxRows || n > maxCols ) { if ( autoGrow ) { declareInternalData ( m + growRows , n ) ; } else { throw new IllegalArgumentException ( "Autogrow has been set to false and the maximum number of rows" + " or columns has been exceeded." ) ; } } }
Provides the results of a QR decomposition . These will be modified by adding or removing rows from the original A matrix .
163
25
149,021
private void updateRemoveQ ( int rowIndex ) { Qm . set ( Q ) ; Q . reshape ( m_m , m_m , false ) ; for ( int i = 0 ; i < rowIndex ; i ++ ) { for ( int j = 1 ; j < m ; j ++ ) { double sum = 0 ; for ( int k = 0 ; k < m ; k ++ ) { sum += Qm . data [ i * m + k ] * U_tran . data [ j * m + k ] ; } Q . data [ i * m_m + j - 1 ] = sum ; } } for ( int i = rowIndex + 1 ; i < m ; i ++ ) { for ( int j = 1 ; j < m ; j ++ ) { double sum = 0 ; for ( int k = 0 ; k < m ; k ++ ) { sum += Qm . data [ i * m + k ] * U_tran . data [ j * m + k ] ; } Q . data [ ( i - 1 ) * m_m + j - 1 ] = sum ; } } }
Updates the Q matrix to take inaccount the row that was removed by only multiplying e lements that need to be . There is still some room for improvement here ...
240
34
149,022
private void updateRemoveR ( ) { for ( int i = 1 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { double sum = 0 ; for ( int k = i - 1 ; k <= j ; k ++ ) { sum += U_tran . data [ i * m + k ] * R . data [ k * n + j ] ; } R . data [ ( i - 1 ) * n + j ] = sum ; } } }
Updates the R matrix to take in account the removed row .
110
13
149,023
public static void normalizeF ( DMatrixRMaj A ) { double val = normF ( A ) ; if ( val == 0 ) return ; int size = A . getNumElements ( ) ; for ( int i = 0 ; i < size ; i ++ ) { A . div ( i , val ) ; } }
Normalizes the matrix such that the Frobenius norm is equal to one .
70
16
149,024
public static double normP ( DMatrixRMaj A , double p ) { if ( p == 1 ) { return normP1 ( A ) ; } else if ( p == 2 ) { return normP2 ( A ) ; } else if ( Double . isInfinite ( p ) ) { return normPInf ( A ) ; } if ( MatrixFeatures_DDRM . isVector ( A ) ) { return elementP ( A , p ) ; } else { throw new IllegalArgumentException ( "Doesn't support induced norms yet." ) ; } }
Computes either the vector p - norm or the induced matrix p - norm depending on A being a vector or a matrix respectively .
120
26
149,025
public static double normP1 ( DMatrixRMaj A ) { if ( MatrixFeatures_DDRM . isVector ( A ) ) { return CommonOps_DDRM . elementSumAbs ( A ) ; } else { return inducedP1 ( A ) ; } }
Computes the p = 1 norm . If A is a matrix then the induced norm is computed .
59
20
149,026
public static double normP2 ( DMatrixRMaj A ) { if ( MatrixFeatures_DDRM . isVector ( A ) ) { return normF ( A ) ; } else { return inducedP2 ( A ) ; } }
Computes the p = 2 norm . If A is a matrix then the induced norm is computed .
51
20
149,027
public static double fastNormP2 ( DMatrixRMaj A ) { if ( MatrixFeatures_DDRM . isVector ( A ) ) { return fastNormF ( A ) ; } else { return inducedP2 ( A ) ; } }
Computes the p = 2 norm . If A is a matrix then the induced norm is computed . This implementation is faster but more prone to buffer overflow or underflow problems .
53
35
149,028
protected List < String > extractWords ( ) throws IOException { while ( true ) { lineNumber ++ ; String line = in . readLine ( ) ; if ( line == null ) { return null ; } // skip comment lines if ( hasComment ) { if ( line . charAt ( 0 ) == comment ) continue ; } // extract the words, which are the variables encoded return parseWords ( line ) ; } }
Finds the next valid line of words in the stream and extracts them .
87
15
149,029
protected List < String > parseWords ( String line ) { List < String > words = new ArrayList < String > ( ) ; boolean insideWord = ! isSpace ( line . charAt ( 0 ) ) ; int last = 0 ; for ( int i = 0 ; i < line . length ( ) ; i ++ ) { char c = line . charAt ( i ) ; if ( insideWord ) { // see if its at the end of a word if ( isSpace ( c ) ) { words . add ( line . substring ( last , i ) ) ; insideWord = false ; } } else { if ( ! isSpace ( c ) ) { last = i ; insideWord = true ; } } } // if the line ended add the final word if ( insideWord ) { words . add ( line . substring ( last ) ) ; } return words ; }
Extracts the words from a string . Words are seperated by a space character .
183
19
149,030
public static double findMax ( double [ ] u , int startU , int length ) { double max = - 1 ; int index = startU * 2 ; int stopIndex = ( startU + length ) * 2 ; for ( ; index < stopIndex ; ) { double real = u [ index ++ ] ; double img = u [ index ++ ] ; double val = real * real + img * img ; if ( val > max ) { max = val ; } } return Math . sqrt ( max ) ; }
Returns the maximum magnitude of the complex numbers
108
8
149,031
public static void extractHouseholderColumn ( ZMatrixRMaj A , int row0 , int row1 , int col , double u [ ] , int offsetU ) { int indexU = ( row0 + offsetU ) * 2 ; u [ indexU ++ ] = 1 ; u [ indexU ++ ] = 0 ; for ( int row = row0 + 1 ; row < row1 ; row ++ ) { int indexA = A . getIndex ( row , col ) ; u [ indexU ++ ] = A . data [ indexA ] ; u [ indexU ++ ] = A . data [ indexA + 1 ] ; } }
Extracts a house holder vector from the column of A and stores it in u
134
17
149,032
public static void extractHouseholderRow ( ZMatrixRMaj A , int row , int col0 , int col1 , double u [ ] , int offsetU ) { int indexU = ( offsetU + col0 ) * 2 ; u [ indexU ] = 1 ; u [ indexU + 1 ] = 0 ; int indexA = ( row * A . numCols + ( col0 + 1 ) ) * 2 ; System . arraycopy ( A . data , indexA , u , indexU + 2 , ( col1 - col0 - 1 ) * 2 ) ; }
Extracts a house holder vector from the rows of A and stores it in u
123
17
149,033
public static double extractColumnAndMax ( ZMatrixRMaj A , int row0 , int row1 , int col , double u [ ] , int offsetU ) { int indexU = ( offsetU + row0 ) * 2 ; // find the largest value in this column // this is used to normalize the column and mitigate overflow/underflow double max = 0 ; int indexA = A . getIndex ( row0 , col ) ; double h [ ] = A . data ; for ( int i = row0 ; i < row1 ; i ++ , indexA += A . numCols * 2 ) { // copy the householder vector to an array to reduce cache misses // big improvement on larger matrices and a relatively small performance hit on small matrices. double realVal = u [ indexU ++ ] = h [ indexA ] ; double imagVal = u [ indexU ++ ] = h [ indexA + 1 ] ; double magVal = realVal * realVal + imagVal * imagVal ; if ( max < magVal ) { max = magVal ; } } return Math . sqrt ( max ) ; }
Extracts the column of A and copies it into u while computing the magnitude of the largest element and returning it .
237
24
149,034
public static double computeRowMax ( ZMatrixRMaj A , int row , int col0 , int col1 ) { double max = 0 ; int indexA = A . getIndex ( row , col0 ) ; double h [ ] = A . data ; for ( int i = col0 ; i < col1 ; i ++ ) { double realVal = h [ indexA ++ ] ; double imagVal = h [ indexA ++ ] ; double magVal = realVal * realVal + imagVal * imagVal ; if ( max < magVal ) { max = magVal ; } } return Math . sqrt ( max ) ; }
Finds the magnitude of the largest element in the row
134
11
149,035
public static ZMatrixRMaj hermitian ( int length , double min , double max , Random rand ) { ZMatrixRMaj A = new ZMatrixRMaj ( length , length ) ; fillHermitian ( A , min , max , rand ) ; return A ; }
Creates a random Hermitian matrix with elements from min to max value .
58
16
149,036
public static void fillHermitian ( ZMatrixRMaj A , double min , double max , Random rand ) { if ( A . numRows != A . numCols ) throw new IllegalArgumentException ( "A must be a square matrix" ) ; double range = max - min ; int length = A . numRows ; for ( int i = 0 ; i < length ; i ++ ) { A . set ( i , i , rand . nextDouble ( ) * range + min , 0 ) ; for ( int j = i + 1 ; j < length ; j ++ ) { double real = rand . nextDouble ( ) * range + min ; double imaginary = rand . nextDouble ( ) * range + min ; A . set ( i , j , real , imaginary ) ; A . set ( j , i , real , - imaginary ) ; } } }
Assigns the provided square matrix to be a random Hermitian matrix with elements from min to max value .
183
23
149,037
public static SimpleMatrix wrap ( Matrix internalMat ) { SimpleMatrix ret = new SimpleMatrix ( ) ; ret . setMatrix ( internalMat ) ; return ret ; }
Creates a new SimpleMatrix with the specified DMatrixRMaj used as its internal matrix . This means that the reference is saved and calls made to the returned SimpleMatrix will modify the passed in DMatrixRMaj .
34
46
149,038
public static SimpleMatrix diag ( Class type , double ... vals ) { SimpleMatrix M = new SimpleMatrix ( vals . length , vals . length , type ) ; for ( int i = 0 ; i < vals . length ; i ++ ) { M . set ( i , i , vals [ i ] ) ; } return M ; }
Creates a real valued diagonal matrix of the specified type
75
11
149,039
public static void convert ( DMatrixD1 input , ZMatrixD1 output ) { if ( input . numCols != output . numCols || input . numRows != output . numRows ) { throw new IllegalArgumentException ( "The matrices are not all the same dimension." ) ; } Arrays . fill ( output . data , 0 , output . getDataLength ( ) , 0 ) ; final int length = output . getDataLength ( ) ; for ( int i = 0 ; i < length ; i += 2 ) { output . data [ i ] = input . data [ i / 2 ] ; } }
Converts the real matrix into a complex matrix .
135
10
149,040
public static DMatrixRMaj stripReal ( ZMatrixD1 input , DMatrixRMaj output ) { if ( output == null ) { output = new DMatrixRMaj ( input . numRows , input . numCols ) ; } else if ( input . numCols != output . numCols || input . numRows != output . numRows ) { throw new IllegalArgumentException ( "The matrices are not all the same dimension." ) ; } final int length = input . getDataLength ( ) ; for ( int i = 0 ; i < length ; i += 2 ) { output . data [ i / 2 ] = input . data [ i ] ; } return output ; }
Places the real component of the input matrix into the output matrix .
152
14
149,041
public static DMatrixRMaj convert ( DMatrixRBlock src , DMatrixRMaj dst ) { return ConvertDMatrixStruct . convert ( src , dst ) ; }
Converts a row major block matrix into a row major matrix .
38
13
149,042
public static void convertTranSrc ( DMatrixRMaj src , DMatrixRBlock dst ) { if ( src . numRows != dst . numCols || src . numCols != dst . numRows ) throw new IllegalArgumentException ( "Incompatible matrix shapes." ) ; for ( int i = 0 ; i < dst . numRows ; i += dst . blockLength ) { int blockHeight = Math . min ( dst . blockLength , dst . numRows - i ) ; for ( int j = 0 ; j < dst . numCols ; j += dst . blockLength ) { int blockWidth = Math . min ( dst . blockLength , dst . numCols - j ) ; int indexDst = i * dst . numCols + blockHeight * j ; int indexSrc = j * src . numCols + i ; for ( int l = 0 ; l < blockWidth ; l ++ ) { int rowSrc = indexSrc + l * src . numCols ; int rowDst = indexDst + l ; for ( int k = 0 ; k < blockHeight ; k ++ , rowDst += blockWidth ) { dst . data [ rowDst ] = src . data [ rowSrc ++ ] ; } } } } }
Converts the transpose of a row major matrix into a row major block matrix .
279
17
149,043
public static DMatrixRBlock transpose ( DMatrixRBlock A , DMatrixRBlock A_tran ) { if ( A_tran != null ) { if ( A . numRows != A_tran . numCols || A . numCols != A_tran . numRows ) throw new IllegalArgumentException ( "Incompatible dimensions." ) ; if ( A . blockLength != A_tran . blockLength ) throw new IllegalArgumentException ( "Incompatible block size." ) ; } else { A_tran = new DMatrixRBlock ( A . numCols , A . numRows , A . blockLength ) ; } for ( int i = 0 ; i < A . numRows ; i += A . blockLength ) { int blockHeight = Math . min ( A . blockLength , A . numRows - i ) ; for ( int j = 0 ; j < A . numCols ; j += A . blockLength ) { int blockWidth = Math . min ( A . blockLength , A . numCols - j ) ; int indexA = i * A . numCols + blockHeight * j ; int indexC = j * A_tran . numCols + blockWidth * i ; transposeBlock ( A , A_tran , indexA , indexC , blockWidth , blockHeight ) ; } } return A_tran ; }
Transposes a block matrix .
308
6
149,044
private static void transposeBlock ( DMatrixRBlock A , DMatrixRBlock A_tran , int indexA , int indexC , int width , int height ) { for ( int i = 0 ; i < height ; i ++ ) { int rowIndexC = indexC + i ; int rowIndexA = indexA + width * i ; int end = rowIndexA + width ; for ( ; rowIndexA < end ; rowIndexC += height , rowIndexA ++ ) { A_tran . data [ rowIndexC ] = A . data [ rowIndexA ] ; } } }
Transposes an individual block inside a block matrix .
130
10
149,045
public static void zeroTriangle ( boolean upper , DMatrixRBlock A ) { int blockLength = A . blockLength ; if ( upper ) { for ( int i = 0 ; i < A . numRows ; i += blockLength ) { int h = Math . min ( blockLength , A . numRows - i ) ; for ( int j = i ; j < A . numCols ; j += blockLength ) { int w = Math . min ( blockLength , A . numCols - j ) ; int index = i * A . numCols + h * j ; if ( j == i ) { for ( int k = 0 ; k < h ; k ++ ) { for ( int l = k + 1 ; l < w ; l ++ ) { A . data [ index + w * k + l ] = 0 ; } } } else { for ( int k = 0 ; k < h ; k ++ ) { for ( int l = 0 ; l < w ; l ++ ) { A . data [ index + w * k + l ] = 0 ; } } } } } } else { for ( int i = 0 ; i < A . numRows ; i += blockLength ) { int h = Math . min ( blockLength , A . numRows - i ) ; for ( int j = 0 ; j <= i ; j += blockLength ) { int w = Math . min ( blockLength , A . numCols - j ) ; int index = i * A . numCols + h * j ; if ( j == i ) { for ( int k = 0 ; k < h ; k ++ ) { int z = Math . min ( k , w ) ; for ( int l = 0 ; l < z ; l ++ ) { A . data [ index + w * k + l ] = 0 ; } } } else { for ( int k = 0 ; k < h ; k ++ ) { for ( int l = 0 ; l < w ; l ++ ) { A . data [ index + w * k + l ] = 0 ; } } } } } } }
Sets either the upper or low triangle of a matrix to zero
451
13
149,046
public static boolean blockAligned ( int blockLength , DSubmatrixD1 A ) { if ( A . col0 % blockLength != 0 ) return false ; if ( A . row0 % blockLength != 0 ) return false ; if ( A . col1 % blockLength != 0 && A . col1 != A . original . numCols ) { return false ; } if ( A . row1 % blockLength != 0 && A . row1 != A . original . numRows ) { return false ; } return true ; }
Checks to see if the submatrix has its boundaries along inner blocks .
114
16
149,047
private void makeSingularPositive ( ) { numSingular = qralg . getNumberOfSingularValues ( ) ; singularValues = qralg . getSingularValues ( ) ; for ( int i = 0 ; i < numSingular ; i ++ ) { double val = singularValues [ i ] ; if ( val < 0 ) { singularValues [ i ] = - val ; if ( computeU ) { // compute the results of multiplying it by an element of -1 at this location in // a diagonal matrix. int start = i * Ut . numCols ; int stop = start + Ut . numCols ; for ( int j = start ; j < stop ; j ++ ) { Ut . data [ j ] = - Ut . data [ j ] ; } } } } }
With the QR algorithm it is possible for the found singular values to be native . This makes them all positive by multiplying it by a diagonal matrix that has
168
30
149,048
public void fit ( double samplePoints [ ] , double [ ] observations ) { // Create a copy of the observations and put it into a matrix y . reshape ( observations . length , 1 , false ) ; System . arraycopy ( observations , 0 , y . data , 0 , observations . length ) ; // reshape the matrix to avoid unnecessarily declaring new memory // save values is set to false since its old values don't matter A . reshape ( y . numRows , coef . numRows , false ) ; // set up the A matrix for ( int i = 0 ; i < observations . length ; i ++ ) { double obs = 1 ; for ( int j = 0 ; j < coef . numRows ; j ++ ) { A . set ( i , j , obs ) ; obs *= samplePoints [ i ] ; } } // process the A matrix and see if it failed if ( ! solver . setA ( A ) ) throw new RuntimeException ( "Solver failed" ) ; // solver the the coefficients solver . solve ( y , coef ) ; }
Computes the best fit set of polynomial coefficients to the provided observations .
231
16
149,049
public void removeWorstFit ( ) { // find the observation with the most error int worstIndex = - 1 ; double worstError = - 1 ; for ( int i = 0 ; i < y . numRows ; i ++ ) { double predictedObs = 0 ; for ( int j = 0 ; j < coef . numRows ; j ++ ) { predictedObs += A . get ( i , j ) * coef . get ( j , 0 ) ; } double error = Math . abs ( predictedObs - y . get ( i , 0 ) ) ; if ( error > worstError ) { worstError = error ; worstIndex = i ; } } // nothing left to remove, so just return if ( worstIndex == - 1 ) return ; // remove that observation removeObservation ( worstIndex ) ; // update A solver . removeRowFromA ( worstIndex ) ; // solve for the parameters again solver . solve ( y , coef ) ; }
Removes the observation that fits the model the worst and recomputes the coefficients . This is done efficiently by using an adjustable solver . Often times the elements with the largest errors are outliers and not part of the system being modeled . By removing them a more accurate set of coefficients can be computed .
203
60
149,050
private void removeObservation ( int index ) { final int N = y . numRows - 1 ; final double d [ ] = y . data ; // shift for ( int i = index ; i < N ; i ++ ) { d [ i ] = d [ i + 1 ] ; } y . numRows -- ; }
Removes an element from the observation matrix .
70
9
149,051
public static ZMatrixRMaj householderVector ( ZMatrixRMaj x ) { ZMatrixRMaj u = x . copy ( ) ; double max = CommonOps_ZDRM . elementMaxAbs ( u ) ; CommonOps_ZDRM . elementDivide ( u , max , 0 , u ) ; double nx = NormOps_ZDRM . normF ( u ) ; Complex_F64 c = new Complex_F64 ( ) ; u . get ( 0 , 0 , c ) ; double realTau , imagTau ; if ( c . getMagnitude ( ) == 0 ) { realTau = nx ; imagTau = 0 ; } else { realTau = c . real / c . getMagnitude ( ) * nx ; imagTau = c . imaginary / c . getMagnitude ( ) * nx ; } u . set ( 0 , 0 , c . real + realTau , c . imaginary + imagTau ) ; CommonOps_ZDRM . elementDivide ( u , u . getReal ( 0 , 0 ) , u . getImag ( 0 , 0 ) , u ) ; return u ; }
Computes the householder vector used in QR decomposition .
251
12
149,052
@ Override public boolean decompose ( ZMatrixRMaj A ) { if ( A . numRows != A . numCols ) throw new IllegalArgumentException ( "A must be square." ) ; if ( A . numRows <= 0 ) return false ; QH = A ; N = A . numCols ; if ( b . length < N * 2 ) { b = new double [ N * 2 ] ; gammas = new double [ N ] ; u = new double [ N * 2 ] ; } return _decompose ( ) ; }
Computes the decomposition of the provided matrix . If no errors are detected then true is returned false otherwise .
120
22
149,053
@ Override public DMatrixRMaj getA ( ) { if ( A . data . length < numRows * numCols ) { A = new DMatrixRMaj ( numRows , numCols ) ; } A . reshape ( numRows , numCols , false ) ; CommonOps_DDRM . mult ( Q , R , A ) ; return A ; }
Compute the A matrix from the Q and R matrices .
86
13
149,054
public void set ( T a ) { if ( a . getType ( ) == getType ( ) ) mat . set ( a . getMatrix ( ) ) ; else { setMatrix ( a . mat . copy ( ) ) ; } }
Sets the elements in this matrix to be equal to the elements in the passed in matrix . Both matrix must have the same dimension .
50
27
149,055
public void set ( int row , int col , double value ) { ops . set ( mat , row , col , value ) ; }
Assigns the element in the Matrix to the specified value . Performs a bounds check to make sure the requested element is part of the matrix .
28
30
149,056
public void set ( int index , double value ) { if ( mat . getType ( ) == MatrixType . DDRM ) { ( ( DMatrixRMaj ) mat ) . set ( index , value ) ; } else if ( mat . getType ( ) == MatrixType . FDRM ) { ( ( FMatrixRMaj ) mat ) . set ( index , ( float ) value ) ; } else { throw new RuntimeException ( "Not supported yet for this matrix type" ) ; } }
Assigns an element a value based on its index in the internal array ..
105
16
149,057
public void set ( int row , int col , double real , double imaginary ) { if ( imaginary == 0 ) { set ( row , col , real ) ; } else { ops . set ( mat , row , col , real , imaginary ) ; } }
Used to set the complex value of a matrix element .
53
11
149,058
public double get ( int index ) { MatrixType type = mat . getType ( ) ; if ( type . isReal ( ) ) { if ( type . getBits ( ) == 64 ) { return ( ( DMatrixRMaj ) mat ) . data [ index ] ; } else { return ( ( FMatrixRMaj ) mat ) . data [ index ] ; } } else { throw new IllegalArgumentException ( "Complex matrix. Call get(int,Complex64F) instead" ) ; } }
Returns the value of the matrix at the specified index of the 1D row major array .
111
18
149,059
public void get ( int row , int col , Complex_F64 output ) { ops . get ( mat , row , col , output ) ; }
Used to get the complex value of a matrix element .
31
11
149,060
public T copy ( ) { T ret = createLike ( ) ; ret . getMatrix ( ) . set ( this . getMatrix ( ) ) ; return ret ; }
Creates and returns a matrix which is idential to this one .
35
14
149,061
public boolean isIdentical ( T a , double tol ) { if ( a . getType ( ) != getType ( ) ) return false ; return ops . isIdentical ( mat , a . mat , tol ) ; }
Checks to see if matrix a is the same as this matrix within the specified tolerance .
49
18
149,062
public boolean isInBounds ( int row , int col ) { return row >= 0 && col >= 0 && row < mat . getNumRows ( ) && col < mat . getNumCols ( ) ; }
Returns true of the specified matrix element is valid element inside this matrix .
46
14
149,063
public void convertToSparse ( ) { switch ( mat . getType ( ) ) { case DDRM : { DMatrixSparseCSC m = new DMatrixSparseCSC ( mat . getNumRows ( ) , mat . getNumCols ( ) ) ; ConvertDMatrixStruct . convert ( ( DMatrixRMaj ) mat , m , 0 ) ; setMatrix ( m ) ; } break ; case FDRM : { FMatrixSparseCSC m = new FMatrixSparseCSC ( mat . getNumRows ( ) , mat . getNumCols ( ) ) ; ConvertFMatrixStruct . convert ( ( FMatrixRMaj ) mat , m , 0 ) ; setMatrix ( m ) ; } break ; case DSCC : case FSCC : break ; default : throw new RuntimeException ( "Conversion not supported!" ) ; } }
Switches from a dense to sparse matrix
190
8
149,064
public void convertToDense ( ) { switch ( mat . getType ( ) ) { case DSCC : { DMatrix m = new DMatrixRMaj ( mat . getNumRows ( ) , mat . getNumCols ( ) ) ; ConvertDMatrixStruct . convert ( ( DMatrix ) mat , m ) ; setMatrix ( m ) ; } break ; case FSCC : { FMatrix m = new FMatrixRMaj ( mat . getNumRows ( ) , mat . getNumCols ( ) ) ; ConvertFMatrixStruct . convert ( ( FMatrix ) mat , m ) ; setMatrix ( m ) ; } break ; case DDRM : case FDRM : case ZDRM : case CDRM : break ; default : throw new RuntimeException ( "Not a sparse matrix!" ) ; } }
Switches from a sparse to dense matrix
179
8
149,065
private static void multBlockAdd ( double [ ] blockA , double [ ] blockB , double [ ] blockC , final int m , final int n , final int o , final int blockLength ) { // for( int i = 0; i < m; i++ ) { // for( int j = 0; j < o; j++ ) { // double val = 0; // for( int k = 0; k < n; k++ ) { // val += blockA[ i*blockLength + k]*blockB[ k*blockLength + j]; // } // // blockC[ i*blockLength + j] += val; // } // } // int rowA = 0; // for( int i = 0; i < m; i++ , rowA += blockLength) { // for( int j = 0; j < o; j++ ) { // double val = 0; // int indexB = j; // int indexA = rowA; // int end = indexA + n; // for( ; indexA != end; indexA++ , indexB += blockLength ) { // val += blockA[ indexA ]*blockB[ indexB ]; // } // // blockC[ rowA + j] += val; // } // } // for( int k = 0; k < n; k++ ) { // for( int i = 0; i < m; i++ ) { // for( int j = 0; j < o; j++ ) { // blockC[ i*blockLength + j] += blockA[ i*blockLength + k]*blockB[ k*blockLength + j]; // } // } // } for ( int k = 0 ; k < n ; k ++ ) { int rowB = k * blockLength ; int endB = rowB + o ; for ( int i = 0 ; i < m ; i ++ ) { int indexC = i * blockLength ; double valA = blockA [ indexC + k ] ; int indexB = rowB ; while ( indexB != endB ) { blockC [ indexC ++ ] += valA * blockB [ indexB ++ ] ; } } } }
Performs a matrix multiplication between inner block matrices .
468
11
149,066
public void _solveVectorInternal ( double [ ] vv ) { // Solve L*Y = B int ii = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int ip = indx [ i ] ; double sum = vv [ ip ] ; vv [ ip ] = vv [ i ] ; if ( ii != 0 ) { // for( int j = ii-1; j < i; j++ ) // sum -= dataLU[i* n +j]*vv[j]; int index = i * n + ii - 1 ; for ( int j = ii - 1 ; j < i ; j ++ ) sum -= dataLU [ index ++ ] * vv [ j ] ; } else if ( sum != 0.0 ) { ii = i + 1 ; } vv [ i ] = sum ; } // Solve U*X = Y; TriangularSolver_DDRM . solveU ( dataLU , vv , n ) ; }
a specialized version of solve that avoid additional checks that are not needed .
214
14
149,067
protected void resize ( VariableMatrix mat , int numRows , int numCols ) { if ( mat . isTemp ( ) ) { mat . matrix . reshape ( numRows , numCols ) ; } }
If the variable is a local temporary variable it will be resized so that the operation can complete . If not temporary then it will not be reshaped
47
30
149,068
public static Info neg ( final Variable A , ManagerTempVariables manager ) { Info ret = new Info ( ) ; if ( A instanceof VariableInteger ) { final VariableInteger output = manager . createInteger ( ) ; ret . output = output ; ret . op = new Operation ( "neg-i" ) { @ Override public void process ( ) { output . value = - ( ( VariableInteger ) A ) . value ; } } ; } else if ( A instanceof VariableScalar ) { final VariableDouble output = manager . createDouble ( ) ; ret . output = output ; ret . op = new Operation ( "neg-s" ) { @ Override public void process ( ) { output . value = - ( ( VariableScalar ) A ) . getDouble ( ) ; } } ; } else if ( A instanceof VariableMatrix ) { final VariableMatrix output = manager . createMatrix ( ) ; ret . output = output ; ret . op = new Operation ( "neg-m" ) { @ Override public void process ( ) { DMatrixRMaj a = ( ( VariableMatrix ) A ) . matrix ; output . matrix . reshape ( a . numRows , a . numCols ) ; CommonOps_DDRM . changeSign ( a , output . matrix ) ; } } ; } else { throw new RuntimeException ( "Unsupported variable " + A ) ; } return ret ; }
Returns the negative of the input variable
300
7
149,069
public static Info eye ( final Variable A , ManagerTempVariables manager ) { Info ret = new Info ( ) ; final VariableMatrix output = manager . createMatrix ( ) ; ret . output = output ; if ( A instanceof VariableMatrix ) { ret . op = new Operation ( "eye-m" ) { @ Override public void process ( ) { DMatrixRMaj mA = ( ( VariableMatrix ) A ) . matrix ; output . matrix . reshape ( mA . numRows , mA . numCols ) ; CommonOps_DDRM . setIdentity ( output . matrix ) ; } } ; } else if ( A instanceof VariableInteger ) { ret . op = new Operation ( "eye-i" ) { @ Override public void process ( ) { int N = ( ( VariableInteger ) A ) . value ; output . matrix . reshape ( N , N ) ; CommonOps_DDRM . setIdentity ( output . matrix ) ; } } ; } else { throw new RuntimeException ( "Unsupported variable type " + A ) ; } return ret ; }
Returns an identity matrix
234
4
149,070
public static Info ones ( final Variable A , final Variable B , ManagerTempVariables manager ) { Info ret = new Info ( ) ; final VariableMatrix output = manager . createMatrix ( ) ; ret . output = output ; if ( A instanceof VariableInteger && B instanceof VariableInteger ) { ret . op = new Operation ( "ones-ii" ) { @ Override public void process ( ) { int numRows = ( ( VariableInteger ) A ) . value ; int numCols = ( ( VariableInteger ) B ) . value ; output . matrix . reshape ( numRows , numCols ) ; CommonOps_DDRM . fill ( output . matrix , 1 ) ; } } ; } else { throw new RuntimeException ( "Expected two integers got " + A + " " + B ) ; } return ret ; }
Returns a matrix full of ones
178
6
149,071
public static Info rng ( final Variable A , ManagerTempVariables manager ) { Info ret = new Info ( ) ; if ( A instanceof VariableInteger ) { ret . op = new Operation ( "rng" ) { @ Override public void process ( ) { int seed = ( ( VariableInteger ) A ) . value ; manager . getRandom ( ) . setSeed ( seed ) ; } } ; } else { throw new RuntimeException ( "Expected one integer" ) ; } return ret ; }
Sets the seed for random number generator
107
8
149,072
public static Info rand ( final Variable A , final Variable B , ManagerTempVariables manager ) { Info ret = new Info ( ) ; final VariableMatrix output = manager . createMatrix ( ) ; ret . output = output ; if ( A instanceof VariableInteger && B instanceof VariableInteger ) { ret . op = new Operation ( "rand-ii" ) { @ Override public void process ( ) { int numRows = ( ( VariableInteger ) A ) . value ; int numCols = ( ( VariableInteger ) B ) . value ; output . matrix . reshape ( numRows , numCols ) ; RandomMatrices_DDRM . fillUniform ( output . matrix , 0 , 1 , manager . getRandom ( ) ) ; } } ; } else { throw new RuntimeException ( "Expected two integers got " + A + " " + B ) ; } return ret ; }
Uniformly random numbers
190
5
149,073
private static boolean extractSimpleExtents ( Variable var , Extents e , boolean row , int length ) { int lower ; int upper ; if ( var . getType ( ) == VariableType . INTEGER_SEQUENCE ) { IntegerSequence sequence = ( ( VariableIntegerSequence ) var ) . sequence ; if ( sequence . getType ( ) == IntegerSequence . Type . FOR ) { IntegerSequence . For seqFor = ( IntegerSequence . For ) sequence ; seqFor . initialize ( length ) ; if ( seqFor . getStep ( ) == 1 ) { lower = seqFor . getStart ( ) ; upper = seqFor . getEnd ( ) ; } else { return false ; } } else { return false ; } } else if ( var . getType ( ) == VariableType . SCALAR ) { lower = upper = ( ( VariableInteger ) var ) . value ; } else { throw new RuntimeException ( "How did a bad variable get put here?!?!" ) ; } if ( row ) { e . row0 = lower ; e . row1 = upper ; } else { e . col0 = lower ; e . col1 = upper ; } return true ; }
See if a simple sequence can be used to extract the array . A simple extent is a continuous block from a min to max index
252
26
149,074
public Token add ( Function function ) { Token t = new Token ( function ) ; push ( t ) ; return t ; }
Adds a function to the end of the token list
26
10
149,075
public Token add ( Variable variable ) { Token t = new Token ( variable ) ; push ( t ) ; return t ; }
Adds a variable to the end of the token list
26
10
149,076
public Token add ( Symbol symbol ) { Token t = new Token ( symbol ) ; push ( t ) ; return t ; }
Adds a symbol to the end of the token list
26
10
149,077
public Token add ( String word ) { Token t = new Token ( word ) ; push ( t ) ; return t ; }
Adds a word to the end of the token list
26
10
149,078
public void push ( Token token ) { size ++ ; if ( first == null ) { first = token ; last = token ; token . previous = null ; token . next = null ; } else { last . next = token ; token . previous = last ; token . next = null ; last = token ; } }
Adds a new Token to the end of the linked list
65
11
149,079
public void insert ( Token where , Token token ) { if ( where == null ) { // put at the front of the list if ( size == 0 ) push ( token ) ; else { first . previous = token ; token . previous = null ; token . next = first ; first = token ; size ++ ; } } else if ( where == last || null == last ) { push ( token ) ; } else { token . next = where . next ; token . previous = where ; where . next . previous = token ; where . next = token ; size ++ ; } }
Inserts token after where . if where is null then it is inserted to the beginning of the list .
119
21
149,080
public void remove ( Token token ) { if ( token == first ) { first = first . next ; } if ( token == last ) { last = last . previous ; } if ( token . next != null ) { token . next . previous = token . previous ; } if ( token . previous != null ) { token . previous . next = token . next ; } token . next = token . previous = null ; size -- ; }
Removes the token from the list
90
7
149,081
public void replace ( Token original , Token target ) { if ( first == original ) first = target ; if ( last == original ) last = target ; target . next = original . next ; target . previous = original . previous ; if ( original . next != null ) original . next . previous = target ; if ( original . previous != null ) original . previous . next = target ; original . next = original . previous = null ; }
Removes original and places target at the same location
90
10
149,082
public TokenList extractSubList ( Token begin , Token end ) { if ( begin == end ) { remove ( begin ) ; return new TokenList ( begin , begin ) ; } else { if ( first == begin ) { first = end . next ; } if ( last == end ) { last = begin . previous ; } if ( begin . previous != null ) { begin . previous . next = end . next ; } if ( end . next != null ) { end . next . previous = begin . previous ; } begin . previous = null ; end . next = null ; TokenList ret = new TokenList ( begin , end ) ; size -= ret . size ( ) ; return ret ; } }
Removes elements from begin to end from the list inclusive . Returns a new list which is composed of the removed elements
145
23
149,083
public void insertAfter ( Token before , TokenList list ) { Token after = before . next ; before . next = list . first ; list . first . previous = before ; if ( after == null ) { last = list . last ; } else { after . previous = list . last ; list . last . next = after ; } size += list . size ; }
Inserts the LokenList immediately following the before token
76
11
149,084
public static int isValid ( DMatrixRMaj cov ) { if ( ! MatrixFeatures_DDRM . isDiagonalPositive ( cov ) ) return 1 ; if ( ! MatrixFeatures_DDRM . isSymmetric ( cov , TOL ) ) return 2 ; if ( ! MatrixFeatures_DDRM . isPositiveSemidefinite ( cov ) ) return 3 ; return 0 ; }
Performs a variety of tests to see if the provided matrix is a valid covariance matrix .
88
19
149,085
public static boolean invert ( final DMatrixRMaj cov , final DMatrixRMaj cov_inv ) { if ( cov . numCols <= 4 ) { if ( cov . numCols != cov . numRows ) { throw new IllegalArgumentException ( "Must be a square matrix." ) ; } if ( cov . numCols >= 2 ) UnrolledInverseFromMinor_DDRM . inv ( cov , cov_inv ) ; else cov_inv . data [ 0 ] = 1.0 / cov . data [ 0 ] ; } else { LinearSolverDense < DMatrixRMaj > solver = LinearSolverFactory_DDRM . symmPosDef ( cov . numRows ) ; // wrap it to make sure the covariance is not modified. solver = new LinearSolverSafe < DMatrixRMaj > ( solver ) ; if ( ! solver . setA ( cov ) ) return false ; solver . invert ( cov_inv ) ; } return true ; }
Performs a matrix inversion operations that takes advantage of the special properties of a covariance matrix .
221
20
149,086
public int sum ( ) { int total = 0 ; int N = getNumElements ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( data [ i ] ) total += 1 ; } return total ; }
Returns the total number of elements which are true .
52
10
149,087
protected void init ( DMatrixRMaj A ) { UBV = A ; m = UBV . numRows ; n = UBV . numCols ; min = Math . min ( m , n ) ; int max = Math . max ( m , n ) ; if ( b . length < max + 1 ) { b = new double [ max + 1 ] ; u = new double [ max + 1 ] ; } if ( gammasU . length < m ) { gammasU = new double [ m ] ; } if ( gammasV . length < n ) { gammasV = new double [ n ] ; } }
Sets up internal data structures and creates a copy of the input matrix .
138
15
149,088
@ Override public DMatrixRMaj getU ( DMatrixRMaj U , boolean transpose , boolean compact ) { U = handleU ( U , transpose , compact , m , n , min ) ; CommonOps_DDRM . setIdentity ( U ) ; for ( int i = 0 ; i < m ; i ++ ) u [ i ] = 0 ; for ( int j = min - 1 ; j >= 0 ; j -- ) { u [ j ] = 1 ; for ( int i = j + 1 ; i < m ; i ++ ) { u [ i ] = UBV . get ( i , j ) ; } if ( transpose ) QrHelperFunctions_DDRM . rank1UpdateMultL ( U , u , gammasU [ j ] , j , j , m ) ; else QrHelperFunctions_DDRM . rank1UpdateMultR ( U , u , gammasU [ j ] , j , j , m , this . b ) ; } return U ; }
Returns the orthogonal U matrix .
222
8
149,089
@ Override public DMatrixRMaj getV ( DMatrixRMaj V , boolean transpose , boolean compact ) { V = handleV ( V , transpose , compact , m , n , min ) ; CommonOps_DDRM . setIdentity ( V ) ; // UBV.print(); // todo the very first multiplication can be avoided by setting to the rank1update output for ( int j = min - 1 ; j >= 0 ; j -- ) { u [ j + 1 ] = 1 ; for ( int i = j + 2 ; i < n ; i ++ ) { u [ i ] = UBV . get ( j , i ) ; } if ( transpose ) QrHelperFunctions_DDRM . rank1UpdateMultL ( V , u , gammasV [ j ] , j + 1 , j + 1 , n ) ; else QrHelperFunctions_DDRM . rank1UpdateMultR ( V , u , gammasV [ j ] , j + 1 , j + 1 , n , this . b ) ; } return V ; }
Returns the orthogonal V matrix .
236
8
149,090
public static < S extends Matrix , D extends Matrix > LinearSolver < S , D > safe ( LinearSolver < S , D > solver ) { if ( solver . modifiesA ( ) || solver . modifiesB ( ) ) { if ( solver instanceof LinearSolverDense ) { return new LinearSolverSafe ( ( LinearSolverDense ) solver ) ; } else if ( solver instanceof LinearSolverSparse ) { return new LinearSolverSparseSafe ( ( LinearSolverSparse ) solver ) ; } else { throw new IllegalArgumentException ( "Unknown solver type" ) ; } } else { return solver ; } }
Wraps a linear solver of any type with a safe solver the ensures inputs are not modified
148
20
149,091
public static String fancyStringF ( double value , DecimalFormat format , int length , int significant ) { String formatted = fancyString ( value , format , length , significant ) ; int n = length - formatted . length ( ) ; if ( n > 0 ) { StringBuilder builder = new StringBuilder ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { builder . append ( ' ' ) ; } return formatted + builder . toString ( ) ; } else { return formatted ; } }
Fixed length fancy formatting for doubles . If possible decimal notation is used . If all the significant digits can t be shown then it will switch to exponential notation . If not all the space is needed then it will be filled in to ensure it has the specified length .
108
52
149,092
private void performDynamicStep ( ) { // initially look for singular values of zero if ( findingZeros ) { if ( steps > 6 ) { findingZeros = false ; } else { double scale = computeBulgeScale ( ) ; performImplicitSingleStep ( scale , 0 , false ) ; } } else { // For very large and very small numbers the only way to prevent overflow/underflow // is to have a common scale between the wilkinson shift and the implicit single step // What happens if you don't is that when the wilkinson shift returns the value it // computed it multiplies it by the scale twice, which will cause an overflow double scale = computeBulgeScale ( ) ; // use the wilkinson shift to perform a step double lambda = selectWilkinsonShift ( scale ) ; performImplicitSingleStep ( scale , lambda , false ) ; } }
Here the lambda in the implicit step is determined dynamically . At first it selects zeros to quickly reveal singular values that are zero or close to zero . Then it computes it using a Wilkinson shift .
180
40
149,093
private void performScriptedStep ( ) { double scale = computeBulgeScale ( ) ; if ( steps > giveUpOnKnown ) { // give up on the script followScript = false ; } else { // use previous singular value to step double s = values [ x2 ] / scale ; performImplicitSingleStep ( scale , s * s , false ) ; } }
Shifts are performed based upon singular values computed previously . If it does not converge using one of those singular values it uses a Wilkinson shift instead .
78
29
149,094
public boolean nextSplit ( ) { if ( numSplits == 0 ) return false ; x2 = splits [ -- numSplits ] ; if ( numSplits > 0 ) x1 = splits [ numSplits - 1 ] + 1 ; else x1 = 0 ; return true ; }
Tells it to process the submatrix at the next split . Should be called after the current submatrix has been processed .
61
27
149,095
public void performImplicitSingleStep ( double scale , double lambda , boolean byAngle ) { createBulge ( x1 , lambda , scale , byAngle ) ; for ( int i = x1 ; i < x2 - 1 && bulge != 0.0 ; i ++ ) { removeBulgeLeft ( i , true ) ; if ( bulge == 0 ) break ; removeBulgeRight ( i ) ; } if ( bulge != 0 ) removeBulgeLeft ( x2 - 1 , false ) ; incrementSteps ( ) ; }
Given the lambda value perform an implicit QR step on the matrix .
117
13
149,096
protected void updateRotator ( DMatrixRMaj Q , int m , int n , double c , double s ) { int rowA = m * Q . numCols ; int rowB = n * Q . numCols ; // for( int i = 0; i < Q.numCols; i++ ) { // double a = Q.get(rowA+i); // double b = Q.get(rowB+i); // Q.set( rowA+i, c*a + s*b); // Q.set( rowB+i, -s*a + c*b); // } // System.out.println("------ AFter Update Rotator "+m+" "+n); // Q.print(); // System.out.println(); int endA = rowA + Q . numCols ; for ( ; rowA != endA ; rowA ++ , rowB ++ ) { double a = Q . get ( rowA ) ; double b = Q . get ( rowB ) ; Q . set ( rowA , c * a + s * b ) ; Q . set ( rowB , - s * a + c * b ) ; } }
Multiplied a transpose orthogonal matrix Q by the specified rotator . This is used to update the U and V matrices . Updating the transpose of the matrix is faster since it only modifies the rows .
255
47
149,097
protected boolean checkForAndHandleZeros ( ) { // check for zeros along off diagonal for ( int i = x2 - 1 ; i >= x1 ; i -- ) { if ( isOffZero ( i ) ) { // System.out.println("steps at split = "+steps); resetSteps ( ) ; splits [ numSplits ++ ] = i ; x1 = i + 1 ; return true ; } } // check for zeros along diagonal for ( int i = x2 - 1 ; i >= x1 ; i -- ) { if ( isDiagonalZero ( i ) ) { // System.out.println("steps at split = "+steps); pushRight ( i ) ; resetSteps ( ) ; splits [ numSplits ++ ] = i ; x1 = i + 1 ; return true ; } } return false ; }
Checks to see if either the diagonal element or off diagonal element is zero . If one is then it performs a split or pushes it off the matrix .
179
31
149,098
private void pushRight ( int row ) { if ( isOffZero ( row ) ) return ; // B = createB(); // B.print(); rotatorPushRight ( row ) ; int end = N - 2 - row ; for ( int i = 0 ; i < end && bulge != 0 ; i ++ ) { rotatorPushRight2 ( row , i + 2 ) ; } // } }
If there is a zero on the diagonal element the off diagonal element needs pushed off so that all the algorithms assumptions are two and so that it can split the matrix .
85
33
149,099
private void rotatorPushRight ( int m ) { double b11 = off [ m ] ; double b21 = diag [ m + 1 ] ; computeRotator ( b21 , - b11 ) ; // apply rotator on the right off [ m ] = 0 ; diag [ m + 1 ] = b21 * c - b11 * s ; if ( m + 2 < N ) { double b22 = off [ m + 1 ] ; off [ m + 1 ] = b22 * c ; bulge = b22 * s ; } else { bulge = 0 ; } // SimpleMatrix Q = createQ(m,m+1, c, s, true); // B=Q.mult(B); // // B.print(); // printMatrix(); // System.out.println(" bulge = "+bulge); // System.out.println(); if ( Ut != null ) { updateRotator ( Ut , m , m + 1 , c , s ) ; // SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print(); // printMatrix(); // System.out.println("bulge = "+bulge); // System.out.println(); } }
Start pushing the element off to the right .
264
9