code
stringlengths
73
34.1k
label
stringclasses
1 value
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); } }
java
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; } }
java
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); }
java
@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"); } }
java
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 ]; }
java
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."); } } }
java
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; } } }
java
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; } } }
java
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); } }
java
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."); } }
java
public static double normP1( DMatrixRMaj A ) { if( MatrixFeatures_DDRM.isVector(A)) { return CommonOps_DDRM.elementSumAbs(A); } else { return inducedP1(A); } }
java
public static double normP2( DMatrixRMaj A ) { if( MatrixFeatures_DDRM.isVector(A)) { return normF(A); } else { return inducedP2(A); } }
java
public static double fastNormP2( DMatrixRMaj A ) { if( MatrixFeatures_DDRM.isVector(A)) { return fastNormF(A); } else { return inducedP2(A); } }
java
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); } }
java
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; }
java
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); }
java
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]; } }
java
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); }
java
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); }
java
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); }
java
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; }
java
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); } } }
java
public static SimpleMatrix wrap( Matrix internalMat ) { SimpleMatrix ret = new SimpleMatrix(); ret.setMatrix(internalMat); return ret; }
java
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; }
java
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]; } }
java
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; }
java
public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst ) { return ConvertDMatrixStruct.convert(src,dst); }
java
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++]; } } } } }
java
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; }
java
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 ]; } } }
java
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; } } } } } } }
java
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; }
java
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]; } } } } }
java
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); }
java
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); }
java
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--; }
java
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; }
java
@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(); }
java
@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; }
java
public void set( T a ) { if( a.getType() == getType() ) mat.set(a.getMatrix()); else { setMatrix(a.mat.copy()); } }
java
public void set( int row , int col , double value ) { ops.set(mat, row, col, value); }
java
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"); } }
java
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); } }
java
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"); } }
java
public void get( int row , int col , Complex_F64 output ) { ops.get(mat,row,col,output); }
java
public T copy() { T ret = createLike(); ret.getMatrix().set(this.getMatrix()); return ret; }
java
public boolean isIdentical(T a, double tol) { if( a.getType() != getType() ) return false; return ops.isIdentical(mat,a.mat,tol); }
java
public boolean isInBounds(int row, int col) { return row >= 0 && col >= 0 && row < mat.getNumRows() && col < mat.getNumCols(); }
java
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!"); } }
java
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!"); } }
java
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++]; } } } }
java
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); }
java
protected void resize( VariableMatrix mat , int numRows , int numCols ) { if( mat.isTemp() ) { mat.matrix.reshape(numRows,numCols); } }
java
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; }
java
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; }
java
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; }
java
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; }
java
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; }
java
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; }
java
public Token add( Function function ) { Token t = new Token(function); push( t ); return t; }
java
public Token add( Variable variable ) { Token t = new Token(variable); push( t ); return t; }
java
public Token add( Symbol symbol ) { Token t = new Token(symbol); push( t ); return t; }
java
public Token add( String word ) { Token t = new Token(word); push( t ); return t; }
java
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; } }
java
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++; } }
java
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--; }
java
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; }
java
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; } }
java
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; }
java
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; }
java
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; }
java
public int sum() { int total = 0; int N = getNumElements(); for (int i = 0; i < N; i++) { if( data[i] ) total += 1; } return total; }
java
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 ]; } }
java
@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; }
java
@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; }
java
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; } }
java
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; } }
java
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); } }
java
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); } }
java
public boolean nextSplit() { if( numSplits == 0 ) return false; x2 = splits[--numSplits]; if( numSplits > 0 ) x1 = splits[numSplits-1]+1; else x1 = 0; return true; }
java
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(); }
java
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); } }
java
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; }
java
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); } // } }
java
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(); } }
java
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(); } }
java
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)* }
java
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; }
java
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; } } }
java
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); }
java
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]; } }
java
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; }
java
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; }
java
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; }
java
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; } }
java
public static DMatrixSparseCSC diag(double... values ) { int N = values.length; return diag(new DMatrixSparseCSC(N,N,N),values,0,N); }
java
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; } }
java
public static void permutationInverse( int []original , int []inverse , int length ) { for (int i = 0; i < length; i++) { inverse[original[i]] = i; } }
java
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; } } } }
java
public static void removeZeros( DMatrixSparseCSC input , DMatrixSparseCSC output , double tol ) { ImplCommonOps_DSCC.removeZeros(input,output,tol); }
java