_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6000 | DMatrixRMaj.add | train | 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 | {
"resource": ""
} |
q6001 | DMatrixRMaj.get | train | @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 | {
"resource": ""
} |
q6002 | DMatrixRMaj.set | train | 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 | {
"resource": ""
} |
q6003 | LinearSolverChol_DDRB.solve | train | @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 | {
"resource": ""
} |
q6004 | SimpleEVD.getEigenvalues | train | 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 | {
"resource": ""
} |
q6005 | SimpleEVD.getIndexMax | train | 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 | {
"resource": ""
} |
q6006 | SimpleEVD.getIndexMin | train | 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 | {
"resource": ""
} |
q6007 | QrStructuralCounts_DSCC.process | train | 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 | {
"resource": ""
} |
q6008 | QrStructuralCounts_DSCC.init | train | 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 | {
"resource": ""
} |
q6009 | QrStructuralCounts_DSCC.countNonZeroInR | train | 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 | {
"resource": ""
} |
q6010 | QrStructuralCounts_DSCC.countNonZeroInV | train | void countNonZeroInV( int []parent ) {
int []w = gwork.data;
findMinElementIndexInRows(leftmost);
createRowElementLinkedLists(leftmost,w);
countNonZeroUsingLinkedList(parent,w);
} | java | {
"resource": ""
} |
q6011 | QrStructuralCounts_DSCC.countNonZeroUsingLinkedList | train | 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 | {
"resource": ""
} |
q6012 | Equation.alias | train | 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 | {
"resource": ""
} |
q6013 | Equation.alias | train | 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 | {
"resource": ""
} |
q6014 | Equation.alias | train | 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 | {
"resource": ""
} |
q6015 | Equation.aliasGeneric | train | 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 | {
"resource": ""
} |
q6016 | Equation.compile | train | 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 | {
"resource": ""
} |
q6017 | Equation.parseMacro | train | 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 | {
"resource": ""
} |
q6018 | Equation.checkForUnknownVariables | train | 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 | {
"resource": ""
} |
q6019 | Equation.createVariableInferred | train | 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 | {
"resource": ""
} |
q6020 | Equation.parseAssignRange | train | 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 | {
"resource": ""
} |
q6021 | Equation.handleParentheses | train | 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 | {
"resource": ""
} |
q6022 | Equation.parseParameterCommaBlock | train | 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 | {
"resource": ""
} |
q6023 | Equation.parseSubmatrixToExtract | train | 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 | {
"resource": ""
} |
q6024 | Equation.addSubMatrixVariables | train | 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 | {
"resource": ""
} |
q6025 | Equation.parseBlockNoParentheses | train | 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 | {
"resource": ""
} |
q6026 | Equation.stripCommas | train | 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 | {
"resource": ""
} |
q6027 | Equation.parseSequencesWithColons | train | 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 | {
"resource": ""
} |
q6028 | Equation.parseIntegerLists | train | 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 | {
"resource": ""
} |
q6029 | Equation.parseCombineIntegerLists | train | 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 | {
"resource": ""
} |
q6030 | Equation.isVariableInteger | train | private static boolean isVariableInteger(TokenList.Token t) {
if( t == null )
return false;
return t.getScalarType() == VariableScalar.Type.INTEGER;
} | java | {
"resource": ""
} |
q6031 | Equation.parseBracketCreateMatrix | train | 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 | {
"resource": ""
} |
q6032 | Equation.parseNegOp | train | 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 | {
"resource": ""
} |
q6033 | Equation.parseOperationsL | train | 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 | {
"resource": ""
} |
q6034 | Equation.parseOperationsLR | train | 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 | {
"resource": ""
} |
q6035 | Equation.lookupVariable | train | public <T extends Variable> T lookupVariable(String token) {
Variable result = variables.get(token);
return (T)result;
} | java | {
"resource": ""
} |
q6036 | Equation.insertMacros | train | 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 | {
"resource": ""
} |
q6037 | Equation.isTargetOp | train | 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 | {
"resource": ""
} |
q6038 | Equation.isOperatorLR | train | 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 | {
"resource": ""
} |
q6039 | Equation.isReserved | train | 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 | {
"resource": ""
} |
q6040 | Equation.process | train | public Equation process( String equation , boolean debug ) {
compile(equation,true,debug).perform();
return this;
} | java | {
"resource": ""
} |
q6041 | Equation.print | train | 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 | {
"resource": ""
} |
q6042 | QrHelperFunctions_DDRM.computeTauAndDivide | train | 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 | {
"resource": ""
} |
q6043 | MatrixFeatures_DSCC.isSameStructure | train | 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 | {
"resource": ""
} |
q6044 | MatrixFeatures_DSCC.isVector | train | public static boolean isVector(DMatrixSparseCSC a) {
return (a.numCols == 1 && a.numRows > 1) || (a.numRows == 1 && a.numCols>1);
} | java | {
"resource": ""
} |
q6045 | MatrixFeatures_DSCC.isSymmetric | train | 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 | {
"resource": ""
} |
q6046 | WatchedDoubleStepQREigen_DDRM.implicitDoubleStep | train | 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 | {
"resource": ""
} |
q6047 | WatchedDoubleStepQREigen_DDRM.performImplicitDoubleStep | train | 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 | {
"resource": ""
} |
q6048 | SolveNullSpaceQRP_DDRM.process | train | 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 | {
"resource": ""
} |
q6049 | MatrixFeatures_DDRM.isInverse | train | 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 | {
"resource": ""
} |
q6050 | MatrixFeatures_DDRM.isRowsLinearIndependent | train | 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 | {
"resource": ""
} |
q6051 | MatrixFeatures_DDRM.isConstantVal | train | 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 | {
"resource": ""
} |
q6052 | MatrixFeatures_DDRM.isDiagonalPositive | train | 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 | {
"resource": ""
} |
q6053 | MatrixFeatures_DDRM.rank | train | 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 | {
"resource": ""
} |
q6054 | MatrixFeatures_DDRM.countNonZero | train | 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 | {
"resource": ""
} |
q6055 | CommonOps_DDRM.invertSPD | train | 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 | {
"resource": ""
} |
q6056 | CommonOps_DDRM.identity | train | 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 | {
"resource": ""
} |
q6057 | CommonOps_DDRM.extract | train | 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 | {
"resource": ""
} |
q6058 | CommonOps_DDRM.extract | train | 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 | {
"resource": ""
} |
q6059 | CommonOps_DDRM.extract | train | 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 | {
"resource": ""
} |
q6060 | CommonOps_DDRM.extractRow | train | 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 | {
"resource": ""
} |
q6061 | CommonOps_DDRM.extractColumn | train | 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 | {
"resource": ""
} |
q6062 | CommonOps_DDRM.removeColumns | train | 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 | {
"resource": ""
} |
q6063 | CommonOps_DDRM.scaleRow | train | 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 | {
"resource": ""
} |
q6064 | CommonOps_DDRM.scaleCol | train | 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 | {
"resource": ""
} |
q6065 | CommonOps_DDRM.elementLessThan | train | 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 | {
"resource": ""
} |
q6066 | CommonOps_DDRM.elements | train | 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 | {
"resource": ""
} |
q6067 | CommonOps_DDRM.countTrue | train | 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 | {
"resource": ""
} |
q6068 | CommonOps_DDRM.symmLowerToFull | train | 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 | {
"resource": ""
} |
q6069 | TridiagonalDecompositionHouseholderOrig_DDRM.init | train | 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 | {
"resource": ""
} |
q6070 | MatrixMultProduct_DDRM.inner_reorder_lower | train | 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 | {
"resource": ""
} |
q6071 | ComplexMath_F64.pow | train | 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 | {
"resource": ""
} |
q6072 | ComplexMath_F64.sqrt | train | 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 | {
"resource": ""
} |
q6073 | EigenPowerMethod_DDRM.computeDirect | train | 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 | {
"resource": ""
} |
q6074 | EigenPowerMethod_DDRM.checkConverged | train | 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 | {
"resource": ""
} |
q6075 | PrincipalComponentAnalysis.setup | train | public void setup( int numSamples , int sampleSize ) {
mean = new double[ sampleSize ];
A.reshape(numSamples,sampleSize,false);
sampleIndex = 0;
numComponents = -1;
} | java | {
"resource": ""
} |
q6076 | PrincipalComponentAnalysis.getBasisVector | train | 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 | {
"resource": ""
} |
q6077 | PrincipalComponentAnalysis.sampleToEigenSpace | train | 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 | {
"resource": ""
} |
q6078 | PrincipalComponentAnalysis.eigenToSampleSpace | train | 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 | {
"resource": ""
} |
q6079 | PrincipalComponentAnalysis.response | train | 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 | {
"resource": ""
} |
q6080 | DecompositionFactory_DDRM.decomposeSafe | train | 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 | {
"resource": ""
} |
q6081 | CommonOps_DDF2.extractColumn | train | 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 | {
"resource": ""
} |
q6082 | DecompositionFactory_ZDRM.decomposeSafe | train | public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {
if( decomposition.inputModified() ) {
a = a.copy();
}
return decomposition.decompose(a);
} | java | {
"resource": ""
} |
q6083 | TriangularSolver_DDRB.invert | train | 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 | {
"resource": ""
} |
q6084 | RandomMatrices_DDRM.span | train | 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 | {
"resource": ""
} |
q6085 | RandomMatrices_DDRM.insideSpan | train | public static DMatrixRMaj insideSpan(DMatrixRMaj[] span , double min , double max , Random rand ) {
DMatrixRMaj A = new DMatrixRMaj(span.length,1);
DMatrixRMaj B = new DMatrixRMaj(span[0].getNumElements(),1);
for( int i = 0; i < span.length; i++ ) {
B.set(span[i]);
double val = rand.nextDouble()*(max-min)+min;
CommonOps_DDRM.scale(val,B);
CommonOps_DDRM.add(A,B,A);
}
return A;
} | java | {
"resource": ""
} |
q6086 | RandomMatrices_DDRM.diagonal | train | public static DMatrixRMaj diagonal(int N , double min , double max , Random rand ) {
return diagonal(N,N,min,max,rand);
} | java | {
"resource": ""
} |
q6087 | RandomMatrices_DDRM.diagonal | train | public static DMatrixRMaj diagonal(int numRows , int numCols , double min , double max , Random rand ) {
if( max < min )
throw new IllegalArgumentException("The max must be >= the min");
DMatrixRMaj ret = new DMatrixRMaj(numRows,numCols);
int N = Math.min(numRows,numCols);
double r = max-min;
for( int i = 0; i < N; i++ ) {
ret.set(i,i, rand.nextDouble()*r+min);
}
return ret;
} | java | {
"resource": ""
} |
q6088 | RandomMatrices_DDRM.symmetricWithEigenvalues | train | public static DMatrixRMaj symmetricWithEigenvalues(int num, Random rand , double ...eigenvalues ) {
DMatrixRMaj V = RandomMatrices_DDRM.orthogonal(num,num,rand);
DMatrixRMaj D = CommonOps_DDRM.diag(eigenvalues);
DMatrixRMaj temp = new DMatrixRMaj(num,num);
CommonOps_DDRM.mult(V,D,temp);
CommonOps_DDRM.multTransB(temp,V,D);
return D;
} | java | {
"resource": ""
} |
q6089 | RandomMatrices_DDRM.randomBinary | train | public static BMatrixRMaj randomBinary(int numRow , int numCol , Random rand ) {
BMatrixRMaj mat = new BMatrixRMaj(numRow,numCol);
setRandomB(mat, rand);
return mat;
} | java | {
"resource": ""
} |
q6090 | RandomMatrices_DDRM.symmetric | train | public static DMatrixRMaj symmetric(int length, double min, double max, Random rand) {
DMatrixRMaj A = new DMatrixRMaj(length,length);
symmetric(A,min,max,rand);
return A;
} | java | {
"resource": ""
} |
q6091 | RandomMatrices_DDRM.symmetric | train | public static void symmetric(DMatrixRMaj 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++ ) {
for( int j = i; j < length; j++ ) {
double val = rand.nextDouble()*range + min;
A.set(i,j,val);
A.set(j,i,val);
}
}
} | java | {
"resource": ""
} |
q6092 | RandomMatrices_DDRM.triangularUpper | train | public static DMatrixRMaj triangularUpper(int dimen , int hessenberg , double min , double max , Random rand )
{
if( hessenberg < 0 )
throw new RuntimeException("hessenberg must be more than or equal to 0");
double range = max-min;
DMatrixRMaj A = new DMatrixRMaj(dimen,dimen);
for( int i = 0; i < dimen; i++ ) {
int start = i <= hessenberg ? 0 : i-hessenberg;
for( int j = start; j < dimen; j++ ) {
A.set(i,j, rand.nextDouble()*range+min);
}
}
return A;
} | java | {
"resource": ""
} |
q6093 | CovarianceRandomDraw_DDRM.computeLikelihoodP | train | public double computeLikelihoodP() {
double ret = 1.0;
for( int i = 0; i < r.numRows; i++ ) {
double a = r.get(i,0);
ret *= Math.exp(-a*a/2.0);
}
return ret;
} | java | {
"resource": ""
} |
q6094 | SymmetricQRAlgorithmDecomposition_DDRM.decompose | train | @Override
public boolean decompose(DMatrixRMaj orig) {
if( orig.numCols != orig.numRows )
throw new IllegalArgumentException("Matrix must be square.");
if( orig.numCols <= 0 )
return false;
int N = orig.numRows;
// compute a similar tridiagonal matrix
if( !decomp.decompose(orig) )
return false;
if( diag == null || diag.length < N) {
diag = new double[N];
off = new double[N-1];
}
decomp.getDiagonal(diag,off);
// Tell the helper to work with this matrix
helper.init(diag,off,N);
if( computeVectors ) {
if( computeVectorsWithValues ) {
return extractTogether();
} else {
return extractSeparate(N);
}
} else {
return computeEigenValues();
}
} | java | {
"resource": ""
} |
q6095 | SymmetricQRAlgorithmDecomposition_DDRM.computeEigenValues | train | private boolean computeEigenValues() {
// make a copy of the internal tridiagonal matrix data for later use
diagSaved = helper.copyDiag(diagSaved);
offSaved = helper.copyOff(offSaved);
vector.setQ(null);
vector.setFastEigenvalues(true);
// extract the eigenvalues
if( !vector.process(-1,null,null) )
return false;
// save a copy of them since this data structure will be recycled next
values = helper.copyEigenvalues(values);
return true;
} | java | {
"resource": ""
} |
q6096 | LUDecompositionBase_ZDRM.solveL | train | protected void solveL(double[] vv) {
int ii = 0;
for( int i = 0; i < n; i++ ) {
int ip = indx[i];
double sumReal = vv[ip*2];
double sumImg = vv[ip*2+1];
vv[ip*2] = vv[i*2];
vv[ip*2+1] = vv[i*2+1];
if( ii != 0 ) {
// for( int j = ii-1; j < i; j++ )
// sum -= dataLU[i* n +j]*vv[j];
int index = i*stride + (ii-1)*2;
for( int j = ii-1; j < i; j++ ){
double luReal = dataLU[index++];
double luImg = dataLU[index++];
double vvReal = vv[j*2];
double vvImg = vv[j*2+1];
sumReal -= luReal*vvReal - luImg*vvImg;
sumImg -= luReal*vvImg + luImg*vvReal;
}
} else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {
ii=i+1;
}
vv[i*2] = sumReal;
vv[i*2+1] = sumImg;
}
} | java | {
"resource": ""
} |
q6097 | CholeskyBlockHelper_DDRM.decompose | train | public boolean decompose(DMatrixRMaj mat , int indexStart , int n ) {
double m[] = mat.data;
double el_ii;
double div_el_ii=0;
for( int i = 0; i < n; i++ ) {
for( int j = i; j < n; j++ ) {
double sum = m[indexStart+i*mat.numCols+j];
int iEl = i*n;
int jEl = j*n;
int end = iEl+i;
// k = 0:i-1
for( ; iEl<end; iEl++,jEl++ ) {
// sum -= el[i*n+k]*el[j*n+k];
sum -= el[iEl]*el[jEl];
}
if( i == j ) {
// is it positive-definate?
if( sum <= 0.0 )
return false;
el_ii = Math.sqrt(sum);
el[i*n+i] = el_ii;
m[indexStart+i*mat.numCols+i] = el_ii;
div_el_ii = 1.0/el_ii;
} else {
double v = sum*div_el_ii;
el[j*n+i] = v;
m[indexStart+j*mat.numCols+i] = v;
}
}
}
return true;
} | java | {
"resource": ""
} |
q6098 | PermuteArray.createList | train | public static List<int[]> createList( int N )
{
int data[] = new int[ N ];
for( int i = 0; i < data.length; i++ ) {
data[i] = -1;
}
List<int[]> ret = new ArrayList<int[]>();
createList(data,0,-1,ret);
return ret;
} | java | {
"resource": ""
} |
q6099 | PermuteArray.createList | train | private static void createList( int data[], int k , int level , List<int[]> ret )
{
data[k] = level;
if( level < data.length-1 ) {
for( int i = 0; i < data.length; i++ ) {
if( data[i] == -1 ) {
createList(data,i,level+1,ret);
}
}
} else {
int []copy = new int[data.length];
System.arraycopy(data,0,copy,0,data.length);
ret.add(copy);
}
data[k] = -1;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.