Search in sources :

Example 16 with ArgumentTypeException

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

the class JavaScriptFormFactory method convertAST.

@Override
public void convertAST(final StringBuilder buf, final IAST function) {
    if (function.isNumericFunction(true)) {
        try {
            double value = EvalEngine.get().evalDouble(function);
            buf.append("(" + value + ")");
            return;
        } catch (RuntimeException rex) {
        // 
        }
    }
    IExpr head = function.head();
    if (head.isSymbol()) {
        String str = functionHead((ISymbol) head);
        if (str != null) {
            if (function.isASTSizeGE(S.Round, 3)) {
                throw new ArgumentTypeException("Cannot convert to JavaScript: " + function.toString());
            }
            if (function.isAST(S.ArcTan, 3)) {
                // swap arguments for atan2() convention in JavaScript
                IASTMutable arcTan2 = function.copy();
                arcTan2.set(1, function.arg2());
                arcTan2.set(2, function.arg1());
                buf.append("Math.atan2");
                convertArgs(buf, head, arcTan2);
                return;
            }
            buf.append(str);
            convertArgs(buf, head, function);
            return;
        }
        if (javascriptFlavor == USE_MATHCELL && function.headID() < 0) {
            if (Config.FUZZY_PARSER) {
                throw new ArgumentTypeException("Cannot convert to JavaScript. Function head: " + function.head());
            }
            // avoid generating JavaScript eval(head) here
            buf.append("(window[");
            convertInternal(buf, head);
            buf.append("](");
            convertArgs(buf, head, function);
            buf.append("))");
            return;
        }
    }
    if (function.isList()) {
        // interpret List() as javascript array
        buf.append("[");
        for (int i = 1; i < function.size(); i++) {
            convertInternal(buf, function.get(i));
            if (i < function.size() - 1) {
                buf.append(",");
            }
        }
        buf.append("]");
        return;
    }
    if (function.isAST(S.Defer, 2) || function.isAST(S.Evaluate, 2) || function.isAST(S.Hold, 2) || function.isUnevaluated()) {
        convertInternal(buf, function.first());
        return;
    }
    if (javascriptFlavor == USE_MATHCELL) {
        if (function.isPlus() || function.isTimes()) {
            if (function.size() >= 3) {
                for (int i = 1; i < function.size() - 1; i++) {
                    if (function.isPlus()) {
                        buf.append("add(");
                    } else {
                        buf.append("mul(");
                    }
                }
                convertInternal(buf, function.arg1());
                buf.append(",");
                for (int i = 2; i < function.size(); i++) {
                    convertInternal(buf, function.get(i));
                    buf.append(")");
                    if (i < function.size() - 1) {
                        buf.append(",");
                    }
                }
                return;
            }
        } else if (function.isPower()) {
            convertPowerMathcell(buf, function);
            return;
        } else if (function.isInfinity()) {
            buf.append("Number.POSITIVE_INFINITY");
            return;
        } else if (function.isNegativeInfinity()) {
            buf.append("Number.NEGATIVE_INFINITY");
            return;
        } else if (function.head() == S.Log) {
            if (function.isAST1()) {
                IExpr arg1 = function.first();
                buf.append("log(");
                convertInternal(buf, arg1);
                buf.append(", Math.E)");
                return;
            } else if (function.isAST2()) {
                IExpr arg1 = function.first();
                IExpr arg2 = function.second();
                buf.append("log(");
                convertInternal(buf, arg1);
                buf.append(", ");
                convertInternal(buf, arg2);
                buf.append(")");
                return;
            }
        } else if (function.head() == S.Piecewise && function.size() > 1) {
            int[] dim = function.isPiecewise();
            if (dim != null && convertPiecewise(dim, function, buf)) {
                return;
            }
        } else if (function.head() == S.ConditionalExpression && function.size() == 3) {
            convertConditionalExpression(function, buf);
            return;
        } else if (function.head() == S.HeavisideTheta && function.size() >= 2) {
            convertHeavisideTheta(function, buf);
            return;
        }
        IAST piecewiseExpand = Arithmetic.piecewiseExpand(function, S.Reals);
        int[] dim = piecewiseExpand.isPiecewise();
        if (dim != null && convertPiecewise(dim, piecewiseExpand, buf)) {
            return;
        }
    } else {
        if (function.isPower()) {
            convertPower(buf, function);
            return;
        } else if (function.isInfinity()) {
            buf.append("Number.POSITIVE_INFINITY");
            return;
        } else if (function.isNegativeInfinity()) {
            buf.append("Number.NEGATIVE_INFINITY");
            return;
        } else if (function.head() == S.Piecewise && function.size() > 1) {
            int[] dim = function.isPiecewise();
            if (dim != null && convertPiecewise(dim, function, buf)) {
                return;
            }
        } else if (function.head() == S.ConditionalExpression && function.size() == 3) {
            convertConditionalExpression(function, buf);
            return;
        } else if (function.head() == S.Cot && function.size() == 2) {
            buf.append("(1/Math.tan(");
            convertInternal(buf, function.arg1());
            buf.append("))");
            return;
        } else if (function.head() == S.ArcCot && function.size() == 2) {
            buf.append("((Math.PI/2.0)-Math.atan(");
            convertInternal(buf, function.arg1());
            buf.append("))");
            return;
        }
        IAST piecewiseExpand = Arithmetic.piecewiseExpand(function, S.Reals);
        int[] dim = piecewiseExpand.isPiecewise();
        if (dim != null && convertPiecewise(dim, piecewiseExpand, buf)) {
            return;
        }
    }
    if (function.head() == S.If && function.size() >= 3 && function.size() <= 4) {
        // use the ternary operator
        buf.append("((");
        convertInternal(buf, function.arg1());
        buf.append(") ? (");
        convertInternal(buf, function.arg2());
        buf.append(") : ( ");
        if (function.size() == 4) {
            convertInternal(buf, function.arg3());
        } else {
            buf.append("Number.NaN");
        }
        buf.append(" ))");
        return;
    }
    if (function.isAST(S.Missing)) {
        // Missing value
        buf.append("Number.NaN");
        return;
    }
    if (function.headID() > 0) {
        throw new ArgumentTypeException("Cannot convert to JavaScript. Function head: " + function.head());
    }
    convertInternal(buf, head);
    convertArgs(buf, head, function);
}
Also used : IExpr(org.matheclipse.core.interfaces.IExpr) IASTMutable(org.matheclipse.core.interfaces.IASTMutable) IAST(org.matheclipse.core.interfaces.IAST) ArgumentTypeException(org.matheclipse.core.eval.exception.ArgumentTypeException)

Example 17 with ArgumentTypeException

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

the class Functors method rules.

/**
 * Create a functor from the given rules. If <code>astRules</code> is a <code>List[]</code>
 * object, the elements of the list are taken as the rules of the form <code>Rule[lhs, rhs]</code>
 * , otherwise the <code>astRules</code> itself is taken as the <code>Rule[lhs, rhs]</code>.
 *
 * @param astRules a possibly nested list of rules of the form <code>x-&gt;y</code> or <code>
 *     x:&gt;y</code>
 * @return
 */
public static Function<IExpr, IExpr> rules(IAST astRules, EvalEngine engine) {
    final Map<IExpr, IExpr> equalRules;
    IAST rule;
    List<PatternMatcherAndEvaluator> matchers = new ArrayList<PatternMatcherAndEvaluator>();
    if (astRules.isList()) {
        return rulesFromNestedList(astRules, engine, matchers);
    } else {
        if (astRules.isRuleAST()) {
            rule = astRules;
            equalRules = new OpenFixedSizeMap<IExpr, IExpr>(3);
            addRuleToCollection(equalRules, matchers, rule);
        } else {
            throw new ArgumentTypeException("rule expression (x->y or x:>y) expected instead of " + astRules.toString());
        }
        if (matchers.size() > 0) {
            return new RulesPatternFunctor(equalRules, matchers, engine);
        }
        return equalRule(rule);
    }
}
Also used : ArrayList(java.util.ArrayList) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST) PatternMatcherAndEvaluator(org.matheclipse.core.patternmatching.PatternMatcherAndEvaluator) ArgumentTypeException(org.matheclipse.core.eval.exception.ArgumentTypeException)

Example 18 with ArgumentTypeException

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

the class InterpolatingFunctionExpr method evaluate.

public IExpr evaluate(IAST ast, EvalEngine engine) {
    if (ast.head() instanceof InterpolatingFunctionExpr && ast.isAST1()) {
        IExpr arg1 = ast.arg1();
        if (arg1.isComplex() || arg1.isComplexNumeric()) {
            return F.NIL;
        }
        boolean evaled = false;
        try {
            double value = arg1.evalDouble();
            evaled = true;
            if (value < min || value > max) {
                // Input value `1` lies outside the range of data in the interpolating function.
                // Extrapolation will be used.
                IOFunctions.printMessage(ast.topHead(), "dmval", F.list(F.list(arg1)), engine);
            }
        } catch (ArgumentTypeException atex) {
        // fall through for symbolic arguments
        }
        if (ast.head() instanceof HermiteFunctionExpr) {
            if (evaled) {
                InterpolatingFunctionExpr<IAST> function = (InterpolatingFunctionExpr<IAST>) ast.head();
                Object model = function.toData();
                if (model instanceof FieldHermiteInterpolator) {
                    FieldHermiteInterpolator<IExpr> interpolator = (FieldHermiteInterpolator<IExpr>) model;
                    IExpr[] arr = interpolator.value(arg1);
                    if (arr.length == 1) {
                        return arr[0];
                    }
                    return F.List(arr);
                }
            }
            return F.NIL;
        }
        if (ast.head() instanceof ASTFunctionExpr) {
            ASTFunctionExpr function = (ASTFunctionExpr) ast.head();
            Object model = function.toData();
            if (model instanceof IAST) {
                IAST interpolator = (IAST) model;
                return F.unaryAST1(interpolator, arg1);
            }
            return F.NIL;
        }
    }
    return F.NIL;
}
Also used : FieldHermiteInterpolator(org.hipparchus.analysis.interpolation.FieldHermiteInterpolator) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST) ArgumentTypeException(org.matheclipse.core.eval.exception.ArgumentTypeException)

Example 19 with ArgumentTypeException

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

the class QuantityImpl method plus.

@Override
public IExpr plus(final IExpr scalar, boolean nilIfUnevaluated) {
    boolean azero = isZero();
    boolean bzero = scalar.isZero();
    if (azero && !bzero) {
        // 0[m] + X(X!=0) gives X(X!=0)
        return scalar;
    }
    if (!azero && bzero) {
        // X(X!=0) + 0[m] gives X(X!=0)
        return this;
    }
    /**
     * at this point the implication holds: azero == bzero
     */
    if (scalar instanceof IQuantity) {
        IQuantity quantity = (IQuantity) scalar;
        IUnit unit = quantity.unit();
        if (!fData.equals(unit)) {
            IExpr lhs = UnitSystem.SI().apply(this);
            IExpr rhs = UnitSystem.SI().apply(quantity);
            if (!this.equals(lhs) || !quantity.equals(rhs)) {
                return lhs.plus(rhs);
            }
            // `1` and `2` are incompatible units
            throw new ArgumentTypeException("compat", F.list(F.stringx(fData.toString()), F.stringx(unit.toString())));
        }
        if (fData.equals(unit)) {
            // 0[m] + 0[m] gives 0[m]
            return ofUnit(arg1.plus(quantity.value()));
        } else if (azero) {
            // 0[m] + 0[s] gives 0
            return arg1.plus(quantity.value());
        }
    } else // <- scalar is not an instance of Quantity
    if (azero) {
        // 0[kg] + 0 gives 0[kg]
        return this;
    }
    return nilIfUnevaluated ? F.NIL : F.Plus(this, scalar);
}
Also used : IExpr(org.matheclipse.core.interfaces.IExpr) ArgumentTypeException(org.matheclipse.core.eval.exception.ArgumentTypeException)

Example 20 with ArgumentTypeException

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

the class ListLinePlot3D method heightLinePlot.

private IExpr heightLinePlot(IAST heights, IAST plotStyle, EvalEngine engine) {
    final int valuesSize = heights.size();
    IASTAppendable resultList = F.NIL;
    IExpr flattenHeights = engine.evaluate(F.Flatten(heights));
    final double deltaHeight = engine.evaluate(F.Max(flattenHeights).subtract(F.Min(flattenHeights))).evalDouble();
    if (F.isZero(deltaHeight)) {
        // Division by zero `1`.
        throw new ArgumentTypeException("zzdivzero", F.List("- delta height is 0"));
    }
    int lineColorNumber = 1;
    for (int i = 1; i < valuesSize; i++) {
        if (heights.get(i).isAST()) {
            IAST rowList = (IAST) heights.get(i);
            final int rowListSize = rowList.size();
            IASTAppendable lineList = F.ListAlloc(rowListSize);
            for (int j = 1; j < rowListSize; j++) {
                // ListLinePlot3D size is 2.5 × 2.5 × 1 independently from its coordinates
                lineList.append(F.List(F.num(i * 2.5 / valuesSize), F.num(j * 2.5 / rowListSize), rowList.get(j).divide(deltaHeight)));
            }
            final IAST color = GraphicsFunctions.plotStyleColorExpr(lineColorNumber++, plotStyle);
            if (!resultList.isPresent()) {
                resultList = F.ListAlloc(valuesSize);
            }
            resultList.append(color);
            resultList.append(F.Line(lineList));
        }
    }
    return resultList;
}
Also used : IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST) ArgumentTypeException(org.matheclipse.core.eval.exception.ArgumentTypeException)

Aggregations

ArgumentTypeException (org.matheclipse.core.eval.exception.ArgumentTypeException)44 IExpr (org.matheclipse.core.interfaces.IExpr)24 IAST (org.matheclipse.core.interfaces.IAST)16 Complex (org.hipparchus.complex.Complex)11 ISymbol (org.matheclipse.core.interfaces.ISymbol)10 EvalEngine (org.matheclipse.core.eval.EvalEngine)6 UnaryNumerical (org.matheclipse.core.generic.UnaryNumerical)6 UnivariateDifferentiableFunction (org.hipparchus.analysis.differentiation.UnivariateDifferentiableFunction)5 ISignedNumber (org.matheclipse.core.interfaces.ISignedNumber)5 ArrayList (java.util.ArrayList)4 IASTAppendable (org.matheclipse.core.interfaces.IASTAppendable)4 DSFactory (org.hipparchus.analysis.differentiation.DSFactory)3 FiniteDifferencesDifferentiator (org.hipparchus.analysis.differentiation.FiniteDifferencesDifferentiator)3 Config (org.matheclipse.core.basic.Config)3 F (org.matheclipse.core.expression.F)3 IInteger (org.matheclipse.core.interfaces.IInteger)3 INum (org.matheclipse.core.interfaces.INum)3 BisectionSolver (org.hipparchus.analysis.solvers.BisectionSolver)2 LinearConstraint (org.hipparchus.optim.linear.LinearConstraint)2 Gamma (org.hipparchus.special.Gamma)2