idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
149,100
private void rotatorPushRight2 ( int m , int offset ) { double b11 = bulge ; double b12 = diag [ m + offset ] ; computeRotator ( b12 , - b11 ) ; diag [ m + offset ] = b12 * c - b11 * s ; if ( m + offset < N - 1 ) { double b22 = off [ m + offset ] ; off [ m + offset ] = b22 * c ; bulge = b22 * s ; } // SimpleMatrix Q = createQ(m,m+offset, 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 + offset , c , s ) ; // SimpleMatrix.wrap(Ut).mult(B).mult(SimpleMatrix.wrap(Vt).transpose()).print(); // printMatrix(); // System.out.println("bulge = "+bulge); // System.out.println(); } }
Used to finish up pushing the bulge off the matrix .
246
12
149,101
public void exceptionShift ( ) { numExceptional ++ ; double mag = 0.05 * numExceptional ; if ( mag > 1.0 ) mag = 1.0 ; double angle = 2.0 * UtilEjml . PI * ( rand . nextDouble ( ) - 0.5 ) * mag ; performImplicitSingleStep ( 0 , angle , true ) ; // allow more convergence time nextExceptional = steps + exceptionalThresh ; // (numExceptional+1)* }
It is possible for the QR algorithm to get stuck in a loop because of symmetries . This happens more often with larger matrices . By taking a random step it can break the symmetry and finish .
104
41
149,102
private boolean computeUWV ( ) { bidiag . getDiagonal ( diag , off ) ; qralg . setMatrix ( numRowsT , numColsT , diag , off ) ; // long pointA = System.currentTimeMillis(); // compute U and V matrices if ( computeU ) Ut = bidiag . getU ( Ut , true , compact ) ; if ( computeV ) Vt = bidiag . getV ( Vt , true , compact ) ; qralg . setFastValues ( false ) ; if ( computeU ) qralg . setUt ( Ut ) ; else qralg . setUt ( null ) ; if ( computeV ) qralg . setVt ( Vt ) ; else qralg . setVt ( null ) ; // long pointB = System.currentTimeMillis(); boolean ret = ! qralg . process ( ) ; // long pointC = System.currentTimeMillis(); // System.out.println(" compute UV "+(pointB-pointA)+" QR = "+(pointC-pointB)); return ret ; }
Compute singular values and U and V at the same time
243
12
149,103
private void makeSingularPositive ( ) { numSingular = qralg . getNumberOfSingularValues ( ) ; singularValues = qralg . getSingularValues ( ) ; for ( int i = 0 ; i < numSingular ; i ++ ) { double val = qralg . getSingularValue ( i ) ; if ( val < 0 ) { singularValues [ i ] = 0.0 - 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 . set ( j , 0.0 - Ut . get ( j ) ) ; } } } else { singularValues [ i ] = val ; } } }
With the QR algorithm it is possible for the found singular values to be negative . This makes them all positive by multiplying it by a diagonal matrix that has
191
30
149,104
public static boolean checkDuplicateElements ( DMatrixSparseCSC A ) { A = A . copy ( ) ; // create a copy so that it doesn't modify A A . sortIndices ( null ) ; return ! checkSortedFlag ( A ) ; }
Checks for duplicate elements . A is sorted
59
9
149,105
public static void changeSign ( DMatrixSparseCSC A , DMatrixSparseCSC B ) { if ( A != B ) { B . copyStructure ( A ) ; } for ( int i = 0 ; i < A . nz_length ; i ++ ) { B . nz_values [ i ] = - A . nz_values [ i ] ; } }
B = - A . Changes the sign of elements in A and stores it in B . A and B can be the same instance .
85
27
149,106
public static double elementMin ( DMatrixSparseCSC A ) { if ( A . nz_length == 0 ) return 0 ; // if every element is assigned a value then the first element can be a minimum. // Otherwise zero needs to be considered double min = A . isFull ( ) ? A . nz_values [ 0 ] : 0 ; for ( int i = 0 ; i < A . nz_length ; i ++ ) { double val = A . nz_values [ i ] ; if ( val < min ) { min = val ; } } return min ; }
Returns the value of the element with the minimum value
126
10
149,107
public static double elementMax ( DMatrixSparseCSC A ) { if ( A . nz_length == 0 ) return 0 ; // if every element is assigned a value then the first element can be a max. // Otherwise zero needs to be considered double max = A . isFull ( ) ? A . nz_values [ 0 ] : 0 ; for ( int i = 0 ; i < A . nz_length ; i ++ ) { double val = A . nz_values [ i ] ; if ( val > max ) { max = val ; } } return max ; }
Returns the value of the element with the largest value
126
10
149,108
public static double elementSum ( DMatrixSparseCSC A ) { if ( A . nz_length == 0 ) return 0 ; double sum = 0 ; for ( int i = 0 ; i < A . nz_length ; i ++ ) { sum += A . nz_values [ i ] ; } return sum ; }
Sum of all elements
72
4
149,109
public static void columnMaxAbs ( DMatrixSparseCSC A , double [ ] values ) { if ( values . length < A . numCols ) throw new IllegalArgumentException ( "Array is too small. " + values . length + " < " + A . numCols ) ; for ( int i = 0 ; i < A . numCols ; i ++ ) { int idx0 = A . col_idx [ i ] ; int idx1 = A . col_idx [ i + 1 ] ; double maxabs = 0 ; for ( int j = idx0 ; j < idx1 ; j ++ ) { double v = Math . abs ( A . nz_values [ j ] ) ; if ( v > maxabs ) maxabs = v ; } values [ i ] = maxabs ; } }
Finds the maximum abs in each column of A and stores it into values
181
15
149,110
public static DMatrixSparseCSC diag ( double ... values ) { int N = values . length ; return diag ( new DMatrixSparseCSC ( N , N , N ) , values , 0 , N ) ; }
Returns a diagonal matrix with the specified diagonal elements .
52
10
149,111
public static void permutationVector ( DMatrixSparseCSC P , int [ ] vector ) { if ( P . numCols != P . numRows ) { throw new MatrixDimensionException ( "Expected a square matrix" ) ; } else if ( P . nz_length != P . numCols ) { throw new IllegalArgumentException ( "Expected N non-zero elements in permutation matrix" ) ; } else if ( vector . length < P . numCols ) { throw new IllegalArgumentException ( "vector is too short" ) ; } int M = P . numCols ; for ( int i = 0 ; i < M ; i ++ ) { if ( P . col_idx [ i + 1 ] != i + 1 ) throw new IllegalArgumentException ( "Unexpected number of elements in a column" ) ; vector [ P . nz_rows [ i ] ] = i ; } }
Converts the permutation matrix into a vector
202
9
149,112
public static void permutationInverse ( int [ ] original , int [ ] inverse , int length ) { for ( int i = 0 ; i < length ; i ++ ) { inverse [ original [ i ] ] = i ; } }
Computes the inverse permutation vector
49
7
149,113
public static void zero ( DMatrixSparseCSC A , int row0 , int row1 , int col0 , int col1 ) { for ( int col = col1 - 1 ; col >= col0 ; col -- ) { int numRemoved = 0 ; int idx0 = A . col_idx [ col ] , idx1 = A . col_idx [ col + 1 ] ; for ( int i = idx0 ; i < idx1 ; i ++ ) { int row = A . nz_rows [ i ] ; // if sorted a faster technique could be used if ( row >= row0 && row < row1 ) { numRemoved ++ ; } else if ( numRemoved > 0 ) { A . nz_rows [ i - numRemoved ] = row ; A . nz_values [ i - numRemoved ] = A . nz_values [ i ] ; } } if ( numRemoved > 0 ) { // this could be done more intelligently. Each time a column is adjusted all the columns are adjusted // after it. Maybe accumulate the changes in each column and do it in one pass? Need an array to store // those results though for ( int i = idx1 ; i < A . nz_length ; i ++ ) { A . nz_rows [ i - numRemoved ] = A . nz_rows [ i ] ; A . nz_values [ i - numRemoved ] = A . nz_values [ i ] ; } A . nz_length -= numRemoved ; for ( int i = col + 1 ; i <= A . numCols ; i ++ ) { A . col_idx [ i ] -= numRemoved ; } } } }
Zeros an inner rectangle inside the matrix .
367
9
149,114
public static void removeZeros ( DMatrixSparseCSC input , DMatrixSparseCSC output , double tol ) { ImplCommonOps_DSCC . removeZeros ( input , output , tol ) ; }
Copies all elements from input into output which are &gt ; tol .
50
16
149,115
public void growMaxLength ( int arrayLength , boolean preserveValue ) { if ( arrayLength < 0 ) throw new IllegalArgumentException ( "Negative array length. Overflow?" ) ; // see if multiplying numRows*numCols will cause an overflow. If it won't then pick the smaller of the two if ( numRows != 0 && numCols <= Integer . MAX_VALUE / numRows ) { // save the user from themselves arrayLength = Math . min ( numRows * numCols , arrayLength ) ; } if ( nz_values == null || arrayLength > this . nz_values . length ) { double [ ] data = new double [ arrayLength ] ; int [ ] row_idx = new int [ arrayLength ] ; if ( preserveValue ) { if ( nz_values == null ) throw new IllegalArgumentException ( "Can't preserve values when uninitialized" ) ; System . arraycopy ( this . nz_values , 0 , data , 0 , this . nz_length ) ; System . arraycopy ( this . nz_rows , 0 , row_idx , 0 , this . nz_length ) ; } this . nz_values = data ; this . nz_rows = row_idx ; } }
Increases the maximum size of the data array so that it can store sparse data up to length . The class parameter nz_length is not modified by this function call .
277
34
149,116
public void growMaxColumns ( int desiredColumns , boolean preserveValue ) { if ( col_idx . length < desiredColumns + 1 ) { int [ ] c = new int [ desiredColumns + 1 ] ; if ( preserveValue ) System . arraycopy ( col_idx , 0 , c , 0 , col_idx . length ) ; col_idx = c ; } }
Increases the maximum number of columns in the matrix .
86
10
149,117
public void histogramToStructure ( int histogram [ ] ) { col_idx [ 0 ] = 0 ; int index = 0 ; for ( int i = 1 ; i <= numCols ; i ++ ) { col_idx [ i ] = index += histogram [ i - 1 ] ; } nz_length = index ; growMaxLength ( nz_length , false ) ; if ( col_idx [ numCols ] != nz_length ) throw new RuntimeException ( "Egads" ) ; }
Given the histogram of columns compute the col_idx for the matrix . nz_length is automatically set and nz_values will grow if needed .
115
33
149,118
public void sortIndices ( SortCoupledArray_F64 sorter ) { if ( sorter == null ) sorter = new SortCoupledArray_F64 ( ) ; sorter . quick ( col_idx , numCols + 1 , nz_rows , nz_values ) ; indicesSorted = true ; }
Sorts the row indices in ascending order .
74
9
149,119
public void copyStructure ( DMatrixSparseCSC orig ) { reshape ( orig . numRows , orig . numCols , orig . nz_length ) ; this . nz_length = orig . nz_length ; System . arraycopy ( orig . col_idx , 0 , col_idx , 0 , orig . numCols + 1 ) ; System . arraycopy ( orig . nz_rows , 0 , nz_rows , 0 , orig . nz_length ) ; }
Copies the non - zero structure of orig into this
113
11
149,120
public static boolean bidiagOuterBlocks ( final int blockLength , final DSubmatrixD1 A , final double gammasU [ ] , final double gammasV [ ] ) { // System.out.println("---------- Orig"); // A.original.print(); int width = Math . min ( blockLength , A . col1 - A . col0 ) ; int height = Math . min ( blockLength , A . row1 - A . row0 ) ; int min = Math . min ( width , height ) ; for ( int i = 0 ; i < min ; i ++ ) { //--- Apply reflector to the column // compute the householder vector if ( ! computeHouseHolderCol ( blockLength , A , gammasU , i ) ) return false ; // apply to rest of the columns in the column block rank1UpdateMultR_Col ( blockLength , A , i , gammasU [ A . col0 + i ] ) ; // apply to the top row block rank1UpdateMultR_TopRow ( blockLength , A , i , gammasU [ A . col0 + i ] ) ; System . out . println ( "After column stuff" ) ; A . original . print ( ) ; //-- Apply reflector to the row if ( ! computeHouseHolderRow ( blockLength , A , gammasV , i ) ) return false ; // apply to rest of the rows in the row block rank1UpdateMultL_Row ( blockLength , A , i , i + 1 , gammasV [ A . row0 + i ] ) ; System . out . println ( "After update row" ) ; A . original . print ( ) ; // apply to the left column block // TODO THIS WON'T WORK!!!!!!!!!!!!! // Needs the whole matrix to have been updated by the left reflector to compute the correct solution // rank1UpdateMultL_LeftCol(blockLength,A,i,i+1,gammasV[A.row0+i]); System . out . println ( "After row stuff" ) ; A . original . print ( ) ; } return true ; }
Performs a standard bidiagonal decomposition just on the outer blocks of the provided matrix
452
18
149,121
@ Override public boolean setA ( DMatrixRBlock A ) { // Extract a lower triangular solution if ( ! decomposer . decompose ( A ) ) return false ; blockLength = A . blockLength ; return true ; }
Decomposes and overwrites the input matrix .
50
10
149,122
@ Override public void solve ( DMatrixRBlock B , DMatrixRBlock X ) { if ( B . blockLength != blockLength ) throw new IllegalArgumentException ( "Unexpected blocklength in B." ) ; DSubmatrixD1 L = new DSubmatrixD1 ( decomposer . getT ( null ) ) ; if ( X != null ) { if ( X . blockLength != blockLength ) throw new IllegalArgumentException ( "Unexpected blocklength in X." ) ; if ( X . numRows != L . col1 ) throw new IllegalArgumentException ( "Not enough rows in X" ) ; } if ( B . numRows != L . col1 ) throw new IllegalArgumentException ( "Not enough rows in B" ) ; // L * L^T*X = B // Solve for Y: L*Y = B TriangularSolver_DDRB . solve ( blockLength , false , L , new DSubmatrixD1 ( B ) , false ) ; // L^T * X = Y TriangularSolver_DDRB . solve ( blockLength , false , L , new DSubmatrixD1 ( B ) , true ) ; if ( X != null ) { // copy the solution from B into X MatrixOps_DDRB . extractAligned ( B , X ) ; } }
If X == null then the solution is written into B . Otherwise the solution is copied from B into X .
295
22
149,123
public void growInternal ( int amount ) { int tmp [ ] = new int [ data . length + amount ] ; System . arraycopy ( data , 0 , tmp , 0 , data . length ) ; this . data = tmp ; }
Increases the internal array s length by the specified amount . Previous values are preserved . The length value is not modified since this does not change the meaning of the array just increases the amount of data which can be stored in it .
49
45
149,124
public static boolean lower ( double [ ] T , int indexT , int n ) { double el_ii ; double div_el_ii = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { double sum = T [ indexT + j * n + i ] ; // todo optimize for ( int k = 0 ; k < i ; k ++ ) { sum -= T [ indexT + i * n + k ] * T [ indexT + j * n + k ] ; } if ( i == j ) { // is it positive-definite? if ( sum <= 0.0 ) return false ; el_ii = Math . sqrt ( sum ) ; T [ indexT + i * n + i ] = el_ii ; div_el_ii = 1.0 / el_ii ; } else { T [ indexT + j * n + i ] = sum * div_el_ii ; } } } return true ; }
Performs an inline lower Cholesky decomposition on an inner row - major matrix . Only the lower triangular portion of the matrix is read or written to .
221
32
149,125
public static LinearSolverDense < DMatrixRMaj > general ( int numRows , int numCols ) { if ( numRows == numCols ) return linear ( numRows ) ; else return leastSquares ( numRows , numCols ) ; }
Creates a general purpose solver . Use this if you are not sure what you need .
61
19
149,126
public static LinearSolverDense < DMatrixRMaj > symmPosDef ( int matrixWidth ) { if ( matrixWidth < EjmlParameters . SWITCH_BLOCK64_CHOLESKY ) { CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM ( true ) ; return new LinearSolverChol_DDRM ( decomp ) ; } else { if ( EjmlParameters . MEMORY == EjmlParameters . MemoryUsage . FASTER ) return new LinearSolverChol_DDRB ( ) ; else { CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM ( true ) ; return new LinearSolverChol_DDRM ( decomp ) ; } } }
Creates a solver for symmetric positive definite matrices .
180
13
149,127
public void setConvergence ( int maxIterations , double ftol , double gtol ) { this . maxIterations = maxIterations ; this . ftol = ftol ; this . gtol = gtol ; }
Specifies convergence criteria
51
4
149,128
private void computeGradientAndHessian ( DMatrixRMaj param ) { // residuals = f(x) - y function . compute ( param , residuals ) ; computeNumericalJacobian ( param , jacobian ) ; CommonOps_DDRM . multTransA ( jacobian , residuals , g ) ; CommonOps_DDRM . multTransA ( jacobian , jacobian , H ) ; CommonOps_DDRM . extractDiag ( H , Hdiag ) ; }
Computes the d and H parameters .
118
8
149,129
public static DMatrixRMaj wrap ( int numRows , int numCols , double [ ] data ) { DMatrixRMaj s = new DMatrixRMaj ( ) ; s . data = data ; s . numRows = numRows ; s . numCols = numCols ; return s ; }
Creates a new DMatrixRMaj around the provided data . The data must encode a row - major matrix . Any modification to the returned matrix will modify the provided data .
71
36
149,130
public void add ( int row , int col , double value ) { if ( col < 0 || col >= numCols || row < 0 || row >= numRows ) { throw new IllegalArgumentException ( "Specified element is out of bounds" ) ; } data [ row * numCols + col ] += value ; }
todo move to commonops
70
6
149,131
@ Override public double get ( int row , int col ) { if ( col < 0 || col >= numCols || row < 0 || row >= numRows ) { throw new IllegalArgumentException ( "Specified element is out of bounds: " + row + " " + col ) ; } return data [ row * numCols + col ] ; }
Returns the value of the specified matrix element . Performs a bounds check to make sure the requested element is part of the matrix .
77
26
149,132
public void set ( int numRows , int numCols , boolean rowMajor , double ... data ) { reshape ( numRows , numCols ) ; int length = numRows * numCols ; if ( length > this . data . length ) throw new IllegalArgumentException ( "The length of this matrix's data array is too small." ) ; if ( rowMajor ) { System . arraycopy ( data , 0 , this . data , 0 , length ) ; } else { int index = 0 ; for ( int i = 0 ; i < numRows ; i ++ ) { for ( int j = 0 ; j < numCols ; j ++ ) { this . data [ index ++ ] = data [ j * numRows + i ] ; } } } }
Sets this matrix equal to the matrix encoded in the array .
167
13
149,133
@ Override public void solve ( DMatrixRMaj B , DMatrixRMaj X ) { blockB . reshape ( B . numRows , B . numCols , false ) ; MatrixOps_DDRB . convert ( B , blockB ) ; // since overwrite B is true X does not need to be passed in alg . solve ( blockB , null ) ; MatrixOps_DDRB . convert ( blockB , X ) ; }
Only converts the B matrix and passes that onto solve . Te result is then copied into the input X matrix .
99
22
149,134
public List < Complex_F64 > getEigenvalues ( ) { List < Complex_F64 > ret = new ArrayList < Complex_F64 > ( ) ; if ( is64 ) { EigenDecomposition_F64 d = ( EigenDecomposition_F64 ) eig ; for ( int i = 0 ; i < eig . getNumberOfEigenvalues ( ) ; i ++ ) { ret . add ( d . getEigenvalue ( i ) ) ; } } else { EigenDecomposition_F32 d = ( EigenDecomposition_F32 ) eig ; for ( int i = 0 ; i < eig . getNumberOfEigenvalues ( ) ; i ++ ) { Complex_F32 c = d . getEigenvalue ( i ) ; ret . add ( new Complex_F64 ( c . real , c . imaginary ) ) ; } } return ret ; }
Returns a list of all the eigenvalues
199
9
149,135
public int getIndexMax ( ) { int indexMax = 0 ; double max = getEigenvalue ( 0 ) . getMagnitude2 ( ) ; final int N = getNumberOfEigenvalues ( ) ; for ( int i = 1 ; i < N ; i ++ ) { double m = getEigenvalue ( i ) . getMagnitude2 ( ) ; if ( m > max ) { max = m ; indexMax = i ; } } return indexMax ; }
Returns the index of the eigenvalue which has the largest magnitude .
101
14
149,136
public int getIndexMin ( ) { int indexMin = 0 ; double min = getEigenvalue ( 0 ) . getMagnitude2 ( ) ; final int N = getNumberOfEigenvalues ( ) ; for ( int i = 1 ; i < N ; i ++ ) { double m = getEigenvalue ( i ) . getMagnitude2 ( ) ; if ( m < min ) { min = m ; indexMin = i ; } } return indexMin ; }
Returns the index of the eigenvalue which has the smallest magnitude .
101
14
149,137
public boolean process ( DMatrixSparseCSC A ) { init ( A ) ; TriangularSolver_DSCC . eliminationTree ( A , true , parent , gwork ) ; countNonZeroInR ( parent ) ; countNonZeroInV ( parent ) ; // if more columns than rows it's possible that Q*R != A. That's because a householder // would need to be created that's outside the m by m Q matrix. In reality it has // a partial solution. Column pivot are needed. if ( m < n ) { for ( int row = 0 ; row < m ; row ++ ) { if ( gwork . data [ head + row ] < 0 ) { return false ; } } } return true ; }
Examins the structure of A for QR decomposition
157
10
149,138
void init ( DMatrixSparseCSC A ) { this . A = A ; this . m = A . numRows ; this . n = A . numCols ; this . next = 0 ; this . head = m ; this . tail = m + n ; this . nque = m + 2 * n ; if ( parent . length < n || leftmost . length < m ) { parent = new int [ n ] ; post = new int [ n ] ; pinv = new int [ m + n ] ; countsR = new int [ n ] ; leftmost = new int [ m ] ; } gwork . reshape ( m + 3 * n ) ; }
Initializes data structures
146
4
149,139
void countNonZeroInR ( int [ ] parent ) { TriangularSolver_DSCC . postorder ( parent , n , post , gwork ) ; columnCounts . process ( A , parent , post , countsR ) ; nz_in_R = 0 ; for ( int k = 0 ; k < n ; k ++ ) { nz_in_R += countsR [ k ] ; } if ( nz_in_R < 0 ) throw new RuntimeException ( "Too many elements. Numerical overflow in R counts" ) ; }
Count the number of non - zero elements in R
120
10
149,140
void countNonZeroInV ( int [ ] parent ) { int [ ] w = gwork . data ; findMinElementIndexInRows ( leftmost ) ; createRowElementLinkedLists ( leftmost , w ) ; countNonZeroUsingLinkedList ( parent , w ) ; }
Count the number of non - zero elements in V
63
10
149,141
void countNonZeroUsingLinkedList ( int parent [ ] , int ll [ ] ) { Arrays . fill ( pinv , 0 , m , - 1 ) ; nz_in_V = 0 ; m2 = m ; for ( int k = 0 ; k < n ; k ++ ) { int i = ll [ head + k ] ; // remove row i from queue k nz_in_V ++ ; // count V(k,k) as nonzero if ( i < 0 ) // add a fictitious row since there are no nz elements i = m2 ++ ; pinv [ i ] = k ; // associate row i with V(:,k) if ( -- ll [ nque + k ] <= 0 ) continue ; nz_in_V += ll [ nque + k ] ; int pa ; if ( ( pa = parent [ k ] ) != - 1 ) { // move all rows to parent of k if ( ll [ nque + pa ] == 0 ) ll [ tail + pa ] = ll [ tail + k ] ; ll [ next + ll [ tail + k ] ] = ll [ head + pa ] ; ll [ head + pa ] = ll [ next + i ] ; ll [ nque + pa ] += ll [ nque + k ] ; } } for ( int i = 0 , k = n ; i < m ; i ++ ) { if ( pinv [ i ] < 0 ) pinv [ i ] = k ++ ; } if ( nz_in_V < 0 ) throw new RuntimeException ( "Too many elements. Numerical overflow in V counts" ) ; }
Non - zero counts of Householder vectors and computes a permutation matrix that ensures diagonal entires are all structurally nonzero .
347
27
149,142
public void alias ( DMatrixRMaj variable , String name ) { if ( isReserved ( name ) ) throw new RuntimeException ( "Reserved word or contains a reserved character" ) ; VariableMatrix old = ( VariableMatrix ) variables . get ( name ) ; if ( old == null ) { variables . put ( name , new VariableMatrix ( variable ) ) ; } else { old . matrix = variable ; } }
Adds a new Matrix variable . If one already has the same name it is written over .
88
18
149,143
public void alias ( double value , String name ) { if ( isReserved ( name ) ) throw new RuntimeException ( "Reserved word or contains a reserved character. '" + name + "'" ) ; VariableDouble old = ( VariableDouble ) variables . get ( name ) ; if ( old == null ) { variables . put ( name , new VariableDouble ( value ) ) ; } else { old . value = value ; } }
Adds a new floating point variable . If one already has the same name it is written over .
91
19
149,144
public void alias ( Object ... args ) { if ( args . length % 2 == 1 ) throw new RuntimeException ( "Even number of arguments expected" ) ; for ( int i = 0 ; i < args . length ; i += 2 ) { aliasGeneric ( args [ i ] , ( String ) args [ i + 1 ] ) ; } }
Creates multiple aliases at once .
72
7
149,145
protected void aliasGeneric ( Object variable , String name ) { if ( variable . getClass ( ) == Integer . class ) { alias ( ( ( Integer ) variable ) . intValue ( ) , name ) ; } else if ( variable . getClass ( ) == Double . class ) { alias ( ( ( Double ) variable ) . doubleValue ( ) , name ) ; } else if ( variable . getClass ( ) == DMatrixRMaj . class ) { alias ( ( DMatrixRMaj ) variable , name ) ; } else if ( variable . getClass ( ) == FMatrixRMaj . class ) { alias ( ( FMatrixRMaj ) variable , name ) ; } else if ( variable . getClass ( ) == DMatrixSparseCSC . class ) { alias ( ( DMatrixSparseCSC ) variable , name ) ; } else if ( variable . getClass ( ) == SimpleMatrix . class ) { alias ( ( SimpleMatrix ) variable , name ) ; } else if ( variable instanceof DMatrixFixed ) { DMatrixRMaj M = new DMatrixRMaj ( 1 , 1 ) ; ConvertDMatrixStruct . convert ( ( DMatrixFixed ) variable , M ) ; alias ( M , name ) ; } else if ( variable instanceof FMatrixFixed ) { FMatrixRMaj M = new FMatrixRMaj ( 1 , 1 ) ; ConvertFMatrixStruct . convert ( ( FMatrixFixed ) variable , M ) ; alias ( M , name ) ; } else { throw new RuntimeException ( "Unknown value type of " + ( variable . getClass ( ) . getSimpleName ( ) ) + " for variable " + name ) ; } }
Aliases variables with an unknown type .
364
8
149,146
public Sequence compile ( String equation , boolean assignment , boolean debug ) { functions . setManagerTemp ( managerTemp ) ; Sequence sequence = new Sequence ( ) ; TokenList tokens = extractTokens ( equation , managerTemp ) ; if ( tokens . size ( ) < 3 ) throw new RuntimeException ( "Too few tokens" ) ; TokenList . Token t0 = tokens . getFirst ( ) ; if ( t0 . word != null && t0 . word . compareToIgnoreCase ( "macro" ) == 0 ) { parseMacro ( tokens , sequence ) ; } else { insertFunctionsAndVariables ( tokens ) ; insertMacros ( tokens ) ; if ( debug ) { System . out . println ( "Parsed tokens:\n------------" ) ; tokens . print ( ) ; System . out . println ( ) ; } // Get the results variable if ( t0 . getType ( ) != Type . VARIABLE && t0 . getType ( ) != Type . WORD ) { compileTokens ( sequence , tokens ) ; // If there's no output then this is acceptable, otherwise it's assumed to be a bug // If there's no output then a configuration was changed Variable variable = tokens . getFirst ( ) . getVariable ( ) ; if ( variable != null ) { if ( assignment ) throw new IllegalArgumentException ( "No assignment to an output variable could be found. Found " + t0 ) ; else { sequence . output = variable ; // set this to be the output for print() } } } else { compileAssignment ( sequence , tokens , t0 ) ; } if ( debug ) { System . out . println ( "Operations:\n------------" ) ; for ( int i = 0 ; i < sequence . operations . size ( ) ; i ++ ) { System . out . println ( sequence . operations . get ( i ) . name ( ) ) ; } } } return sequence ; }
Parses the equation and compiles it into a sequence which can be executed later on
405
18
149,147
private void parseMacro ( TokenList tokens , Sequence sequence ) { Macro macro = new Macro ( ) ; TokenList . Token t = tokens . getFirst ( ) . next ; if ( t . word == null ) { throw new ParseError ( "Expected the macro's name after " + tokens . getFirst ( ) . word ) ; } List < TokenList . Token > variableTokens = new ArrayList < TokenList . Token > ( ) ; macro . name = t . word ; t = t . next ; t = parseMacroInput ( variableTokens , t ) ; for ( TokenList . Token a : variableTokens ) { if ( a . word == null ) throw new ParseError ( "expected word in macro header" ) ; macro . inputs . add ( a . word ) ; } t = t . next ; if ( t == null || t . getSymbol ( ) != Symbol . ASSIGN ) throw new ParseError ( "Expected assignment" ) ; t = t . next ; macro . tokens = new TokenList ( t , tokens . last ) ; sequence . addOperation ( macro . createOperation ( macros ) ) ; }
Parse a macro defintion .
243
8
149,148
private void checkForUnknownVariables ( TokenList tokens ) { TokenList . Token t = tokens . getFirst ( ) ; while ( t != null ) { if ( t . getType ( ) == Type . WORD ) throw new ParseError ( "Unknown variable on right side. " + t . getWord ( ) ) ; t = t . next ; } }
Examines the list of variables for any unknown variables and throws an exception if one is found
78
18
149,149
private Variable createVariableInferred ( TokenList . Token t0 , Variable variableRight ) { Variable result ; if ( t0 . getType ( ) == Type . WORD ) { switch ( variableRight . getType ( ) ) { case MATRIX : alias ( new DMatrixRMaj ( 1 , 1 ) , t0 . getWord ( ) ) ; break ; case SCALAR : if ( variableRight instanceof VariableInteger ) { alias ( 0 , t0 . getWord ( ) ) ; } else { alias ( 1.0 , t0 . getWord ( ) ) ; } break ; case INTEGER_SEQUENCE : alias ( ( IntegerSequence ) null , t0 . getWord ( ) ) ; break ; default : throw new RuntimeException ( "Type not supported for assignment: " + variableRight . getType ( ) ) ; } result = variables . get ( t0 . getWord ( ) ) ; } else { result = t0 . getVariable ( ) ; } return result ; }
Infer the type of and create a new output variable using the results from the right side of the equation . If the type is already known just return that .
216
32
149,150
private List < Variable > parseAssignRange ( Sequence sequence , TokenList tokens , TokenList . Token t0 ) { // find assignment symbol TokenList . Token tokenAssign = t0 . next ; while ( tokenAssign != null && tokenAssign . symbol != Symbol . ASSIGN ) { tokenAssign = tokenAssign . next ; } if ( tokenAssign == null ) throw new ParseError ( "Can't find assignment operator" ) ; // see if it is a sub matrix before if ( tokenAssign . previous . symbol == Symbol . PAREN_RIGHT ) { TokenList . Token start = t0 . next ; if ( start . symbol != Symbol . PAREN_LEFT ) throw new ParseError ( ( "Expected left param for assignment" ) ) ; TokenList . Token end = tokenAssign . previous ; TokenList subTokens = tokens . extractSubList ( start , end ) ; subTokens . remove ( subTokens . getFirst ( ) ) ; subTokens . remove ( subTokens . getLast ( ) ) ; handleParentheses ( subTokens , sequence ) ; List < TokenList . Token > inputs = parseParameterCommaBlock ( subTokens , sequence ) ; if ( inputs . isEmpty ( ) ) throw new ParseError ( "Empty function input parameters" ) ; List < Variable > range = new ArrayList <> ( ) ; addSubMatrixVariables ( inputs , range ) ; if ( range . size ( ) != 1 && range . size ( ) != 2 ) { throw new ParseError ( "Unexpected number of range variables. 1 or 2 expected" ) ; } return range ; } return null ; }
See if a range for assignment is specified . If so return the range otherwise return null
351
17
149,151
protected void handleParentheses ( TokenList tokens , Sequence sequence ) { // have a list to handle embedded parentheses, e.g. (((((a))))) List < TokenList . Token > left = new ArrayList < TokenList . Token > ( ) ; // find all of them TokenList . Token t = tokens . first ; while ( t != null ) { TokenList . Token next = t . next ; if ( t . getType ( ) == Type . SYMBOL ) { if ( t . getSymbol ( ) == Symbol . PAREN_LEFT ) left . add ( t ) ; else if ( t . getSymbol ( ) == Symbol . PAREN_RIGHT ) { if ( left . isEmpty ( ) ) throw new ParseError ( ") found with no matching (" ) ; TokenList . Token a = left . remove ( left . size ( ) - 1 ) ; // remember the element before so the new one can be inserted afterwards TokenList . Token before = a . previous ; TokenList sublist = tokens . extractSubList ( a , t ) ; // remove parentheses sublist . remove ( sublist . first ) ; sublist . remove ( sublist . last ) ; // if its a function before () then the () indicates its an input to a function if ( before != null && before . getType ( ) == Type . FUNCTION ) { List < TokenList . Token > inputs = parseParameterCommaBlock ( sublist , sequence ) ; if ( inputs . isEmpty ( ) ) throw new ParseError ( "Empty function input parameters" ) ; else { createFunction ( before , inputs , tokens , sequence ) ; } } else if ( before != null && before . getType ( ) == Type . VARIABLE && before . getVariable ( ) . getType ( ) == VariableType . MATRIX ) { // if it's a variable then that says it's a sub-matrix TokenList . Token extract = parseSubmatrixToExtract ( before , sublist , sequence ) ; // put in the extract operation tokens . insert ( before , extract ) ; tokens . remove ( before ) ; } else { // if null then it was empty inside TokenList . Token output = parseBlockNoParentheses ( sublist , sequence , false ) ; if ( output != null ) tokens . insert ( before , output ) ; } } } t = next ; } if ( ! left . isEmpty ( ) ) throw new ParseError ( "Dangling ( parentheses" ) ; }
Searches for pairs of parentheses and processes blocks inside of them . Embedded parentheses are handled with no problem . On output only a single token should be in tokens .
531
34
149,152
protected List < TokenList . Token > parseParameterCommaBlock ( TokenList tokens , Sequence sequence ) { // find all the comma tokens List < TokenList . Token > commas = new ArrayList < TokenList . Token > ( ) ; TokenList . Token token = tokens . first ; int numBracket = 0 ; while ( token != null ) { if ( token . getType ( ) == Type . SYMBOL ) { switch ( token . getSymbol ( ) ) { case COMMA : if ( numBracket == 0 ) commas . add ( token ) ; break ; case BRACKET_LEFT : numBracket ++ ; break ; case BRACKET_RIGHT : numBracket -- ; break ; } } token = token . next ; } List < TokenList . Token > output = new ArrayList < TokenList . Token > ( ) ; if ( commas . isEmpty ( ) ) { output . add ( parseBlockNoParentheses ( tokens , sequence , false ) ) ; } else { TokenList . Token before = tokens . first ; for ( int i = 0 ; i < commas . size ( ) ; i ++ ) { TokenList . Token after = commas . get ( i ) ; if ( before == after ) throw new ParseError ( "No empty function inputs allowed!" ) ; TokenList . Token tmp = after . next ; TokenList sublist = tokens . extractSubList ( before , after ) ; sublist . remove ( after ) ; // remove the comma output . add ( parseBlockNoParentheses ( sublist , sequence , false ) ) ; before = tmp ; } // if the last character is a comma then after.next above will be null and thus before is null if ( before == null ) throw new ParseError ( "No empty function inputs allowed!" ) ; TokenList . Token after = tokens . last ; TokenList sublist = tokens . extractSubList ( before , after ) ; output . add ( parseBlockNoParentheses ( sublist , sequence , false ) ) ; } return output ; }
Searches for commas in the set of tokens . Used for inputs to functions .
434
18
149,153
protected TokenList . Token parseSubmatrixToExtract ( TokenList . Token variableTarget , TokenList tokens , Sequence sequence ) { List < TokenList . Token > inputs = parseParameterCommaBlock ( tokens , sequence ) ; List < Variable > variables = new ArrayList < Variable > ( ) ; // for the operation, the first variable must be the matrix which is being manipulated variables . add ( variableTarget . getVariable ( ) ) ; addSubMatrixVariables ( inputs , variables ) ; if ( variables . size ( ) != 2 && variables . size ( ) != 3 ) { throw new ParseError ( "Unexpected number of variables. 1 or 2 expected" ) ; } // first parameter is the matrix it will be extracted from. rest specify range Operation . Info info ; // only one variable means its referencing elements // two variables means its referencing a sub matrix if ( inputs . size ( ) == 1 ) { Variable varA = variables . get ( 1 ) ; if ( varA . getType ( ) == VariableType . SCALAR ) { info = functions . create ( "extractScalar" , variables ) ; } else { info = functions . create ( "extract" , variables ) ; } } else if ( inputs . size ( ) == 2 ) { Variable varA = variables . get ( 1 ) ; Variable varB = variables . get ( 2 ) ; if ( varA . getType ( ) == VariableType . SCALAR && varB . getType ( ) == VariableType . SCALAR ) { info = functions . create ( "extractScalar" , variables ) ; } else { info = functions . create ( "extract" , variables ) ; } } else { throw new ParseError ( "Expected 2 inputs to sub-matrix" ) ; } sequence . addOperation ( info . op ) ; return new TokenList . Token ( info . output ) ; }
Converts a submatrix into an extract matrix operation .
404
12
149,154
private void addSubMatrixVariables ( List < TokenList . Token > inputs , List < Variable > variables ) { for ( int i = 0 ; i < inputs . size ( ) ; i ++ ) { TokenList . Token t = inputs . get ( i ) ; if ( t . getType ( ) != Type . VARIABLE ) throw new ParseError ( "Expected variables only in sub-matrix input, not " + t . getType ( ) ) ; Variable v = t . getVariable ( ) ; if ( v . getType ( ) == VariableType . INTEGER_SEQUENCE || isVariableInteger ( t ) ) { variables . add ( v ) ; } else { throw new ParseError ( "Expected an integer, integer sequence, or array range to define a submatrix" ) ; } } }
Goes through the token lists and adds all the variables which can be used to define a sub - matrix . If anything else is found an excpetion is thrown
179
33
149,155
protected TokenList . Token parseBlockNoParentheses ( TokenList tokens , Sequence sequence , boolean insideMatrixConstructor ) { // search for matrix bracket operations if ( ! insideMatrixConstructor ) { parseBracketCreateMatrix ( tokens , sequence ) ; } // First create sequences from anything involving a colon parseSequencesWithColons ( tokens , sequence ) ; // process operators depending on their priority parseNegOp ( tokens , sequence ) ; parseOperationsL ( tokens , sequence ) ; parseOperationsLR ( new Symbol [ ] { Symbol . POWER , Symbol . ELEMENT_POWER } , tokens , sequence ) ; parseOperationsLR ( new Symbol [ ] { Symbol . TIMES , Symbol . RDIVIDE , Symbol . LDIVIDE , Symbol . ELEMENT_TIMES , Symbol . ELEMENT_DIVIDE } , tokens , sequence ) ; parseOperationsLR ( new Symbol [ ] { Symbol . PLUS , Symbol . MINUS } , tokens , sequence ) ; // Commas are used in integer sequences. Can be used to force to compiler to treat - as negative not // minus. They can now be removed since they have served their purpose stripCommas ( tokens ) ; // now construct rest of the lists and combine them together parseIntegerLists ( tokens ) ; parseCombineIntegerLists ( tokens ) ; if ( ! insideMatrixConstructor ) { if ( tokens . size ( ) > 1 ) { System . err . println ( "Remaining tokens: " + tokens . size ) ; TokenList . Token t = tokens . first ; while ( t != null ) { System . err . println ( " " + t ) ; t = t . next ; } throw new RuntimeException ( "BUG in parser. There should only be a single token left" ) ; } return tokens . first ; } else { return null ; } }
Parses a code block with no parentheses and no commas . After it is done there should be a single token left which is returned .
383
29
149,156
private void stripCommas ( TokenList tokens ) { TokenList . Token t = tokens . getFirst ( ) ; while ( t != null ) { TokenList . Token next = t . next ; if ( t . getSymbol ( ) == Symbol . COMMA ) { tokens . remove ( t ) ; } t = next ; } }
Removes all commas from the token list
71
9
149,157
protected void parseSequencesWithColons ( TokenList tokens , Sequence sequence ) { TokenList . Token t = tokens . getFirst ( ) ; if ( t == null ) return ; int state = 0 ; TokenList . Token start = null ; TokenList . Token middle = null ; TokenList . Token prev = t ; boolean last = false ; while ( true ) { if ( state == 0 ) { if ( isVariableInteger ( t ) && ( t . next != null && t . next . getSymbol ( ) == Symbol . COLON ) ) { start = t ; state = 1 ; t = t . next ; } else if ( t != null && t . getSymbol ( ) == Symbol . COLON ) { // If it starts with a colon then it must be 'all' or a type-o IntegerSequence range = new IntegerSequence . Range ( null , null ) ; VariableIntegerSequence varSequence = functions . getManagerTemp ( ) . createIntegerSequence ( range ) ; TokenList . Token n = new TokenList . Token ( varSequence ) ; tokens . insert ( t . previous , n ) ; tokens . remove ( t ) ; t = n ; } } else if ( state == 1 ) { // var : ? if ( isVariableInteger ( t ) ) { state = 2 ; } else { // array range IntegerSequence range = new IntegerSequence . Range ( start , null ) ; VariableIntegerSequence varSequence = functions . getManagerTemp ( ) . createIntegerSequence ( range ) ; replaceSequence ( tokens , varSequence , start , prev ) ; state = 0 ; } } else if ( state == 2 ) { // var:var ? if ( t != null && t . getSymbol ( ) == Symbol . COLON ) { middle = prev ; state = 3 ; } else { // create for sequence with start and stop elements only IntegerSequence numbers = new IntegerSequence . For ( start , null , prev ) ; VariableIntegerSequence varSequence = functions . getManagerTemp ( ) . createIntegerSequence ( numbers ) ; replaceSequence ( tokens , varSequence , start , prev ) ; if ( t != null ) t = t . previous ; state = 0 ; } } else if ( state == 3 ) { // var:var: ? if ( isVariableInteger ( t ) ) { // create 'for' sequence with three variables IntegerSequence numbers = new IntegerSequence . For ( start , middle , t ) ; VariableIntegerSequence varSequence = functions . getManagerTemp ( ) . createIntegerSequence ( numbers ) ; t = replaceSequence ( tokens , varSequence , start , t ) ; } else { // array range with 2 elements IntegerSequence numbers = new IntegerSequence . Range ( start , middle ) ; VariableIntegerSequence varSequence = functions . getManagerTemp ( ) . createIntegerSequence ( numbers ) ; replaceSequence ( tokens , varSequence , start , prev ) ; } state = 0 ; } if ( last ) { break ; } else if ( t . next == null ) { // handle the case where it is the last token in the sequence last = true ; } prev = t ; t = t . next ; } }
Searches for descriptions of integer sequences and array ranges that have a colon character in them
690
18
149,158
protected void parseIntegerLists ( TokenList tokens ) { TokenList . Token t = tokens . getFirst ( ) ; if ( t == null || t . next == null ) return ; int state = 0 ; TokenList . Token start = null ; TokenList . Token prev = t ; boolean last = false ; while ( true ) { if ( state == 0 ) { if ( isVariableInteger ( t ) ) { start = t ; state = 1 ; } } else if ( state == 1 ) { // var ? if ( isVariableInteger ( t ) ) { // see if its explicit number sequence state = 2 ; } else { // just scalar integer, skip state = 0 ; } } else if ( state == 2 ) { // var var .... if ( ! isVariableInteger ( t ) ) { // create explicit list sequence IntegerSequence sequence = new IntegerSequence . Explicit ( start , prev ) ; VariableIntegerSequence varSequence = functions . getManagerTemp ( ) . createIntegerSequence ( sequence ) ; replaceSequence ( tokens , varSequence , start , prev ) ; state = 0 ; } } if ( last ) { break ; } else if ( t . next == null ) { // handle the case where it is the last token in the sequence last = true ; } prev = t ; t = t . next ; } }
Searches for a sequence of integers
283
8
149,159
protected void parseCombineIntegerLists ( TokenList tokens ) { TokenList . Token t = tokens . getFirst ( ) ; if ( t == null || t . next == null ) return ; int numFound = 0 ; TokenList . Token start = null ; TokenList . Token end = null ; while ( t != null ) { if ( t . getType ( ) == Type . VARIABLE && ( isVariableInteger ( t ) || t . getVariable ( ) . getType ( ) == VariableType . INTEGER_SEQUENCE ) ) { if ( numFound == 0 ) { numFound = 1 ; start = end = t ; } else { numFound ++ ; end = t ; } } else if ( numFound > 1 ) { IntegerSequence sequence = new IntegerSequence . Combined ( start , end ) ; VariableIntegerSequence varSequence = functions . getManagerTemp ( ) . createIntegerSequence ( sequence ) ; replaceSequence ( tokens , varSequence , start , end ) ; numFound = 0 ; } else { numFound = 0 ; } t = t . next ; } if ( numFound > 1 ) { IntegerSequence sequence = new IntegerSequence . Combined ( start , end ) ; VariableIntegerSequence varSequence = functions . getManagerTemp ( ) . createIntegerSequence ( sequence ) ; replaceSequence ( tokens , varSequence , start , end ) ; } }
Looks for sequences of integer lists and combine them into one big sequence
303
13
149,160
private static boolean isVariableInteger ( TokenList . Token t ) { if ( t == null ) return false ; return t . getScalarType ( ) == VariableScalar . Type . INTEGER ; }
Checks to see if the token is an integer scalar
46
12
149,161
protected void parseBracketCreateMatrix ( TokenList tokens , Sequence sequence ) { List < TokenList . Token > left = new ArrayList < TokenList . Token > ( ) ; TokenList . Token t = tokens . getFirst ( ) ; while ( t != null ) { TokenList . Token next = t . next ; if ( t . getSymbol ( ) == Symbol . BRACKET_LEFT ) { left . add ( t ) ; } else if ( t . getSymbol ( ) == Symbol . BRACKET_RIGHT ) { if ( left . isEmpty ( ) ) throw new RuntimeException ( "No matching left bracket for right" ) ; TokenList . Token start = left . remove ( left . size ( ) - 1 ) ; // Compute everything inside the [ ], this will leave a // series of variables and semi-colons hopefully TokenList bracketLet = tokens . extractSubList ( start . next , t . previous ) ; parseBlockNoParentheses ( bracketLet , sequence , true ) ; MatrixConstructor constructor = constructMatrix ( bracketLet ) ; // define the matrix op and inject into token list Operation . Info info = Operation . matrixConstructor ( constructor ) ; sequence . addOperation ( info . op ) ; tokens . insert ( start . previous , new TokenList . Token ( info . output ) ) ; // remove the brackets tokens . remove ( start ) ; tokens . remove ( t ) ; } t = next ; } if ( ! left . isEmpty ( ) ) throw new RuntimeException ( "Dangling [" ) ; }
Searches for brackets which are only used to construct new matrices by concatenating 1 or more matrices together
327
24
149,162
protected void parseNegOp ( TokenList tokens , Sequence sequence ) { if ( tokens . size == 0 ) return ; TokenList . Token token = tokens . first ; while ( token != null ) { TokenList . Token next = token . next ; escape : if ( token . getSymbol ( ) == Symbol . MINUS ) { if ( token . previous != null && token . previous . getType ( ) != Type . SYMBOL ) break escape ; if ( token . previous != null && token . previous . getType ( ) == Type . SYMBOL && ( token . previous . symbol == Symbol . TRANSPOSE ) ) break escape ; if ( token . next == null || token . next . getType ( ) == Type . SYMBOL ) break escape ; if ( token . next . getType ( ) != Type . VARIABLE ) throw new RuntimeException ( "Crap bug rethink this function" ) ; // create the operation Operation . Info info = Operation . neg ( token . next . getVariable ( ) , functions . getManagerTemp ( ) ) ; // add the operation to the sequence sequence . addOperation ( info . op ) ; // update the token list TokenList . Token t = new TokenList . Token ( info . output ) ; tokens . insert ( token . next , t ) ; tokens . remove ( token . next ) ; tokens . remove ( token ) ; next = t ; } token = next ; } }
Searches for cases where a minus sign means negative operator . That happens when there is a minus sign with a variable to its right and no variable to its left
302
33
149,163
protected void parseOperationsL ( TokenList tokens , Sequence sequence ) { if ( tokens . size == 0 ) return ; TokenList . Token token = tokens . first ; if ( token . getType ( ) != Type . VARIABLE ) throw new ParseError ( "The first token in an equation needs to be a variable and not " + token ) ; while ( token != null ) { if ( token . getType ( ) == Type . FUNCTION ) { throw new ParseError ( "Function encountered with no parentheses" ) ; } else if ( token . getType ( ) == Type . SYMBOL && token . getSymbol ( ) == Symbol . TRANSPOSE ) { if ( token . previous . getType ( ) == Type . VARIABLE ) token = insertTranspose ( token . previous , tokens , sequence ) ; else throw new ParseError ( "Expected variable before transpose" ) ; } token = token . next ; } }
Parses operations where the input comes from variables to its left only . Hard coded to only look for transpose for now
205
25
149,164
protected void parseOperationsLR ( Symbol ops [ ] , TokenList tokens , Sequence sequence ) { if ( tokens . size == 0 ) return ; TokenList . Token token = tokens . first ; if ( token . getType ( ) != Type . VARIABLE ) throw new ParseError ( "The first token in an equation needs to be a variable and not " + token ) ; boolean hasLeft = false ; while ( token != null ) { if ( token . getType ( ) == Type . FUNCTION ) { throw new ParseError ( "Function encountered with no parentheses" ) ; } else if ( token . getType ( ) == Type . VARIABLE ) { if ( hasLeft ) { if ( isTargetOp ( token . previous , ops ) ) { token = createOp ( token . previous . previous , token . previous , token , tokens , sequence ) ; } } else { hasLeft = true ; } } else { if ( token . previous . getType ( ) == Type . SYMBOL ) { throw new ParseError ( "Two symbols next to each other. " + token . previous + " and " + token ) ; } } token = token . next ; } }
Parses operations where the input comes from variables to its left and right
254
15
149,165
public < T extends Variable > T lookupVariable ( String token ) { Variable result = variables . get ( token ) ; return ( T ) result ; }
Looks up a variable given its name . If none is found then return null .
31
16
149,166
void insertMacros ( TokenList tokens ) { TokenList . Token t = tokens . getFirst ( ) ; while ( t != null ) { if ( t . getType ( ) == Type . WORD ) { Macro v = lookupMacro ( t . word ) ; if ( v != null ) { TokenList . Token before = t . previous ; List < TokenList . Token > inputs = new ArrayList < TokenList . Token > ( ) ; t = parseMacroInput ( inputs , t . next ) ; TokenList sniplet = v . execute ( inputs ) ; tokens . extractSubList ( before . next , t ) ; tokens . insertAfter ( before , sniplet ) ; t = sniplet . last ; } } t = t . next ; } }
Checks to see if a WORD matches the name of a macro . if it does it applies the macro at that location
165
25
149,167
protected static boolean isTargetOp ( TokenList . Token token , Symbol [ ] ops ) { Symbol c = token . symbol ; for ( int i = 0 ; i < ops . length ; i ++ ) { if ( c == ops [ i ] ) return true ; } return false ; }
Checks to see if the token is in the list of allowed character operations . Used to apply order of operations
60
22
149,168
protected static boolean isOperatorLR ( Symbol s ) { if ( s == null ) return false ; switch ( s ) { case ELEMENT_DIVIDE : case ELEMENT_TIMES : case ELEMENT_POWER : case RDIVIDE : case LDIVIDE : case TIMES : case POWER : case PLUS : case MINUS : case ASSIGN : return true ; } return false ; }
Operators which affect the variables to its left and right
84
11
149,169
protected boolean isReserved ( String name ) { if ( functions . isFunctionName ( name ) ) return true ; for ( int i = 0 ; i < name . length ( ) ; i ++ ) { if ( ! isLetter ( name . charAt ( i ) ) ) return true ; } return false ; }
Returns true if the specified name is NOT allowed . It isn t allowed if it matches a built in operator or if it contains a restricted character .
66
29
149,170
public Equation process ( String equation , boolean debug ) { compile ( equation , true , debug ) . perform ( ) ; return this ; }
Compiles and performs the provided equation .
29
8
149,171
public void print ( String equation ) { // first assume it's just a variable Variable v = lookupVariable ( equation ) ; if ( v == null ) { Sequence sequence = compile ( equation , false , false ) ; sequence . perform ( ) ; v = sequence . output ; } if ( v instanceof VariableMatrix ) { ( ( VariableMatrix ) v ) . matrix . print ( ) ; } else if ( v instanceof VariableScalar ) { System . out . println ( "Scalar = " + ( ( VariableScalar ) v ) . getDouble ( ) ) ; } else { System . out . println ( "Add support for " + v . getClass ( ) . getSimpleName ( ) ) ; } }
Prints the results of the equation to standard out . Useful for debugging
153
14
149,172
public static double computeTauAndDivide ( final int j , final int numRows , final double [ ] u , final double max ) { double tau = 0 ; // double div_max = 1.0/max; // if( Double.isInfinite(div_max)) { for ( int i = j ; i < numRows ; i ++ ) { double d = u [ i ] /= max ; tau += d * d ; } // } else { // for( int i = j; i < numRows; i++ ) { // double d = u[i] *= div_max; // tau += d*d; // } // } tau = Math . sqrt ( tau ) ; if ( u [ j ] < 0 ) tau = - tau ; return tau ; }
Normalizes elements in u by dividing by max and computes the norm2 of the normalized array u . Adjust the sign of the returned value depending on the size of the first element in u . Normalization is done to avoid overflow .
180
47
149,173
public static boolean isSameStructure ( DMatrixSparseCSC a , DMatrixSparseCSC b ) { if ( a . numRows == b . numRows && a . numCols == b . numCols && a . nz_length == b . nz_length ) { for ( int i = 0 ; i <= a . numCols ; i ++ ) { if ( a . col_idx [ i ] != b . col_idx [ i ] ) return false ; } for ( int i = 0 ; i < a . nz_length ; i ++ ) { if ( a . nz_rows [ i ] != b . nz_rows [ i ] ) return false ; } return true ; } return false ; }
Checks to see if the two matrices have the same shape and same pattern of non - zero elements
167
21
149,174
public static boolean isVector ( DMatrixSparseCSC a ) { return ( a . numCols == 1 && a . numRows > 1 ) || ( a . numRows == 1 && a . numCols > 1 ) ; }
Returns true if the input is a vector
54
8
149,175
public static boolean isSymmetric ( DMatrixSparseCSC A , double tol ) { if ( A . numRows != A . numCols ) return false ; int N = A . numCols ; for ( int i = 0 ; i < N ; i ++ ) { int idx0 = A . col_idx [ i ] ; int idx1 = A . col_idx [ i + 1 ] ; for ( int index = idx0 ; index < idx1 ; index ++ ) { int j = A . nz_rows [ index ] ; double value_ji = A . nz_values [ index ] ; double value_ij = A . get ( i , j ) ; if ( Math . abs ( value_ij - value_ji ) > tol ) return false ; } } return true ; }
Checks to see if the matrix is symmetric to within tolerance .
183
14
149,176
public void implicitDoubleStep ( int x1 , int x2 ) { if ( printHumps ) System . out . println ( "Performing implicit double step" ) ; // compute the wilkinson shift double z11 = A . get ( x2 - 1 , x2 - 1 ) ; double z12 = A . get ( x2 - 1 , x2 ) ; double z21 = A . get ( x2 , x2 - 1 ) ; double z22 = A . get ( x2 , x2 ) ; double a11 = A . get ( x1 , x1 ) ; double a21 = A . get ( x1 + 1 , x1 ) ; double a12 = A . get ( x1 , x1 + 1 ) ; double a22 = A . get ( x1 + 1 , x1 + 1 ) ; double a32 = A . get ( x1 + 2 , x1 + 1 ) ; if ( normalize ) { temp [ 0 ] = a11 ; temp [ 1 ] = a21 ; temp [ 2 ] = a12 ; temp [ 3 ] = a22 ; temp [ 4 ] = a32 ; temp [ 5 ] = z11 ; temp [ 6 ] = z22 ; temp [ 7 ] = z12 ; temp [ 8 ] = z21 ; double max = Math . abs ( temp [ 0 ] ) ; for ( int j = 1 ; j < temp . length ; j ++ ) { if ( Math . abs ( temp [ j ] ) > max ) max = Math . abs ( temp [ j ] ) ; } a11 /= max ; a21 /= max ; a12 /= max ; a22 /= max ; a32 /= max ; z11 /= max ; z22 /= max ; z12 /= max ; z21 /= max ; } // these equations are derived when the eigenvalues are extracted from the lower right // 2 by 2 matrix. See page 388 of Fundamentals of Matrix Computations 2nd ed for details. double b11 , b21 , b31 ; if ( useStandardEq ) { b11 = ( ( a11 - z11 ) * ( a11 - z22 ) - z21 * z12 ) / a21 + a12 ; b21 = a11 + a22 - z11 - z22 ; b31 = a32 ; } else { // this is different from the version in the book and seems in my testing to be more resilient to // over flow issues b11 = ( ( a11 - z11 ) * ( a11 - z22 ) - z21 * z12 ) + a12 * a21 ; b21 = ( a11 + a22 - z11 - z22 ) * a21 ; b31 = a32 * a21 ; } performImplicitDoubleStep ( x1 , x2 , b11 , b21 , b31 ) ; }
Performs an implicit double step using the values contained in the lower right hand side of the submatrix for the estimated eigenvector values .
611
29
149,177
public void performImplicitDoubleStep ( int x1 , int x2 , double real , double img ) { double a11 = A . get ( x1 , x1 ) ; double a21 = A . get ( x1 + 1 , x1 ) ; double a12 = A . get ( x1 , x1 + 1 ) ; double a22 = A . get ( x1 + 1 , x1 + 1 ) ; double a32 = A . get ( x1 + 2 , x1 + 1 ) ; double p_plus_t = 2.0 * real ; double p_times_t = real * real + img * img ; double b11 , b21 , b31 ; if ( useStandardEq ) { b11 = ( a11 * a11 - p_plus_t * a11 + p_times_t ) / a21 + a12 ; b21 = a11 + a22 - p_plus_t ; b31 = a32 ; } else { // this is different from the version in the book and seems in my testing to be more resilient to // over flow issues b11 = ( a11 * a11 - p_plus_t * a11 + p_times_t ) + a12 * a21 ; b21 = ( a11 + a22 - p_plus_t ) * a21 ; b31 = a32 * a21 ; } performImplicitDoubleStep ( x1 , x2 , b11 , b21 , b31 ) ; }
Performs an implicit double step given the set of two imaginary eigenvalues provided . Since one eigenvalue is the complex conjugate of the other only one set of real and imaginary numbers is needed .
321
42
149,178
public boolean process ( DMatrixRMaj A , int numSingularValues , DMatrixRMaj nullspace ) { decomposition . decompose ( A ) ; if ( A . numRows > A . numCols ) { Q . reshape ( A . numCols , Math . min ( A . numRows , A . numCols ) ) ; decomposition . getQ ( Q , true ) ; } else { Q . reshape ( A . numCols , A . numCols ) ; decomposition . getQ ( Q , false ) ; } nullspace . reshape ( Q . numRows , numSingularValues ) ; CommonOps_DDRM . extract ( Q , 0 , Q . numRows , Q . numCols - numSingularValues , Q . numCols , nullspace , 0 , 0 ) ; return true ; }
Finds the null space of A
189
7
149,179
public static boolean isInverse ( DMatrixRMaj a , DMatrixRMaj b , double tol ) { if ( a . numRows != b . numRows || a . numCols != b . numCols ) { return false ; } int numRows = a . numRows ; int numCols = a . numCols ; for ( int i = 0 ; i < numRows ; i ++ ) { for ( int j = 0 ; j < numCols ; j ++ ) { double total = 0 ; for ( int k = 0 ; k < numCols ; k ++ ) { total += a . get ( i , k ) * b . get ( k , j ) ; } if ( i == j ) { if ( ! ( Math . abs ( total - 1 ) <= tol ) ) return false ; } else if ( ! ( Math . abs ( total ) <= tol ) ) return false ; } } return true ; }
Checks to see if the two matrices are inverses of each other .
209
17
149,180
public static boolean isRowsLinearIndependent ( DMatrixRMaj A ) { // LU decomposition LUDecomposition < DMatrixRMaj > lu = DecompositionFactory_DDRM . lu ( A . numRows , A . numCols ) ; if ( lu . inputModified ( ) ) A = A . copy ( ) ; if ( ! lu . decompose ( A ) ) throw new RuntimeException ( "Decompositon failed?" ) ; // if they are linearly independent it should not be singular return ! lu . isSingular ( ) ; }
Checks to see if the rows of the provided matrix are linearly independent .
131
16
149,181
public static boolean isConstantVal ( DMatrixRMaj mat , double val , double tol ) { // see if the result is an identity matrix int index = 0 ; for ( int i = 0 ; i < mat . numRows ; i ++ ) { for ( int j = 0 ; j < mat . numCols ; j ++ ) { if ( ! ( Math . abs ( mat . get ( index ++ ) - val ) <= tol ) ) return false ; } } return true ; }
Checks to see if every value in the matrix is the specified value .
107
15
149,182
public static boolean isDiagonalPositive ( DMatrixRMaj a ) { for ( int i = 0 ; i < a . numRows ; i ++ ) { if ( ! ( a . get ( i , i ) >= 0 ) ) return false ; } return true ; }
Checks to see if all the diagonal elements in the matrix are positive .
60
15
149,183
public static int rank ( DMatrixRMaj A , double threshold ) { SingularValueDecomposition_F64 < DMatrixRMaj > svd = DecompositionFactory_DDRM . svd ( A . numRows , A . numCols , false , false , true ) ; if ( svd . inputModified ( ) ) A = A . copy ( ) ; if ( ! svd . decompose ( A ) ) throw new RuntimeException ( "Decomposition failed" ) ; return SingularOps_DDRM . rank ( svd , threshold ) ; }
Computes the rank of a matrix using the specified tolerance .
128
12
149,184
public static int countNonZero ( DMatrixRMaj A ) { int total = 0 ; for ( int row = 0 , index = 0 ; row < A . numRows ; row ++ ) { for ( int col = 0 ; col < A . numCols ; col ++ , index ++ ) { if ( A . data [ index ] != 0 ) { total ++ ; } } } return total ; }
Counts the number of elements in A which are not zero .
87
13
149,185
public static boolean invertSPD ( DMatrixRMaj mat , DMatrixRMaj result ) { if ( mat . numRows != mat . numCols ) throw new IllegalArgumentException ( "Must be a square matrix" ) ; result . reshape ( mat . numRows , mat . numRows ) ; if ( mat . numRows <= UnrolledCholesky_DDRM . MAX ) { // L*L' = A if ( ! UnrolledCholesky_DDRM . lower ( mat , result ) ) return false ; // L = inv(L) TriangularSolver_DDRM . invertLower ( result . data , result . numCols ) ; // inv(A) = inv(L')*inv(L) SpecializedOps_DDRM . multLowerTranA ( result ) ; } else { LinearSolverDense < DMatrixRMaj > solver = LinearSolverFactory_DDRM . chol ( mat . numCols ) ; if ( solver . modifiesA ( ) ) mat = mat . copy ( ) ; if ( ! solver . setA ( mat ) ) return false ; solver . invert ( result ) ; } return true ; }
Matrix inverse for symmetric positive definite matrices . For small matrices an unrolled cholesky is used . Otherwise a standard decomposition .
270
29
149,186
public static DMatrixRMaj identity ( int numRows , int numCols ) { DMatrixRMaj ret = new DMatrixRMaj ( numRows , numCols ) ; int small = numRows < numCols ? numRows : numCols ; for ( int i = 0 ; i < small ; i ++ ) { ret . set ( i , i , 1.0 ) ; } return ret ; }
Creates a rectangular matrix which is zero except along the diagonals .
95
15
149,187
public static void extract ( DMatrix src , int srcY0 , int srcY1 , int srcX0 , int srcX1 , DMatrix dst ) { ( ( ReshapeMatrix ) dst ) . reshape ( srcY1 - srcY0 , srcX1 - srcX0 ) ; extract ( src , srcY0 , srcY1 , srcX0 , srcX1 , dst , 0 , 0 ) ; }
Extract where the destination is reshaped to match the extracted region
94
13
149,188
public static void extract ( DMatrixRMaj src , int rows [ ] , int rowsSize , int cols [ ] , int colsSize , DMatrixRMaj dst ) { if ( rowsSize != dst . numRows || colsSize != dst . numCols ) throw new MatrixDimensionException ( "Unexpected number of rows and/or columns in dst matrix" ) ; int indexDst = 0 ; for ( int i = 0 ; i < rowsSize ; i ++ ) { int indexSrcRow = src . numCols * rows [ i ] ; for ( int j = 0 ; j < colsSize ; j ++ ) { dst . data [ indexDst ++ ] = src . data [ indexSrcRow + cols [ j ] ] ; } } }
Extracts out a matrix from source given a sub matrix with arbitrary rows and columns specified in two array lists
170
22
149,189
public static void extract ( DMatrixRMaj src , int indexes [ ] , int length , DMatrixRMaj dst ) { if ( ! MatrixFeatures_DDRM . isVector ( dst ) ) throw new MatrixDimensionException ( "Dst must be a vector" ) ; if ( length != dst . getNumElements ( ) ) throw new MatrixDimensionException ( "Unexpected number of elements in dst vector" ) ; for ( int i = 0 ; i < length ; i ++ ) { dst . data [ i ] = src . data [ indexes [ i ] ] ; } }
Extracts the elements from the source matrix by their 1D index .
127
15
149,190
public static DMatrixRMaj extractRow ( DMatrixRMaj a , int row , DMatrixRMaj out ) { if ( out == null ) out = new DMatrixRMaj ( 1 , a . numCols ) ; else if ( ! MatrixFeatures_DDRM . isVector ( out ) || out . getNumElements ( ) != a . numCols ) throw new MatrixDimensionException ( "Output must be a vector of length " + a . numCols ) ; System . arraycopy ( a . data , a . getIndex ( row , 0 ) , out . data , 0 , a . numCols ) ; return out ; }
Extracts the row from a matrix .
144
9
149,191
public static DMatrixRMaj extractColumn ( DMatrixRMaj a , int column , DMatrixRMaj out ) { if ( out == null ) out = new DMatrixRMaj ( a . numRows , 1 ) ; else if ( ! MatrixFeatures_DDRM . isVector ( out ) || out . getNumElements ( ) != a . numRows ) throw new MatrixDimensionException ( "Output must be a vector of length " + a . numRows ) ; int index = column ; for ( int i = 0 ; i < a . numRows ; i ++ , index += a . numCols ) { out . data [ i ] = a . data [ index ] ; } return out ; }
Extracts the column from a matrix .
159
9
149,192
public static void removeColumns ( DMatrixRMaj A , int col0 , int col1 ) { if ( col1 < col0 ) { throw new IllegalArgumentException ( "col1 must be >= col0" ) ; } else if ( col0 >= A . numCols || col1 >= A . numCols ) { throw new IllegalArgumentException ( "Columns which are to be removed must be in bounds" ) ; } int step = col1 - col0 + 1 ; int offset = 0 ; for ( int row = 0 , idx = 0 ; row < A . numRows ; row ++ ) { for ( int i = 0 ; i < col0 ; i ++ , idx ++ ) { A . data [ idx ] = A . data [ idx + offset ] ; } offset += step ; for ( int i = col1 + 1 ; i < A . numCols ; i ++ , idx ++ ) { A . data [ idx ] = A . data [ idx + offset ] ; } } A . numCols -= step ; }
Removes columns from the matrix .
234
7
149,193
public static void scaleRow ( double alpha , DMatrixRMaj A , int row ) { int idx = row * A . numCols ; for ( int col = 0 ; col < A . numCols ; col ++ ) { A . data [ idx ++ ] *= alpha ; } }
In - place scaling of a row in A
65
9
149,194
public static void scaleCol ( double alpha , DMatrixRMaj A , int col ) { int idx = col ; for ( int row = 0 ; row < A . numRows ; row ++ , idx += A . numCols ) { A . data [ idx ] *= alpha ; } }
In - place scaling of a column in A
67
9
149,195
public static BMatrixRMaj elementLessThan ( DMatrixRMaj A , double value , BMatrixRMaj output ) { if ( output == null ) { output = new BMatrixRMaj ( A . numRows , A . numCols ) ; } output . reshape ( A . numRows , A . numCols ) ; int N = A . getNumElements ( ) ; for ( int i = 0 ; i < N ; i ++ ) { output . data [ i ] = A . data [ i ] < value ; } return output ; }
Applies the &gt ; operator to each element in A . Results are stored in a boolean matrix .
123
21
149,196
public static DMatrixRMaj elements ( DMatrixRMaj A , BMatrixRMaj marked , DMatrixRMaj output ) { if ( A . numRows != marked . numRows || A . numCols != marked . numCols ) throw new MatrixDimensionException ( "Input matrices must have the same shape" ) ; if ( output == null ) output = new DMatrixRMaj ( 1 , 1 ) ; output . reshape ( countTrue ( marked ) , 1 ) ; int N = A . getNumElements ( ) ; int index = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( marked . data [ i ] ) { output . data [ index ++ ] = A . data [ i ] ; } } return output ; }
Returns a row matrix which contains all the elements in A which are flagged as true in marked
172
18
149,197
public static int countTrue ( BMatrixRMaj A ) { int total = 0 ; int N = A . getNumElements ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A . data [ i ] ) total ++ ; } return total ; }
Counts the number of elements in A which are true
62
11
149,198
public static void symmLowerToFull ( DMatrixRMaj A ) { if ( A . numRows != A . numCols ) throw new MatrixDimensionException ( "Must be a square matrix" ) ; final int cols = A . numCols ; for ( int row = 0 ; row < A . numRows ; row ++ ) { for ( int col = row + 1 ; col < cols ; col ++ ) { A . data [ row * cols + col ] = A . data [ col * cols + row ] ; } } }
Given a symmetric matrix which is represented by a lower triangular matrix convert it back into a full symmetric matrix .
121
23
149,199
public void init ( DMatrixRMaj A ) { if ( A . numRows != A . numCols ) throw new IllegalArgumentException ( "Must be square" ) ; if ( A . numCols != N ) { N = A . numCols ; QT . reshape ( N , N , false ) ; if ( w . length < N ) { w = new double [ N ] ; gammas = new double [ N ] ; b = new double [ N ] ; } } // just copy the top right triangle QT . set ( A ) ; }
If needed declares and sets up internal data structures .
124
10