Search in sources :

Example 11 with ValidateException

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

the class FindInstance method evaluate.

/**
 * Try to find at least one solution for a set of equations (i.e. <code>Equal[...]</code>
 * expressions).
 */
@Override
public IExpr evaluate(final IAST ast, EvalEngine engine) {
    IAST vars = Validate.checkIsVariableOrVariableList(ast, 2, ast.topHead(), engine);
    if (!vars.isPresent()) {
        return F.NIL;
    }
    try {
        boolean formula = false;
        int maxChoices = 1;
        if (ast.argSize() >= 4) {
            maxChoices = ast.arg4().toIntDefault();
            if (maxChoices < 0) {
                maxChoices = 1;
            }
        } else if (ast.argSize() >= 3) {
            maxChoices = ast.arg3().toIntDefault();
            if (maxChoices < 0) {
                maxChoices = 1;
            }
        }
        try {
            if (ast.arg1().isBooleanFormula()) {
                formula = ast.arg1().isBooleanFormula();
                if (ast.isAST2()) {
                    return BooleanFunctions.solveInstances(ast.arg1(), vars, maxChoices);
                }
            }
        } catch (RuntimeException rex) {
        }
        if (ast.argSize() >= 3) {
            if (ast.arg3().equals(S.Booleans) || formula) {
                return BooleanFunctions.solveInstances(ast.arg1(), vars, maxChoices);
            } else if (ast.arg3().equals(S.Integers)) {
                return Solve.solveIntegers(ast, vars, vars, maxChoices, engine);
            }
            LOGGER.log(engine.getLogLevel(), "{}: Booleans domain expected at position 3 instead of {}", ast.topHead(), ast.arg3());
            return F.NIL;
        }
        IASTMutable termsEqualZeroList = Validate.checkEquations(ast, 1);
        return solveEquations(termsEqualZeroList, F.List(), vars, maxChoices, engine);
    } catch (final ValidateException ve) {
        return IOFunctions.printMessage(ast.topHead(), ve, engine);
    } catch (RuntimeException rex) {
        LOGGER.debug("FindInstance.evaluate() failed", rex);
    }
    return F.NIL;
}
Also used : ValidateException(org.matheclipse.core.eval.exception.ValidateException) IAST(org.matheclipse.core.interfaces.IAST) IASTMutable(org.matheclipse.core.interfaces.IASTMutable)

Example 12 with ValidateException

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

the class ND method partialDerivative.

private IExpr partialDerivative(IExpr function, ISymbol variable, int order, IExpr value, EvalEngine engine) {
    double a3Double = Double.NaN;
    try {
        a3Double = value.evalDouble();
    } catch (ValidateException ve) {
    }
    if (Double.isNaN(a3Double)) {
        Complex a3Complex = Complex.NaN;
        a3Complex = value.evalComplex();
        if (a3Complex != null) {
        // FDSFactory<Complex> factory = new FDSFactory<Complex>(ComplexField.getInstance(),
        // 1, order);
        // // FieldDerivativeStructure<Complex> f = factory.variable(0, a3Complex);
        // FiniteDifferencesDifferentiator differentiator =
        // new FiniteDifferencesDifferentiator(15, 0.01);
        // UnivariateDifferentiableFunction f =
        // differentiator.differentiate(new UnaryNumerical(arg1, arg2,
        // EvalEngine.get()));
        // // return F.complexNum(f.getPartialDerivative(order));
        }
    } else {
        DSFactory factory = new DSFactory(1, order);
        FiniteDifferencesDifferentiator differentiator = new FiniteDifferencesDifferentiator(15, 0.01);
        UnivariateDifferentiableFunction f = differentiator.differentiate(new UnaryNumerical(function, variable, EvalEngine.get()));
        return F.num(f.value(factory.variable(0, a3Double)).getPartialDerivative(order));
    }
    return F.NIL;
}
Also used : ValidateException(org.matheclipse.core.eval.exception.ValidateException) UnaryNumerical(org.matheclipse.core.generic.UnaryNumerical) DSFactory(org.hipparchus.analysis.differentiation.DSFactory) UnivariateDifferentiableFunction(org.hipparchus.analysis.differentiation.UnivariateDifferentiableFunction) FiniteDifferencesDifferentiator(org.hipparchus.analysis.differentiation.FiniteDifferencesDifferentiator) Complex(org.hipparchus.complex.Complex)

Example 13 with ValidateException

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

the class PatternMatcherAndInvoker method eval.

/**
 * {@inheritDoc}
 */
@Override
public IExpr eval(final IExpr leftHandSide, EvalEngine engine) {
    if (isRuleWithoutPatterns() && fLhsPatternExpr.equals(leftHandSide)) {
        if (fTypes.length != 0) {
            return F.NIL;
        }
        IExpr result = F.NIL;
        try {
            result = (IExpr) fMethod.invoke(fInstance);
        } catch (ValidateException | IllegalArgumentException | ReflectiveOperationException e) {
            LOGGER.debug("PatternMatcherAndInvoker.eval() failed", e);
        }
        return result != null ? result : F.NIL;
    }
    IPatternMap patternMap = createPatternMap();
    if (fTypes.length != patternMap.size()) {
        return F.NIL;
    }
    patternMap.initPattern();
    if (matchExpr(fLhsPatternExpr, leftHandSide, engine)) {
        List<IExpr> args = patternMap.getValuesAsList();
        try {
            if (args != null) {
                IExpr result = (IExpr) fMethod.invoke(fInstance, args.toArray());
                return result != null ? result : F.NIL;
            }
        } catch (IllegalArgumentException | ReflectiveOperationException e) {
            LOGGER.debug("PatternMatcherAndInvoker.eval() failed", e);
        }
    }
    return F.NIL;
}
Also used : ValidateException(org.matheclipse.core.eval.exception.ValidateException) IExpr(org.matheclipse.core.interfaces.IExpr)

Example 14 with ValidateException

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

the class PredicateQ method isPossibleZeroQ.

public static boolean isPossibleZeroQ(IAST function, boolean fastTest, EvalEngine engine) {
    try {
        VariablesSet varSet = new VariablesSet(function);
        IAST variables = varSet.getVarList();
        if (function.leafCount() < Config.MAX_POSSIBLE_ZERO_LEAFCOUNT / 5) {
            IExpr expr = F.TrigExpand.of(engine, function);
            expr = F.expandAll(expr, true, true);
            expr = engine.evaluate(expr);
            if (!expr.isAST()) {
                return expr.isZero();
            }
            function = (IAST) expr;
        }
        if (variables.isEmpty()) {
            INumber num = function.isNumericFunction(true) ? function.evalNumber() : null;
            if (num == null || !(F.isZero(num.reDoubleValue(), Config.SPECIAL_FUNCTIONS_TOLERANCE) && F.isZero(num.imDoubleValue(), Config.SPECIAL_FUNCTIONS_TOLERANCE))) {
                return false;
            }
            return true;
        } else {
            if (function.isNumericFunction(varSet)) {
                if (function.isFreeAST(h -> isSpecialNumericFunction(h))) {
                    int trueCounter = 0;
                    // 1. step test some special complex numeric values
                    COMPARE_TERNARY possibeZero = isPossibeZeroFixedValues(F.C0, function, variables, engine);
                    if (possibeZero == IExpr.COMPARE_TERNARY.FALSE) {
                        return false;
                    }
                    if (possibeZero == IExpr.COMPARE_TERNARY.TRUE) {
                        trueCounter++;
                    }
                    possibeZero = isPossibeZeroFixedValues(F.C1, function, variables, engine);
                    if (possibeZero == IExpr.COMPARE_TERNARY.FALSE) {
                        return false;
                    }
                    if (possibeZero == IExpr.COMPARE_TERNARY.TRUE) {
                        trueCounter++;
                    }
                    possibeZero = isPossibeZeroFixedValues(F.CN1, function, variables, engine);
                    if (possibeZero == IExpr.COMPARE_TERNARY.FALSE) {
                        return false;
                    }
                    if (possibeZero == IExpr.COMPARE_TERNARY.TRUE) {
                        trueCounter++;
                    }
                    possibeZero = isPossibeZeroFixedValues(F.CI, function, variables, engine);
                    if (possibeZero == IExpr.COMPARE_TERNARY.FALSE) {
                        return false;
                    }
                    if (possibeZero == IExpr.COMPARE_TERNARY.TRUE) {
                        trueCounter++;
                    }
                    possibeZero = isPossibeZeroFixedValues(F.CNI, function, variables, engine);
                    if (possibeZero == IExpr.COMPARE_TERNARY.FALSE) {
                        return false;
                    }
                    if (possibeZero == IExpr.COMPARE_TERNARY.TRUE) {
                        trueCounter++;
                    }
                    if (trueCounter == 5) {
                        // 2. step test some random complex numeric values
                        for (int i = 0; i < 36; i++) {
                            possibeZero = isPossibeZero(function, variables, engine);
                            if (possibeZero == IExpr.COMPARE_TERNARY.FALSE) {
                                return false;
                            }
                            if (possibeZero == IExpr.COMPARE_TERNARY.TRUE) {
                                trueCounter++;
                            }
                        }
                        if (trueCounter > 28) {
                            return true;
                        }
                    }
                    if (fastTest) {
                        return false;
                    }
                }
            }
        }
        IExpr temp = function.replaceAll(x -> // 
        x.isNumericFunction(true) ? IExpr.ofNullable(x.evalNumber()) : F.NIL);
        if (temp.isPresent()) {
            temp = engine.evaluate(temp);
            if (temp.isZero()) {
                return true;
            }
        }
        return isZeroTogether(function, engine);
    } catch (ValidateException ve) {
        LOGGER.debug("PredicateQ.isPossibleZeroQ() failed", ve);
    }
    return false;
}
Also used : ValidateException(org.matheclipse.core.eval.exception.ValidateException) COMPARE_TERNARY(org.matheclipse.core.interfaces.IExpr.COMPARE_TERNARY) INumber(org.matheclipse.core.interfaces.INumber) VariablesSet(org.matheclipse.core.convert.VariablesSet) IAST(org.matheclipse.core.interfaces.IAST) IExpr(org.matheclipse.core.interfaces.IExpr)

Example 15 with ValidateException

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

the class Solve method of.

/**
 * @param ast the <code>Solve(...)</code> ast
 * @param numeric if true, try to find a numerically solution
 * @param engine
 * @return
 */
public static IExpr of(final IAST ast, boolean numeric, EvalEngine engine) {
    boolean[] isNumeric = new boolean[] { numeric };
    try {
        if (ast.arg1().isEmptyList()) {
            return F.list(F.CEmptyList);
        }
        IAST userDefinedVariables = Validate.checkIsVariableOrVariableList(ast, 2, ast.topHead(), engine);
        if (userDefinedVariables.isPresent()) {
            IAST equationVariables = VariablesSet.getVariables(ast.arg1());
            if (userDefinedVariables.isEmpty()) {
                userDefinedVariables = equationVariables;
            }
            ISymbol domain = S.Complexes;
            if (ast.isAST3()) {
                if (!ast.arg3().isSymbol()) {
                    LOGGER.log(engine.getLogLevel(), "{}: domain definition expected at position 3 instead of {}", ast.topHead(), ast.arg3());
                    return F.NIL;
                }
                domain = (ISymbol) ast.arg3();
                if (domain.equals(S.Booleans)) {
                    return BooleanFunctions.solveInstances(ast.arg1(), userDefinedVariables, Integer.MAX_VALUE);
                }
                if (domain.equals(S.Integers)) {
                    return solveIntegers(ast, equationVariables, userDefinedVariables, Integer.MAX_VALUE, engine);
                }
                if (!domain.equals(S.Reals) && !domain.equals(S.Complexes)) {
                    Level level = engine.getLogLevel();
                    LOGGER.log(level, "{}: domain definition expected at position 3 instead of {}", ast.topHead(), domain);
                    return F.NIL;
                }
            }
            IAssumptions oldAssumptions = engine.getAssumptions();
            try {
                IAssumptions assum = setVariablesReals(userDefinedVariables, domain);
                if (assum != null) {
                    engine.setAssumptions(assum);
                }
                IAST termsList = Validate.checkEquationsAndInequations(ast, 1);
                IASTMutable[] lists = SolveUtils.filterSolveLists(termsList, F.NIL, isNumeric);
                boolean numericFlag = isNumeric[0] || numeric;
                if (lists[2].isPresent()) {
                    IExpr result = solveNumeric(lists[2], numericFlag, engine);
                    if (!result.isPresent()) {
                        return IOFunctions.printMessage(ast.topHead(), "nsmet", F.list(ast.topHead()), engine);
                    }
                    return checkDomain(result, domain);
                }
                IASTMutable termsEqualZeroList = lists[0];
                IExpr result = solveRecursive(termsEqualZeroList, lists[1], numericFlag, userDefinedVariables, engine);
                if (!result.isPresent()) {
                    return IOFunctions.printMessage(ast.topHead(), "nsmet", F.list(ast.topHead()), engine);
                }
                return checkDomain(result, domain);
            } finally {
                engine.setAssumptions(oldAssumptions);
            }
        }
    } catch (ValidateException ve) {
        return IOFunctions.printMessage(S.Solve, ve, engine);
    } catch (LimitException e) {
        LOGGER.log(engine.getLogLevel(), S.Solve, e);
    } catch (RuntimeException rex) {
        LOGGER.debug("Solve.of() failed() failed", rex);
    }
    return F.NIL;
}
Also used : ValidateException(org.matheclipse.core.eval.exception.ValidateException) ISymbol(org.matheclipse.core.interfaces.ISymbol) IAssumptions(org.matheclipse.core.eval.util.IAssumptions) Level(org.apache.logging.log4j.Level) IAST(org.matheclipse.core.interfaces.IAST) IASTMutable(org.matheclipse.core.interfaces.IASTMutable) IExpr(org.matheclipse.core.interfaces.IExpr) LimitException(org.matheclipse.core.eval.exception.LimitException)

Aggregations

ValidateException (org.matheclipse.core.eval.exception.ValidateException)16 IAST (org.matheclipse.core.interfaces.IAST)12 IExpr (org.matheclipse.core.interfaces.IExpr)12 IASTMutable (org.matheclipse.core.interfaces.IASTMutable)5 ISymbol (org.matheclipse.core.interfaces.ISymbol)5 FlowControlException (org.matheclipse.core.eval.exception.FlowControlException)4 IASTAppendable (org.matheclipse.core.interfaces.IASTAppendable)4 Complex (org.hipparchus.complex.Complex)3 EvalEngine (org.matheclipse.core.eval.EvalEngine)3 SymjaMathException (org.matheclipse.core.eval.exception.SymjaMathException)3 VariablesSet (org.matheclipse.core.convert.VariablesSet)2 ExprEvaluator (org.matheclipse.core.eval.ExprEvaluator)2 LimitException (org.matheclipse.core.eval.exception.LimitException)2 ASTSeriesData (org.matheclipse.core.expression.ASTSeriesData)2 IBuiltInSymbol (org.matheclipse.core.interfaces.IBuiltInSymbol)2 IEvaluator (org.matheclipse.core.interfaces.IEvaluator)2 SyntaxError (org.matheclipse.parser.client.SyntaxError)2 MathException (org.matheclipse.parser.client.math.MathException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1