
water.rapids.ASTApply Maven / Gradle / Ivy
package water.rapids;
import water.*;
import water.fvec.*;
import java.util.ArrayList;
/**
* R's `apply`
*/
public class ASTApply extends ASTOp {
protected static int _margin; // 1 => work on rows; 2 => work on columns
protected static String _fun; // the function to run on the frame
protected static AST[] _fun_args; // any additional args to _fun
static final String VARS[] = new String[]{ "", "ary", "MARGIN", "FUN", "..."};
public ASTApply( ) { super(VARS); }
@Override String opStr(){ return "apply";}
@Override ASTOp make() {return new ASTApply();}
@Override ASTApply parse_impl(Exec E) {
AST ary = E.parse(); // parse the array
AST a = E.parse(); // parse the margin, must be 1 or 2
if( a instanceof ASTNum ) _margin=(int)((ASTNum)a)._d;
else throw new IllegalArgumentException("`MARGIN` must be either 1 or 2, it cannot be both.");
_fun = ((ASTId)E.parse())._id; // parse the function
// parse any additional arguments
ArrayList fun_args = new ArrayList<>();
while( !E.isEnd() )fun_args.add(E.parse());
E.eatEnd();
ASTApply res = (ASTApply)clone();
res._asts = new AST[]{ary};
if (fun_args.size() > 0) _fun_args = fun_args.toArray(new AST[fun_args.size()]);
else _fun_args = null;
return res;
}
@Override void apply(Env env) {
String err="Result of function produced more than a single column!";
final ASTOp FUN = ASTOp.get(_fun); // function never goes on the stack... distinctly not 1st class...
// PEEK everything from the stack (do not POP)
Frame fr2 = null; // results Frame
Frame fr = env.popAry();
// apply FUN to each column;
// assume work is independent of Vec order => otherwise asking for trouble anyways.
// Types of results:
// A single row: Each col produces a single number result.
// A new array: Each column produces a new column
// If a new array, columns must be align'able.
if( _margin == 2) {
double[] row_result;
Vec[] vecs_result;
boolean isRow = false;
Futures fs = new Futures();
Key key;
AppendableVec v=null;
NewChunk chunk=null;
Vec[] vecs = new Vec[fr.numCols()];
for(int i=0;i fun_args = new ArrayList<>();
while(E.skipWS().hasNext()) {
fun_args.add(E.parse());
}
ASTSApply res = (ASTSApply)clone();
res._asts = new AST[]{ary};
if (fun_args.size() > 0) _fun_args = fun_args.toArray(new AST[fun_args.size()]);
return res;
}
@Override void apply(Env env) {
super.apply(env);
}
}
// --------------------------------------------------------------------------
// unique(ary)
// Returns only the unique rows
//class ASTUnique extends ASTddply {
// static final String VARS[] = new String[]{ "", "ary"};
// ASTUnique( ) { super(VARS, new Type[]{Type.ARY, Type.ARY}); }
// @Override String opStr(){ return "unique";}
// @Override ASTOp make() {return new ASTUnique();}
// @Override void apply(Env env, int argcnt, ASTApply apply) {
// Thread cThr = Thread.currentThread();
// Frame fr = env.peekAry();
// int cols[] = new int[fr.numCols()];
// for( int i=0; i
© 2015 - 2025 Weber Informatics LLC | Privacy Policy