code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
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;
}
} | java |
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;
}
} | java |
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");
} | java |
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;
} | java |
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);
} | java |
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;
} | java |
@Override
public boolean setA(DMatrixRBlock A) {
// Extract a lower triangular solution
if( !decomposer.decompose(A) )
return false;
blockLength = A.blockLength;
return true;
} | java |
@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);
}
} | java |
public void growInternal(int amount ) {
int tmp[] = new int[ data.length + amount ];
System.arraycopy(data,0,tmp,0,data.length);
this.data = tmp;
} | java |
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;
} | java |
public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {
if( numRows == numCols )
return linear(numRows);
else
return leastSquares(numRows,numCols);
} | java |
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);
}
}
} | java |
public void setConvergence( int maxIterations , double ftol , double gtol ) {
this.maxIterations = maxIterations;
this.ftol = ftol;
this.gtol = gtol;
} | java |
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);
} | java |
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;
} | java |
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;
} | java |
@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 ];
} | java |
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];
}
}
}
} | java |
@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);
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
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);
} | java |
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");
} | java |
void countNonZeroInV( int []parent ) {
int []w = gwork.data;
findMinElementIndexInRows(leftmost);
createRowElementLinkedLists(leftmost,w);
countNonZeroUsingLinkedList(parent,w);
} | java |
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");
} | java |
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;
}
} | java |
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;
}
} | java |
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]);
}
} | java |
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);
}
} | java |
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;
} | java |
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));
} | java |
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;
}
} | java |
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;
} | java |
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;
} | java |
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");
} | java |
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;
} | java |
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);
} | java |
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");
}
}
} | java |
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;
}
} | java |
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;
}
} | java |
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;
}
} | java |
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;
}
} | java |
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);
}
} | java |
private static boolean isVariableInteger(TokenList.Token t) {
if( t == null )
return false;
return t.getScalarType() == VariableScalar.Type.INTEGER;
} | java |
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 [");
} | java |
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;
}
} | java |
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;
}
} | java |
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;
}
} | java |
public <T extends Variable> T lookupVariable(String token) {
Variable result = variables.get(token);
return (T)result;
} | java |
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;
}
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
public Equation process( String equation , boolean debug ) {
compile(equation,true,debug).perform();
return this;
} | java |
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());
}
} | java |
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;
} | java |
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;
} | java |
public static boolean isVector(DMatrixSparseCSC a) {
return (a.numCols == 1 && a.numRows > 1) || (a.numRows == 1 && a.numCols>1);
} | java |
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;
} | java |
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 );
} | java |
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);
} | java |
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;
} | java |
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;
} | java |
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();
} | java |
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;
} | java |
public static boolean isDiagonalPositive( DMatrixRMaj a ) {
for( int i = 0; i < a.numRows; i++ ) {
if( !(a.get(i,i) >= 0) )
return false;
}
return true;
} | java |
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);
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
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);
} | java |
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]];
}
}
} | java |
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]];
}
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
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;
}
} | java |
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;
}
} | java |
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;
} | java |
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;
} | java |
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;
} | java |
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];
}
}
} | java |
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);
} | java |
public static void inner_reorder_lower(DMatrix1Row A , DMatrix1Row B )
{
final int cols = A.numCols;
B.reshape(cols,cols);
Arrays.fill(B.data,0);
for (int i = 0; i <cols; i++) {
for (int j = 0; j <=i; j++) {
B.data[i*cols+j] += A.data[i]*A.data[j];
}
for (int k = 1; k < A.numRows; k++) {
int indexRow = k*cols;
double valI = A.data[i+indexRow];
int indexB = i*cols;
for (int j = 0; j <= i; j++) {
B.data[indexB++] += valI*A.data[indexRow++];
}
}
}
} | java |
public static void pow(ComplexPolar_F64 a , int N , ComplexPolar_F64 result )
{
result.r = Math.pow(a.r,N);
result.theta = N*a.theta;
} | java |
public static void sqrt(Complex_F64 input, Complex_F64 root)
{
double r = input.getMagnitude();
double a = input.real;
root.real = Math.sqrt((r+a)/2.0);
root.imaginary = Math.sqrt((r-a)/2.0);
if( input.imaginary < 0 )
root.imaginary = -root.imaginary;
} | java |
public boolean computeDirect( DMatrixRMaj A ) {
initPower(A);
boolean converged = false;
for( int i = 0; i < maxIterations && !converged; i++ ) {
// q0.print();
CommonOps_DDRM.mult(A,q0,q1);
double s = NormOps_DDRM.normPInf(q1);
CommonOps_DDRM.divide(q1,s,q2);
converged = checkConverged(A);
}
return converged;
} | java |
private boolean checkConverged(DMatrixRMaj A) {
double worst = 0;
double worst2 = 0;
for( int j = 0; j < A.numRows; j++ ) {
double val = Math.abs(q2.data[j] - q0.data[j]);
if( val > worst ) worst = val;
val = Math.abs(q2.data[j] + q0.data[j]);
if( val > worst2 ) worst2 = val;
}
// swap vectors
DMatrixRMaj temp = q0;
q0 = q2;
q2 = temp;
if( worst < tol )
return true;
else if( worst2 < tol )
return true;
else
return false;
} | java |
public void setup( int numSamples , int sampleSize ) {
mean = new double[ sampleSize ];
A.reshape(numSamples,sampleSize,false);
sampleIndex = 0;
numComponents = -1;
} | java |
public double[] getBasisVector( int which ) {
if( which < 0 || which >= numComponents )
throw new IllegalArgumentException("Invalid component");
DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);
CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);
return v.data;
} | java |
public double[] sampleToEigenSpace( double[] sampleData ) {
if( sampleData.length != A.getNumCols() )
throw new IllegalArgumentException("Unexpected sample length");
DMatrixRMaj mean = DMatrixRMaj.wrap(A.getNumCols(),1,this.mean);
DMatrixRMaj s = new DMatrixRMaj(A.getNumCols(),1,true,sampleData);
DMatrixRMaj r = new DMatrixRMaj(numComponents,1);
CommonOps_DDRM.subtract(s, mean, s);
CommonOps_DDRM.mult(V_t,s,r);
return r.data;
} | java |
public double[] eigenToSampleSpace( double[] eigenData ) {
if( eigenData.length != numComponents )
throw new IllegalArgumentException("Unexpected sample length");
DMatrixRMaj s = new DMatrixRMaj(A.getNumCols(),1);
DMatrixRMaj r = DMatrixRMaj.wrap(numComponents,1,eigenData);
CommonOps_DDRM.multTransA(V_t,r,s);
DMatrixRMaj mean = DMatrixRMaj.wrap(A.getNumCols(),1,this.mean);
CommonOps_DDRM.add(s,mean,s);
return s.data;
} | java |
public double response( double[] sample ) {
if( sample.length != A.numCols )
throw new IllegalArgumentException("Expected input vector to be in sample space");
DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);
DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);
CommonOps_DDRM.mult(V_t,s,dots);
return NormOps_DDRM.normF(dots);
} | java |
public static <T extends DMatrix> boolean decomposeSafe(DecompositionInterface<T> decomp, T M ) {
if( decomp.inputModified() ) {
return decomp.decompose(M.<T>copy());
} else {
return decomp.decompose(M);
}
} | java |
public static DMatrix2 extractColumn( DMatrix2x2 a , int column , DMatrix2 out ) {
if( out == null) out = new DMatrix2();
switch( column ) {
case 0:
out.a1 = a.a11;
out.a2 = a.a21;
break;
case 1:
out.a1 = a.a12;
out.a2 = a.a22;
break;
default:
throw new IllegalArgumentException("Out of bounds column. column = "+column);
}
return out;
} | java |
public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {
if( decomposition.inputModified() ) {
a = a.copy();
}
return decomposition.decompose(a);
} | java |
public static void invert( final int blockLength ,
final boolean upper ,
final DSubmatrixD1 T ,
final DSubmatrixD1 T_inv ,
final double temp[] )
{
if( upper )
throw new IllegalArgumentException("Upper triangular matrices not supported yet");
if( temp.length < blockLength*blockLength )
throw new IllegalArgumentException("Temp must be at least blockLength*blockLength long.");
if( T.row0 != T_inv.row0 || T.row1 != T_inv.row1 || T.col0 != T_inv.col0 || T.col1 != T_inv.col1)
throw new IllegalArgumentException("T and T_inv must be at the same elements in the matrix");
final int M = T.row1-T.row0;
final double dataT[] = T.original.data;
final double dataX[] = T_inv.original.data;
final int offsetT = T.row0*T.original.numCols+M*T.col0;
for( int i = 0; i < M; i += blockLength ) {
int heightT = Math.min(T.row1-(i+T.row0),blockLength);
int indexII = offsetT + T.original.numCols*(i+T.row0) + heightT*(i+T.col0);
for( int j = 0; j < i; j += blockLength ) {
int widthX = Math.min(T.col1-(j+T.col0),blockLength);
for( int w = 0; w < temp.length; w++ ) {
temp[w] = 0;
}
for( int k = j; k < i; k += blockLength ) {
int widthT = Math.min(T.col1-(k+T.col0),blockLength);
int indexL = offsetT + T.original.numCols*(i+T.row0) + heightT*(k+T.col0);
int indexX = offsetT + T.original.numCols*(k+T.row0) + widthT*(j+T.col0);
blockMultMinus(dataT,dataX,temp,indexL,indexX,0,heightT,widthT,widthX);
}
int indexX = offsetT + T.original.numCols*(i+T.row0) + heightT*(j+T.col0);
InnerTriangularSolver_DDRB.solveL(dataT,temp,heightT,widthX,heightT,indexII,0);
System.arraycopy(temp,0,dataX,indexX,widthX*heightT);
}
InnerTriangularSolver_DDRB.invertLower(dataT,dataX,heightT,indexII,indexII);
}
} | java |
public static DMatrixRMaj[] span(int dimen, int numVectors , Random rand ) {
if( dimen < numVectors )
throw new IllegalArgumentException("The number of vectors must be less than or equal to the dimension");
DMatrixRMaj u[] = new DMatrixRMaj[numVectors];
u[0] = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);
NormOps_DDRM.normalizeF(u[0]);
for( int i = 1; i < numVectors; i++ ) {
// System.out.println(" i = "+i);
DMatrixRMaj a = new DMatrixRMaj(dimen,1);
DMatrixRMaj r=null;
for( int j = 0; j < i; j++ ) {
// System.out.println("j = "+j);
if( j == 0 )
r = RandomMatrices_DDRM.rectangle(dimen,1,-1,1,rand);
// find a vector that is normal to vector j
// u[i] = (1/2)*(r + Q[j]*r)
a.set(r);
VectorVectorMult_DDRM.householder(-2.0,u[j],r,a);
CommonOps_DDRM.add(r,a,a);
CommonOps_DDRM.scale(0.5,a);
// UtilEjml.print(a);
DMatrixRMaj t = a;
a = r;
r = t;
// normalize it so it doesn't get too small
double val = NormOps_DDRM.normF(r);
if( val == 0 || Double.isNaN(val) || Double.isInfinite(val))
throw new RuntimeException("Failed sanity check");
CommonOps_DDRM.divide(r,val);
}
u[i] = r;
}
return u;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.