addexpression.java
来自「Java 编写的多种数据挖掘算法 包括聚类、分类、预处理等」· Java 代码 · 共 819 行 · 第 1/2 页
JAVA
819 行
Stack operands = new Stack(); for (int i=0;i<m_postFixExpVector.size();i++) { Object nextob = m_postFixExpVector.elementAt(i); if (nextob instanceof NumericOperand) { operands.push(new Double(((NumericOperand)nextob).m_numericConst)); } else if (nextob instanceof AttributeOperand) { double value = vals[((AttributeOperand)nextob).m_attributeIndex]; if (value == Instance.missingValue()) { vals[vals.length-1] = Instance.missingValue(); break; } if (((AttributeOperand)nextob).m_negative) { value = -value; } operands.push(new Double(value)); } else if (nextob instanceof Operator) { char op = ((Operator)nextob).m_operator; if (isUnaryFunction(op)) { double operand = ((Double)operands.pop()).doubleValue(); double result = ((Operator)nextob).applyFunction(operand); operands.push(new Double(result)); } else { double second = ((Double)operands.pop()).doubleValue(); double first = ((Double)operands.pop()).doubleValue(); double result = ((Operator)nextob).applyOperator(first,second); operands.push(new Double(result)); } } else { throw new Exception("Unknown object in postfix vector!"); } } if (operands.size() != 1) { throw new Exception("Problem applying function"); } Double result = ((Double)operands.pop()); if (result.isNaN() || result.isInfinite()) { vals[vals.length-1] = Instance.missingValue(); } else { vals[vals.length-1] = result.doubleValue(); } } /** * Returns true if a token is an operator * @param tok the token to check * @return true if the supplied token is an operator */ private boolean isOperator(char tok) { if (OPERATORS.indexOf(tok) == -1) { return false; } return true; } /** * Returns true if a token is a unary function * @param tok the token to check * @return true if the supplied token is a unary function */ private boolean isUnaryFunction(char tok) { if (UNARY_FUNCTIONS.indexOf(tok) == -1) { return false; } return true; } /** * Return the infix priority of an operator * @param opp the operator * @return the infix priority */ private int infixPriority(char opp) { switch (opp) { case 'l' : case 'b' : case 'c' : case 'e' : case 's' : case 'f' : case 'h' : case 'r' : case 't' : case 'n' : return 3; case '^' : return 2; case '*' : return 2; case '/' : return 2; case '+' : return 1; case '-' : return 1; case '(' : return 4; case ')' : return 0; default : throw new IllegalArgumentException("Unrecognized operator:" + opp); } } /** * Return the stack priority of an operator * @param opp the operator * @return the stack priority */ private int stackPriority(char opp) { switch (opp) { case 'l' : case 'b' : case 'c' : case 'e' : case 's' : case 'f' : case 'h' : case 'r' : case 't' : case 'n' : return 3; case '^' : return 2; case '*' : return 2; case '/' : return 2; case '+' : return 1; case '-' : return 1; case '(' : return 0; case ')' : return -1; default : throw new IllegalArgumentException("Unrecognized operator:" + opp); } } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector newVector = new Vector(3); newVector.addElement(new Option( "\tSpecify the expression to apply. Eg a1^2*a5/log(a7*4.0)." +"\n\tSupported opperators: ,+, -, *, /, ^, log, abs, cos, " +"\n\texp, sqrt, floor, ceil, rint, tan, sin, (, )", "E",1,"-E <expression>")); newVector.addElement(new Option( "\tSpecify the name for the new attribute. (default is the " +"expression provided with -E)", "N",1,"-N <name>")); newVector.addElement(new Option( "\tDebug. Names attribute with the postfix parse of the " +"expression.","D",0,"-D")); return newVector.elements(); } /** * Parses a given list of options. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -E <expression> * Specify the expression to apply. Eg a1^2*a5/log(a7*4.0). * Supported opperators: ,+, -, *, /, ^, log, abs, cos, * exp, sqrt, floor, ceil, rint, tan, sin, (, )</pre> * * <pre> -N <name> * Specify the name for the new attribute. (default is the expression provided with -E)</pre> * * <pre> -D * Debug. Names attribute with the postfix parse of the expression.</pre> * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String expString = Utils.getOption('E', options); if (expString.length() != 0) { setExpression(expString); } else { throw new Exception("Must specify an expression with the -E option"); } String name = Utils.getOption('N',options); if (name.length() != 0) { setName(name); } setDebug(Utils.getFlag('D', options)); } /** * Gets the current settings of the filter. * * @return an array of strings suitable for passing to setOptions */ public String [] getOptions() { String [] options = new String [5]; int current = 0; options[current++] = "-E"; options[current++] = getExpression(); options[current++] = "-N"; options[current++] = getName(); if (getDebug()) { options[current++] = "-D"; } while (current < options.length) { options[current++] = ""; } return options; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String nameTipText() { return "Set the name of the new attribute."; } /** * Set the name for the new attribute. The string "expression" can * be used to make the name of the new attribute equal to the expression * provided. * @param name the name of the new attribute */ public void setName(String name) { m_attributeName = name; } /** * Returns the name of the new attribute * @return the name of the new attribute */ public String getName() { return m_attributeName; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String debugTipText() { return "Set debug mode. If true then the new attribute will be named with " +"the postfix parse of the supplied expression."; } /** * Set debug mode. Causes the new attribute to be named with the postfix * parse of the expression * @param d true if debug mode is to be used */ public void setDebug(boolean d) { m_Debug = d; } /** * Gets whether debug is set * @return true if debug is set */ public boolean getDebug() { return m_Debug; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String expressionTipText() { return "Set the math expression to apply. Eg. a1^2*a5/log(a7*4.0)"; } /** * Set the expression to apply * @param expr a mathematical expression to apply */ public void setExpression(String expr) { m_infixExpression = expr; } /** * Get the expression * @return the expression */ public String getExpression() { return m_infixExpression; } /** * Sets the format of the input instances. * * @param instanceInfo an Instances object containing the input instance * structure (any instances contained in the object are ignored - only the * structure is required). * @return true if the outputFormat may be collected immediately * @throws Exception if the format couldn't be set successfully */ public boolean setInputFormat(Instances instanceInfo) throws Exception { convertInfixToPostfix(new String(m_infixExpression)); super.setInputFormat(instanceInfo); Instances outputFormat = new Instances(instanceInfo, 0); Attribute newAttribute; if (m_Debug) { newAttribute = new Attribute(m_postFixExpVector.toString()); } else if (m_attributeName.compareTo("expression") != 0) { newAttribute = new Attribute(m_attributeName); } else { newAttribute = new Attribute(m_infixExpression); } outputFormat.insertAttributeAt(newAttribute, instanceInfo.numAttributes()); setOutputFormat(outputFormat); return true; } /** * Input an instance for filtering. Ordinarily the instance is processed * and made available for output immediately. Some filters require all * instances be read before producing output. * * @param instance the input instance * @return true if the filtered instance may now be * collected with output(). * @throws IllegalStateException if no input format has been defined. * @throws Exception if there was a problem during the filtering. */ public boolean input(Instance instance) throws Exception { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } double[] vals = new double[instance.numAttributes()+1]; for(int i = 0; i < instance.numAttributes(); i++) { if (instance.isMissing(i)) { vals[i] = Instance.missingValue(); } else { vals[i] = instance.value(i); } } evaluateExpression(vals); Instance inst = null; if (instance instanceof SparseInstance) { inst = new SparseInstance(instance.weight(), vals); } else { inst = new Instance(instance.weight(), vals); } inst.setDataset(getOutputFormat()); copyValues(inst, false, instance.dataset(), getOutputFormat()); inst.setDataset(getOutputFormat()); push(inst); return true; } /** * Main method for testing this class. * * @param args should contain arguments to the filter: use -h for help */ public static void main(String [] args) { try { if (Utils.getFlag('b', args)) { Filter.batchFilterFile(new AddExpression(), args); } else { Filter.filterFile(new AddExpression(), args); } } catch (Exception ex) { System.out.println(ex.getMessage()); } }}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?