Search in sources :

Example 1 with SymjaMathException

use of org.matheclipse.core.eval.exception.SymjaMathException in project symja_android_library by axkr.

the class EvalEngine method evalASTBuiltinFunction.

/**
 * @param symbol
 * @param ast
 * @return <code>F.NIL</code> if no evaluation happened
 */
private IExpr evalASTBuiltinFunction(final ISymbol symbol, IAST ast) {
    final int attributes = symbol.getAttributes();
    if (fEvalLHSMode) {
        if ((ISymbol.HOLDALL & attributes) == ISymbol.HOLDALL) {
            // (i.e. Sin, Cos,...)
            if (!(symbol.equals(S.Set) || symbol.equals(S.SetDelayed) || symbol.equals(S.UpSet) || symbol.equals(S.UpSetDelayed))) {
                return F.NIL;
            }
        } else {
            if ((ISymbol.NUMERICFUNCTION & attributes) != ISymbol.NUMERICFUNCTION) {
                return F.NIL;
            }
        }
    }
    if (!symbol.equals(S.Integrate)) {
        IExpr result;
        if ((result = symbol.evalDownRule(this, ast)).isPresent()) {
            return result;
        }
    }
    if (symbol.isBuiltInSymbol()) {
        final IEvaluator evaluator = ((IBuiltInSymbol) symbol).getEvaluator();
        if (evaluator instanceof IFunctionEvaluator) {
            if (ast.isEvalFlagOn(IAST.BUILT_IN_EVALED) && isSymbolicMode(attributes)) {
                return F.NIL;
            }
            // evaluate a built-in function.
            final IFunctionEvaluator functionEvaluator = (IFunctionEvaluator) evaluator;
            OptionsResult opres = checkBuiltinArguments(ast, functionEvaluator);
            if (opres == null) {
                return F.NIL;
            }
            ast = opres.result;
            try {
                if (evaluator instanceof AbstractFunctionOptionEvaluator) {
                    AbstractFunctionOptionEvaluator optionsEvaluator = (AbstractFunctionOptionEvaluator) evaluator;
                    IExpr result = optionsEvaluator.evaluate(ast, opres.argSize, opres.options, this);
                    if (result.isPresent()) {
                        return result;
                    }
                } else {
                    IExpr result = fNumericMode ? functionEvaluator.numericEval(ast, this) : functionEvaluator.evaluate(ast, this);
                    if (result.isPresent()) {
                        return result;
                    }
                }
            } catch (ValidateException ve) {
                return IOFunctions.printMessage(ast.topHead(), ve, this);
            } catch (FlowControlException e) {
                throw e;
            } catch (SymjaMathException ve) {
                LOGGER.log(getLogLevel(), ast.topHead(), ve);
                return F.NIL;
            }
        // cannot generally set the result as evaluated in built-in function. Especially problems in
        // `togetherMode`
        // if (isSymbolicMode(attributes) && !isTogetherMode()) {
        // ast.addEvalFlags(IAST.BUILT_IN_EVALED);
        // }
        }
    }
    return F.NIL;
}
Also used : IBuiltInSymbol(org.matheclipse.core.interfaces.IBuiltInSymbol) ValidateException(org.matheclipse.core.eval.exception.ValidateException) IEvaluator(org.matheclipse.core.interfaces.IEvaluator) IFunctionEvaluator(org.matheclipse.core.eval.interfaces.IFunctionEvaluator) AbstractFunctionOptionEvaluator(org.matheclipse.core.eval.interfaces.AbstractFunctionOptionEvaluator) FlowControlException(org.matheclipse.core.eval.exception.FlowControlException) IExpr(org.matheclipse.core.interfaces.IExpr) SymjaMathException(org.matheclipse.core.eval.exception.SymjaMathException)

Example 2 with SymjaMathException

use of org.matheclipse.core.eval.exception.SymjaMathException in project symja_android_library by axkr.

the class PlusOp method plus.

/**
 * Add an argument <code>arg</code> to this <code>Plus()</code> expression.
 *
 * @param arg
 * @return <code>F.Indeterminate</code> if the result is indeterminated, <code>F.NIL</code>
 *         otherwise.
 */
public IExpr plus(final IExpr arg) {
    // }
    if (arg.isIndeterminate()) {
        return S.Indeterminate;
    }
    try {
        if (numberValue.isPresent() && numberValue.isDirectedInfinity()) {
            if (numberValue.isComplexInfinity()) {
                if (arg.isDirectedInfinity()) {
                    return S.Indeterminate;
                }
                numberValue = F.CComplexInfinity;
                evaled = true;
                return F.NIL;
            } else if (numberValue.isInfinity()) {
                if (arg.isInfinity()) {
                    evaled = true;
                    return F.NIL;
                }
                if (arg.isDirectedInfinity()) {
                    return S.Indeterminate;
                }
                if (arg.isRealResult()) {
                    evaled = true;
                    return F.NIL;
                }
            } else if (numberValue.isNegativeInfinity()) {
                if (arg.isNegativeInfinity()) {
                    evaled = true;
                    return F.NIL;
                }
                if (arg.isDirectedInfinity()) {
                    // Indeterminate expression `1` encountered.
                    IOFunctions.printMessage(S.Infinity, "indet", F.list(F.Plus(numberValue, arg)), EvalEngine.get());
                    return S.Indeterminate;
                }
                if (arg.isRealResult()) {
                    evaled = true;
                    return F.NIL;
                }
            }
        }
        if (arg.isNumber()) {
            if (arg.isZero()) {
                evaled = true;
                return F.NIL;
            }
            if (!numberValue.isPresent()) {
                numberValue = arg;
                return F.NIL;
            }
            if (numberValue.isNumber()) {
                numberValue = numberValue.plus(arg);
                evaled = true;
                return F.NIL;
            }
            if (numberValue.isInfinity()) {
                if (arg.isNegativeInfinity()) {
                    // Indeterminate expression `1` encountered.
                    IOFunctions.printMessage(S.Infinity, "indet", F.list(F.Plus(numberValue, arg)), EvalEngine.get());
                    return S.Indeterminate;
                }
                numberValue = F.CInfinity;
                evaled = true;
                return F.NIL;
            }
            if (numberValue.isNegativeInfinity()) {
                numberValue = negativeInfinityPlus(arg);
                if (numberValue.isIndeterminate()) {
                    return S.Indeterminate;
                }
                evaled = true;
                return F.NIL;
            }
            return F.NIL;
        } else if (arg.isQuantity()) {
            // if (arg.isQuantity()) {
            if (!numberValue.isPresent()) {
                numberValue = arg;
                return F.NIL;
            }
            IQuantity q = (IQuantity) arg;
            IExpr temp = q.plus(numberValue, true);
            if (temp.isPresent()) {
                evaled = true;
                numberValue = temp;
            } else {
                if (addMerge(q, F.C1)) {
                    evaled = true;
                }
            }
            return F.NIL;
        // }
        } else if (arg.isAST()) {
            final IAST ast = (IAST) arg;
            final int headID = ((IAST) arg).headID();
            if (headID >= ID.DirectedInfinity) {
                switch(headID) {
                    case ID.DirectedInfinity:
                        if (arg.isDirectedInfinity()) {
                            if (!numberValue.isPresent()) {
                                numberValue = arg;
                                if (arg.isComplexInfinity()) {
                                    if (plusMap != null && plusMap.size() > 0) {
                                        evaled = true;
                                    }
                                } else {
                                    if (plusMap != null) {
                                        Iterator<Entry<IExpr, IExpr>> iterator = plusMap.entrySet().iterator();
                                        while (iterator.hasNext()) {
                                            Entry<IExpr, IExpr> entry = iterator.next();
                                            if (entry.getKey().isRealResult()) {
                                                iterator.remove();
                                                evaled = true;
                                            }
                                        }
                                    }
                                }
                                return F.NIL;
                            }
                            if (arg.isInfinity()) {
                                if (numberValue.isNegativeInfinity()) {
                                    // Indeterminate expression `1` encountered.
                                    IOFunctions.printMessage(S.Infinity, "indet", F.list(F.Plus(arg, numberValue)), EvalEngine.get());
                                    return S.Indeterminate;
                                }
                                numberValue = F.CInfinity;
                                evaled = true;
                                return F.NIL;
                            } else if (arg.isNegativeInfinity()) {
                                numberValue = negativeInfinityPlus(numberValue);
                                if (numberValue.isIndeterminate()) {
                                    return S.Indeterminate;
                                }
                                evaled = true;
                                return F.NIL;
                            } else if (arg.isComplexInfinity()) {
                                if (numberValue.isDirectedInfinity()) {
                                    // Indeterminate expression `1` encountered.
                                    IOFunctions.printMessage(S.Infinity, "indet", F.list(F.Plus(arg, numberValue)), EvalEngine.get());
                                    return S.Indeterminate;
                                }
                                numberValue = F.CComplexInfinity;
                                evaled = true;
                                return F.NIL;
                            }
                        }
                        break;
                    case ID.Times:
                        if (ast.size() > 1) {
                            if (ast.arg1().isNumber()) {
                                if (addMerge(ast.rest().oneIdentity1(), ast.arg1())) {
                                    evaled = true;
                                }
                                return F.NIL;
                            }
                            if (addMerge(ast, F.C1)) {
                                evaled = true;
                            }
                        }
                        return F.NIL;
                    case ID.Interval:
                        if (arg.isInterval()) {
                            if (!numberValue.isPresent()) {
                                numberValue = arg;
                                return F.NIL;
                            }
                            IExpr temp;
                            if (numberValue.isInterval()) {
                                temp = IntervalSym.plus((IAST) numberValue, (IAST) arg);
                            } else {
                                temp = IntervalSym.plus(numberValue, (IAST) arg);
                            }
                            if (temp.isPresent()) {
                                numberValue = temp;
                                evaled = true;
                            } else {
                                if (addMerge(arg, F.C1)) {
                                    evaled = true;
                                }
                            }
                            return F.NIL;
                        }
                        break;
                    // break;
                    case ID.SeriesData:
                        if (arg instanceof ASTSeriesData) {
                            if (!numberValue.isPresent()) {
                                numberValue = arg;
                                return F.NIL;
                            }
                            numberValue = ((ASTSeriesData) arg).plus(numberValue);
                            evaled = true;
                            return F.NIL;
                        }
                        break;
                }
            }
        // } else if (!numberValue.isPresent() && arg.isRealResult()) {
        // numberValue = arg;
        // return F.NIL;
        }
        if (addMerge(arg, F.C1)) {
            evaled = true;
        }
    } catch (ValidateException | LimitException e) {
        LOGGER.debug("PlusOp.plus() failed", e);
        throw e;
    } catch (SymjaMathException sme) {
        LOGGER.debug("PlusOp.plus() failed", sme);
    }
    return F.NIL;
}
Also used : ValidateException(org.matheclipse.core.eval.exception.ValidateException) IQuantity(org.matheclipse.core.tensor.qty.IQuantity) Entry(java.util.Map.Entry) ASTSeriesData(org.matheclipse.core.expression.ASTSeriesData) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST) LimitException(org.matheclipse.core.eval.exception.LimitException) SymjaMathException(org.matheclipse.core.eval.exception.SymjaMathException)

Example 3 with SymjaMathException

use of org.matheclipse.core.eval.exception.SymjaMathException in project symja_android_library by axkr.

the class SymjaInterpreter method interpreter.

/**
 * Evaluate the expression assigned to this interpreter.
 *
 * @param function <code>null</code> if you like to evaluate in symbolic mode; &quot;N&quot; if
 *        you like to evaluate in numeric mode
 * @return
 */
public String interpreter(String function) {
    String evalStr = codeString;
    IExpr expr;
    EvalEngine engine = EvalEngine.get();
    EvalEngine.setReset(engine);
    try {
        ExprParser p = new ExprParser(engine, true);
        // throws SyntaxError exception, if syntax isn't valid
        if (function != null) {
            evalStr = function + "(" + codeString + ")";
        }
        expr = p.parse(evalStr);
    } catch (SyntaxError e1) {
        try {
            ExprParser p = new ExprParser(engine);
            // throws SyntaxError exception, if syntax isn't valid
            if (function != null) {
                evalStr = function + "[" + codeString + "]";
            }
            expr = p.parse(evalStr);
        } catch (Exception e2) {
            outStream.println(e2.getMessage());
            return "";
        }
    }
    IExpr result;
    final StringBuilder buf = new StringBuilder();
    try {
        result = evaluate(expr);
        if (result.isPresent()) {
            if (result.equals(S.Null)) {
                return buf.toString();
            }
            if (OutputFormFactory.get(engine.isRelaxedSyntax()).convert(buf, result)) {
                return buf.toString();
            }
        }
        return "ERROR-IN-OUTPUTFORM";
    } catch (SymjaMathException sma) {
        Throwable me = sma.getCause();
        Validate.printException(buf, me);
        if (expr.equals(S.Null)) {
            return buf.toString();
        }
        if (OutputFormFactory.get(engine.isRelaxedSyntax()).convert(buf, expr)) {
            return buf.toString();
        }
    } catch (final RuntimeException re) {
        Throwable me = re.getCause();
        if (me instanceof MathException) {
            Validate.printException(buf, me);
        } else {
            Validate.printException(buf, re);
        }
    } catch (final Exception ex) {
        Validate.printException(buf, ex);
    } catch (final StackOverflowError soe) {
        Validate.printException(buf, soe);
    } catch (final OutOfMemoryError oome) {
        Validate.printException(buf, oome);
    }
    return buf.toString();
}
Also used : ExprParser(org.matheclipse.core.parser.ExprParser) SymjaMathException(org.matheclipse.core.eval.exception.SymjaMathException) MathException(org.matheclipse.parser.client.math.MathException) SymjaMathException(org.matheclipse.core.eval.exception.SymjaMathException) SyntaxError(org.matheclipse.parser.client.SyntaxError) SymjaMathException(org.matheclipse.core.eval.exception.SymjaMathException) MathException(org.matheclipse.parser.client.math.MathException) IExpr(org.matheclipse.core.interfaces.IExpr)

Example 4 with SymjaMathException

use of org.matheclipse.core.eval.exception.SymjaMathException in project symja_android_library by axkr.

the class CoreCallbackFunction method evaluate.

@Override
public double evaluate(DoubleEvaluator doubleEngine, FunctionNode functionNode, double[] args) {
    ASTNode node = functionNode.getNode(0);
    if (node instanceof SymbolNode) {
        AST2Expr ast2Expr = new AST2Expr();
        IExpr head = ast2Expr.convert(node);
        IASTAppendable fun = F.ast(head, args.length);
        fun.appendArgs(0, args.length, i -> F.num(args[i]));
        // for (int i = 0; i < args.length; i++) {
        // fun.append(args[i]);
        // }
        final IExpr result = F.evaln(fun);
        if (result.isReal()) {
            return ((ISignedNumber) result).doubleValue();
        }
    } else if (node instanceof FunctionNode) {
        AST2Expr ast2Expr = new AST2Expr();
        IExpr head = ast2Expr.convert(node);
        IASTAppendable fun = F.ast(head);
        for (int i = 0; i < args.length; i++) {
            fun.append(args[i]);
        }
        final IExpr result = F.evaln(fun);
        if (result.isReal()) {
            return ((ISignedNumber) result).doubleValue();
        }
    }
    throw new SymjaMathException("CoreCallbackFunction#evaluate() not possible for: " + functionNode.toString());
}
Also used : SymbolNode(org.matheclipse.parser.client.ast.SymbolNode) IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) ISignedNumber(org.matheclipse.core.interfaces.ISignedNumber) ASTNode(org.matheclipse.parser.client.ast.ASTNode) FunctionNode(org.matheclipse.parser.client.ast.FunctionNode) IExpr(org.matheclipse.core.interfaces.IExpr) AST2Expr(org.matheclipse.core.convert.AST2Expr) SymjaMathException(org.matheclipse.core.eval.exception.SymjaMathException)

Example 5 with SymjaMathException

use of org.matheclipse.core.eval.exception.SymjaMathException in project symja_android_library by axkr.

the class AbstractAST method evaluate.

/**
 * {@inheritDoc}
 */
@Override
public IExpr evaluate(EvalEngine engine) {
    LOGGER.debug("Evaluate {}", this);
    final IExpr head = head();
    final int argSize = argSize();
    if (head instanceof ISymbol) {
        ISymbol headSymbol = (ISymbol) head;
        Class<?> clazz = headSymbol.getContext().getJavaClass();
        if (clazz != null) {
            String staticMethodName = headSymbol.getSymbolName();
            // try {
            // Method method = clazz.getMethod(staticMethodName);
            // if (Modifier.isStatic(method.getModifiers())) {
            // Parameter[] parameters = method.getParameters();
            // if (parameters.length == argSize()) {
            // Object[] params = JavaFunctions.determineParameters(this, parameters, 1);
            // if (params != null) {
            // Object result;
            // try {
            // result = method.invoke(null, params);
            // if (result instanceof String) {
            // return F.stringx((String) result);
            // }
            // return Object2Expr.convert(result);
            // } catch (IllegalAccessException
            // | IllegalArgumentException
            // | InvocationTargetException e) {
            // // fall through?
            // }
            // }
            // }
            // }
            // 
            // } catch (IllegalArgumentException | NoSuchMethodException | SecurityException e) {
            // // fall through?
            // }
            Method[] methods = clazz.getMethods();
            for (int i = 0; i < methods.length; i++) {
                if (Modifier.isStatic(methods[i].getModifiers())) {
                    if (staticMethodName.equals(methods[i].getName())) {
                        Parameter[] parameters = methods[i].getParameters();
                        if (parameters.length == argSize()) {
                            Object[] params = JavaFunctions.determineParameters(this, parameters, 1);
                            if (params != null) {
                                Object result;
                                try {
                                    result = methods[i].invoke(null, params);
                                    if (result instanceof String) {
                                        return F.stringx((String) result);
                                    }
                                    return Object2Expr.convert(result, false, true);
                                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                                // fall through?
                                }
                            }
                        }
                    }
                }
            }
        }
        if (head instanceof IBuiltInSymbol) {
            final IEvaluator evaluator = ((IBuiltInSymbol) head).getEvaluator();
            if (evaluator instanceof ICoreFunctionEvaluator) {
                try {
                    ICoreFunctionEvaluator functionEvaluator = (ICoreFunctionEvaluator) evaluator;
                    EvalEngine.OptionsResult opres = engine.checkBuiltinArguments(this, functionEvaluator);
                    if (opres == null) {
                        return F.NIL;
                    }
                    IAST ast = opres.result;
                    IBuiltInSymbol header = ((IBuiltInSymbol) head);
                    if ((header.getAttributes() & ISymbol.SEQUENCEHOLD) != ISymbol.SEQUENCEHOLD) {
                        IExpr temp;
                        if ((temp = F.flattenSequence(this)).isPresent()) {
                            return temp;
                        }
                    }
                    if (isBooleanFunction()) {
                        IExpr temp = extractConditionalExpression(false);
                        if (temp.isPresent()) {
                            return temp;
                        }
                    }
                    IExpr evaluateTemp = evalEvaluate(engine);
                    if (evaluateTemp.isPresent()) {
                        return evaluateTemp;
                    }
                    return functionEvaluator.evaluate(ast, engine);
                } catch (ValidateException ve) {
                    return IOFunctions.printMessage(topHead(), ve, engine);
                } catch (FlowControlException e) {
                    throw e;
                } catch (SymjaMathException ve) {
                    LOGGER.log(engine.getLogLevel(), topHead(), ve);
                    return F.NIL;
                }
            }
        }
    }
    if (head.isAssociation() && argSize == 1) {
        return ((IAssociation) head).getValue(arg1());
    }
    final ISymbol symbol = topHead();
    IExpr temp = engine.evalAttributes(symbol, this);
    if (temp.isPresent()) {
        return temp;
    }
    return engine.evalRules(symbol, this);
}
Also used : ValidateException(org.matheclipse.core.eval.exception.ValidateException) ICoreFunctionEvaluator(org.matheclipse.core.eval.interfaces.ICoreFunctionEvaluator) IBuiltInSymbol(org.matheclipse.core.interfaces.IBuiltInSymbol) EvalEngine(org.matheclipse.core.eval.EvalEngine) PatternMatcherEvalEngine(org.matheclipse.core.patternmatching.PatternMatcherEvalEngine) IAST(org.matheclipse.core.interfaces.IAST) IAssociation(org.matheclipse.core.interfaces.IAssociation) ISymbol(org.matheclipse.core.interfaces.ISymbol) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) SymjaMathException(org.matheclipse.core.eval.exception.SymjaMathException) IEvaluator(org.matheclipse.core.interfaces.IEvaluator) FlowControlException(org.matheclipse.core.eval.exception.FlowControlException) Parameter(java.lang.reflect.Parameter) IPatternObject(org.matheclipse.core.interfaces.IPatternObject) IExpr(org.matheclipse.core.interfaces.IExpr)

Aggregations

SymjaMathException (org.matheclipse.core.eval.exception.SymjaMathException)6 IExpr (org.matheclipse.core.interfaces.IExpr)5 ValidateException (org.matheclipse.core.eval.exception.ValidateException)3 FlowControlException (org.matheclipse.core.eval.exception.FlowControlException)2 IAST (org.matheclipse.core.interfaces.IAST)2 IBuiltInSymbol (org.matheclipse.core.interfaces.IBuiltInSymbol)2 IEvaluator (org.matheclipse.core.interfaces.IEvaluator)2 ASTNode (org.matheclipse.parser.client.ast.ASTNode)2 MathException (org.matheclipse.parser.client.math.MathException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 Parameter (java.lang.reflect.Parameter)1 Entry (java.util.Map.Entry)1 AST2Expr (org.matheclipse.core.convert.AST2Expr)1 EvalEngine (org.matheclipse.core.eval.EvalEngine)1 LimitException (org.matheclipse.core.eval.exception.LimitException)1 AbstractFunctionOptionEvaluator (org.matheclipse.core.eval.interfaces.AbstractFunctionOptionEvaluator)1 ICoreFunctionEvaluator (org.matheclipse.core.eval.interfaces.ICoreFunctionEvaluator)1 IFunctionEvaluator (org.matheclipse.core.eval.interfaces.IFunctionEvaluator)1 ASTSeriesData (org.matheclipse.core.expression.ASTSeriesData)1