Package adams.flow.transformer
Class MathExpression
-
- All Implemented Interfaces:
AdditionalInformationHandler,CleanUpHandler,Destroyable,GlobalInfoSupporter,LoggingLevelHandler,LoggingSupporter,OptionHandler,QuickInfoSupporter,ShallowCopySupporter<Actor>,SizeOfHandler,Stoppable,StoppableWithFeedback,VariablesInspectionHandler,VariableChangeListener,Actor,ErrorHandler,InputConsumer,OutputProducer,GrammarSupplier,Serializable,Comparable
public class MathExpression extends AbstractTransformer implements GrammarSupplier
Evaluates a mathematical expression.
The input value (double or integer) can be accessed via 'X'.
Variables are supported as well, e.g.: pow(X,@{exp}) with '@{exp}' being a variable available at execution time.
The following grammar is used for the expressions:
expr_list ::= '=' expr_list expr_part | expr_part ;
expr_part ::= expr ;
expr ::= ( expr )
# data types
| number
| string
| boolean
| date
# constants
| true
| false
| pi
| e
| now()
| today()
# negating numeric value
| -expr
# comparisons
| expr < expr
| expr <= expr
| expr > expr
| expr >= expr
| expr = expr
| expr != expr (or: expr <> expr)
# boolean operations
| ! expr (or: not expr)
| expr & expr (or: expr and expr)
| expr | expr (or: expr or expr)
| if[else] ( expr , expr (if true) , expr (if false) )
| ifmissing ( variable , expr (default value if variable is missing) )
| isNaN ( expr )
# arithmetics
| expr + expr
| expr - expr
| expr * expr
| expr / expr
| expr ^ expr (power of)
| expr % expr (modulo)
;
# numeric functions
| abs ( expr )
| sqrt ( expr )
| cbrt ( expr )
| log ( expr )
| log10 ( expr )
| exp ( expr )
| sin ( expr )
| sinh ( expr )
| cos ( expr )
| cosh ( expr )
| tan ( expr )
| tanh ( expr )
| atan ( expr )
| atan2 ( exprY , exprX )
| hypot ( exprX , exprY )
| signum ( expr )
| rint ( expr )
| floor ( expr )
| pow[er] ( expr , expr )
| ceil ( expr )
| min ( expr1 , expr2 )
| max ( expr1 , expr2 )
| year ( expr )
| month ( expr )
| day ( expr )
| hour ( expr )
| minute ( expr )
| second ( expr )
| weekday ( expr )
| weeknum ( expr )
# string functions
| substr ( expr , start [, end] )
| left ( expr , len )
| mid ( expr , start , len )
| right ( expr , len )
| rept ( expr , count )
| concatenate ( expr1 , expr2 [, expr3-5] )
| lower[case] ( expr )
| upper[case] ( expr )
| trim ( expr )
| matches ( expr , regexp )
| trim ( expr )
| len[gth] ( str )
| find ( search , expr [, pos] )
| replace ( str , pos , len , newstr )
| substitute ( str , find , replace [, occurrences] )
;
Notes:
- Variables are either all upper case letters (e.g., "ABC") or any character apart from "]" enclosed by "[" and "]" (e.g., "[Hello World]").
- 'start' and 'end' for function 'substr' are indices that start at 1.
- Index 'end' for function 'substr' is excluded (like Java's 'String.substring(int,int)' method)
- Line comments start with '#'.
- Semi-colons (';') or commas (',') can be used as separator in the formulas,
e.g., 'pow(2,2)' is equivalent to 'pow(2;2)'
- dates have to be of format 'yyyy-MM-dd' or 'yyyy-MM-dd HH:mm:ss'
- times have to be of format 'HH:mm:ss' or 'yyyy-MM-dd HH:mm:ss'
- the characters in square brackets in function names are optional:
e.g. 'len("abc")' is the same as 'length("abc")'
A lot of the functions have been modeled after LibreOffice:
https://help.libreoffice.org/Calc/Functions_by_Category
Additional functions:
- env(String): String
First argument is the name of the environment variable to retrieve.
The result is the value of the environment variable.
Additional procedures:
- println(...)
One or more arguments are printed as comma-separated list to stdout.
If no argument is provided, a simple line feed is output.
Input/output:
- accepts:
java.lang.Integer
java.lang.Long
java.lang.Double
adams.data.report.Report
adams.data.report.ReportHandler
- generates:
java.lang.Double
-logging-level <OFF|SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST> (property: loggingLevel) The logging level for outputting errors and debugging output. default: WARNING
-name <java.lang.String> (property: name) The name of the actor. default: MathExpression
-annotation <adams.core.base.BaseAnnotation> (property: annotations) The annotations to attach to this actor. default:
-skip <boolean> (property: skip) If set to true, transformation is skipped and the input token is just forwarded as it is. default: false
-stop-flow-on-error <boolean> (property: stopFlowOnError) If set to true, the flow gets stopped in case this actor encounters an error; useful for critical actors. default: false
-silent <boolean> (property: silent) If enabled, then no errors are output in the console. default: false
-expression <adams.parser.MathematicalExpressionText> (property: expression) The mathematical expression to evaluate; the input value can be accessed via 'X'. default: X
-output-value-pair <boolean> (property: outputValuePair) If enabled, a double array with X and Y is output and not just Y. default: false
-round-output <boolean> (property: roundOutput) If enabled, the output of the expression is rounding with the specified type of rounding. default: false
-rounding-type <ROUND|CEILING|FLOOR> (property: roundingType) The rounding type to perform on the doubles passing through. default: ROUND
- Version:
- $Revision$
- Author:
- fracpete (fracpete at waikato dot ac dot nz)
- See Also:
MathematicalExpression, Serialized Form
-
-
Field Summary
Fields Modifier and Type Field Description protected MathematicalExpressionTextm_Expressionthe mathematical expression to evaluate.protected intm_NumDecimalsthe number of decimals.protected booleanm_OutputValuePairwhether to output X and Y as double array or just Y.protected RoundingTypem_RoundingTypethe rounding type to perform.protected booleanm_RoundOutputwhether to round the output of the expression.-
Fields inherited from class adams.flow.transformer.AbstractTransformer
BACKUP_INPUT, BACKUP_OUTPUT, m_InputToken, m_OutputToken
-
Fields inherited from class adams.flow.core.AbstractActor
m_Annotations, m_BackupState, m_DetectedObjectVariables, m_DetectedVariables, m_ErrorHandler, m_Executed, m_Executing, m_ExecutionListeningSupporter, m_FullName, m_LoggingPrefix, m_Name, m_Parent, m_ScopeHandler, m_Self, m_Silent, m_Skip, m_StopFlowOnError, m_StopMessage, m_Stopped, m_StorageHandler, m_VariablesUpdated
-
Fields inherited from class adams.core.option.AbstractOptionHandler
m_OptionManager
-
Fields inherited from class adams.core.logging.LoggingObject
m_Logger, m_LoggingIsEnabled, m_LoggingLevel
-
Fields inherited from interface adams.flow.core.Actor
FILE_EXTENSION, FILE_EXTENSION_GZ
-
-
Constructor Summary
Constructors Constructor Description MathExpression()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description Class[]accepts()Returns the class that the consumer accepts.protected DoubleapplyRounding(double value)Applies rounding if necessary.voiddefineOptions()Adds options to the internal list of options.protected StringdoExecute()Executes the flow item.StringexpressionTipText()Returns the tip text for this property.Class[]generates()Returns the class of objects that it generates.MathematicalExpressionTextgetExpression()Returns the mathematical expression to evaluate.StringgetGrammar()Returns a string representation of the grammar.intgetNumDecimals()Returns the number of decimals after the decimal point to use.booleangetOutputValuePair()Returns whether to output a double array with X and Y or just Y.StringgetQuickInfo()Returns a quick info about the actor, which will be displayed in the GUI.RoundingTypegetRoundingType()Returns the roundingType to perform on the doubles.booleangetRoundOutput()Returns whether to round the output of the expression.StringglobalInfo()Returns a string describing the object.StringnumDecimalsTipText()Returns the tip text for this property.StringoutputValuePairTipText()Returns the tip text for this property.StringroundingTypeTipText()Returns the tip text for this property.StringroundOutputTipText()Returns the tip text for this property.voidsetExpression(MathematicalExpressionText value)Sets the mathematical expression to evaluate.voidsetNumDecimals(int value)Sets the number of decimals after the decimal point to use.voidsetOutputValuePair(boolean value)Sets whether to output a double array with X and Y or just Y.voidsetRoundingType(RoundingType value)Sets the roundingType to perform on the doubles.voidsetRoundOutput(boolean value)Sets whether to round the output of the expression.StringsetUp()Initializes the sub-actors for flow execution.-
Methods inherited from class adams.flow.transformer.AbstractTransformer
backupState, currentInput, execute, hasInput, hasPendingOutput, input, output, postExecute, restoreState, wrapUp
-
Methods inherited from class adams.flow.core.AbstractActor
annotationsTipText, canInspectOptions, canPerformSetUpCheck, cleanUp, compareTo, configureLogger, destroy, equals, finalUpdateVariables, findVariables, findVariables, forceVariables, forCommandLine, forName, forName, getAdditionalInformation, getAnnotations, getDefaultName, getDetectedVariables, getErrorHandler, getFlowActors, getFlowExecutionListeningSupporter, getFullName, getName, getNextSibling, getParent, getParentComponent, getPreviousSibling, getRoot, getScopeHandler, getSilent, getSkip, getStopFlowOnError, getStopMessage, getStorageHandler, getVariables, handleError, handleException, hasErrorHandler, hasStopMessage, index, initialize, isBackedUp, isExecuted, isExecuting, isFinished, isHeadless, isStopped, nameTipText, performSetUpChecks, performVariableChecks, preExecute, pruneBackup, pruneBackup, reset, setAnnotations, setErrorHandler, setName, setParent, setSilent, setSkip, setStopFlowOnError, setVariables, shallowCopy, shallowCopy, silentTipText, sizeOf, skipTipText, stopExecution, stopExecution, stopFlowOnErrorTipText, updateDetectedVariables, updatePrefix, updateVariables, variableChanged
-
Methods inherited from class adams.core.option.AbstractOptionHandler
cleanUpOptions, finishInit, getDefaultLoggingLevel, getOptionManager, loggingLevelTipText, newOptionManager, setLoggingLevel, toCommandLine, toString
-
Methods inherited from class adams.core.logging.LoggingObject
getLogger, getLoggingLevel, initializeLogging, isLoggingEnabled
-
Methods inherited from class java.lang.Object
clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface adams.flow.core.Actor
cleanUp, compareTo, destroy, equals, findVariables, getAnnotations, getDefaultName, getDetectedVariables, getErrorHandler, getFlowExecutionListeningSupporter, getFullName, getName, getNextSibling, getParent, getParentComponent, getPreviousSibling, getRoot, getScopeHandler, getSilent, getSkip, getStopFlowOnError, getStopMessage, getStorageHandler, getVariables, handleError, hasErrorHandler, hasStopMessage, index, isExecuted, isFinished, isHeadless, isStopped, setAnnotations, setErrorHandler, setName, setParent, setSilent, setSkip, setStopFlowOnError, setVariables, shallowCopy, shallowCopy, sizeOf, stopExecution, stopExecution, toCommandLine, variableChanged
-
Methods inherited from interface adams.core.AdditionalInformationHandler
getAdditionalInformation
-
Methods inherited from interface adams.core.logging.LoggingLevelHandler
getLoggingLevel, setLoggingLevel
-
Methods inherited from interface adams.core.logging.LoggingSupporter
getLogger, isLoggingEnabled
-
Methods inherited from interface adams.core.option.OptionHandler
cleanUpOptions, getOptionManager
-
Methods inherited from interface adams.core.VariablesInspectionHandler
canInspectOptions
-
-
-
-
Field Detail
-
m_Expression
protected MathematicalExpressionText m_Expression
the mathematical expression to evaluate.
-
m_OutputValuePair
protected boolean m_OutputValuePair
whether to output X and Y as double array or just Y.
-
m_RoundOutput
protected boolean m_RoundOutput
whether to round the output of the expression.
-
m_RoundingType
protected RoundingType m_RoundingType
the rounding type to perform.
-
m_NumDecimals
protected int m_NumDecimals
the number of decimals.
-
-
Method Detail
-
globalInfo
public String globalInfo()
Returns a string describing the object.- Specified by:
globalInfoin interfaceGlobalInfoSupporter- Specified by:
globalInfoin classAbstractOptionHandler- Returns:
- a description suitable for displaying in the gui
-
getGrammar
public String getGrammar()
Returns a string representation of the grammar.- Specified by:
getGrammarin interfaceGrammarSupplier- Returns:
- the grammar, null if not available
-
defineOptions
public void defineOptions()
Adds options to the internal list of options.- Specified by:
defineOptionsin interfaceOptionHandler- Overrides:
defineOptionsin classAbstractActor
-
getQuickInfo
public String getQuickInfo()
Returns a quick info about the actor, which will be displayed in the GUI.- Specified by:
getQuickInfoin interfaceActor- Specified by:
getQuickInfoin interfaceQuickInfoSupporter- Overrides:
getQuickInfoin classAbstractActor- Returns:
- null if no info available, otherwise short string
-
setExpression
public void setExpression(MathematicalExpressionText value)
Sets the mathematical expression to evaluate.- Parameters:
value- the expression
-
getExpression
public MathematicalExpressionText getExpression()
Returns the mathematical expression to evaluate.- Returns:
- the expression
-
expressionTipText
public String expressionTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setOutputValuePair
public void setOutputValuePair(boolean value)
Sets whether to output a double array with X and Y or just Y.- Parameters:
value- if true then X and Y are output
-
getOutputValuePair
public boolean getOutputValuePair()
Returns whether to output a double array with X and Y or just Y.- Returns:
- true if X and Y are ouput
-
outputValuePairTipText
public String outputValuePairTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setRoundOutput
public void setRoundOutput(boolean value)
Sets whether to round the output of the expression.- Parameters:
value- if true then round output
-
getRoundOutput
public boolean getRoundOutput()
Returns whether to round the output of the expression.- Returns:
- true if to round output
-
roundOutputTipText
public String roundOutputTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setRoundingType
public void setRoundingType(RoundingType value)
Sets the roundingType to perform on the doubles.- Parameters:
value- the roundingType
-
getRoundingType
public RoundingType getRoundingType()
Returns the roundingType to perform on the doubles.- Returns:
- the roundingType
-
roundingTypeTipText
public String roundingTypeTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setNumDecimals
public void setNumDecimals(int value)
Sets the number of decimals after the decimal point to use.- Parameters:
value- the number of decimals
-
getNumDecimals
public int getNumDecimals()
Returns the number of decimals after the decimal point to use.- Returns:
- the number of decimals
-
numDecimalsTipText
public String numDecimalsTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
accepts
public Class[] accepts()
Returns the class that the consumer accepts.- Specified by:
acceptsin interfaceInputConsumer- Returns:
- the accepted classes
-
generates
public Class[] generates()
Returns the class of objects that it generates.- Specified by:
generatesin interfaceOutputProducer- Returns:
- the generated classes
-
setUp
public String setUp()
Initializes the sub-actors for flow execution.- Specified by:
setUpin interfaceActor- Overrides:
setUpin classAbstractActor- Returns:
- null if everything is fine, otherwise error message
- See Also:
AbstractActor.reset()
-
applyRounding
protected Double applyRounding(double value)
Applies rounding if necessary.- Parameters:
value- the value to round- Returns:
- the potentially modified value
- See Also:
getRoundOutput()
-
doExecute
protected String doExecute()
Executes the flow item.- Specified by:
doExecutein classAbstractActor- Returns:
- null if everything is fine, otherwise error message
-
-