Search in sources :

Example 1 with FailedException

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

the class Integrate method integrateByRubiRules.

/**
 * Use the <a href="http://www.apmaths.uwo.ca/~arich/">Rubi - Symbolic Integration Rules</a> to
 * integrate the expression.
 *
 * @param ast
 * @return
 */
private static IExpr integrateByRubiRules(IAST arg1, IExpr x, IAST ast, EvalEngine engine) {
    // EvalEngine engine = EvalEngine.get();
    if (arg1.isFreeAST(s -> s.isSymbol() && ((ISymbol) s).isContext(Context.RUBI))) {
        int limit = engine.getRecursionLimit();
        boolean quietMode = engine.isQuietMode();
        ISymbol head = arg1.topHead();
        if (head.isNumericFunctionAttribute() || INT_RUBI_FUNCTIONS.contains(head) || head.getSymbolName().startsWith("ยง")) {
            boolean newCache = false;
            try {
                if (engine.rememberASTCache != null) {
                    IExpr result = engine.rememberASTCache.getIfPresent(ast);
                    if (result != null) {
                        // &&engine.getRecursionCounter()>0) {
                        if (result.isPresent()) {
                            return result;
                        }
                        return callRestIntegrate(arg1, x, engine);
                    }
                } else {
                    newCache = true;
                    engine.rememberASTCache = CacheBuilder.newBuilder().maximumSize(50).build();
                }
                try {
                    engine.setQuietMode(true);
                    if (limit <= 0 || limit > Config.INTEGRATE_RUBI_RULES_RECURSION_LIMIT) {
                        engine.setRecursionLimit(Config.INTEGRATE_RUBI_RULES_RECURSION_LIMIT);
                    }
                    engine.rememberASTCache.put(ast, F.NIL);
                    IExpr temp = S.Integrate.evalDownRule(EvalEngine.get(), ast);
                    if (temp.isPresent()) {
                        if (temp.equals(ast)) {
                            if (LOGGER.isDebugEnabled()) {
                                engine.setQuietMode(false);
                                IOFunctions.printMessage(S.Integrate, "rubiendless", F.list(temp), engine);
                            }
                            return F.NIL;
                        }
                        if (temp.isAST()) {
                            engine.rememberASTCache.put(ast, temp);
                        }
                        return temp;
                    }
                } catch (RecursionLimitExceeded rle) {
                    // engine.printMessage("Integrate(Rubi recursion): " +
                    // Config.INTEGRATE_RUBI_RULES_RECURSION_LIMIT
                    // + " exceeded: " + ast.toString());
                    engine.setRecursionLimit(limit);
                    LOGGER.log(engine.getLogLevel(), "Integrate(Rubi recursion)", rle);
                    return F.NIL;
                } catch (RuntimeException rex) {
                    engine.setRecursionLimit(limit);
                    LOGGER.log(engine.getLogLevel(), "Integrate Rubi recursion limit {} RuntimeException: {}", Config.INTEGRATE_RUBI_RULES_RECURSION_LIMIT, ast, rex);
                    return F.NIL;
                }
            } catch (AbortException ae) {
                LOGGER.debug("Integrate.integrateByRubiRules() aborted", ae);
            } catch (final FailedException fe) {
                LOGGER.debug("Integrate.integrateByRubiRules() failed", fe);
            } finally {
                engine.setRecursionLimit(limit);
                if (newCache) {
                    engine.rememberASTCache = null;
                }
                engine.setQuietMode(quietMode);
            }
        }
    }
    return F.NIL;
}
Also used : RecursionLimitExceeded(org.matheclipse.core.eval.exception.RecursionLimitExceeded) ISymbol(org.matheclipse.core.interfaces.ISymbol) FailedException(org.matheclipse.core.eval.exception.FailedException) IExpr(org.matheclipse.core.interfaces.IExpr) AbortException(org.matheclipse.core.eval.exception.AbortException)

Example 2 with FailedException

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

the class AJAXQueryServlet method evaluateString.

private String[] evaluateString(EvalEngine engine, final String inputString, final String numericMode, final String function, StringWriter outWriter, StringWriter errorWriter) {
    String input = inputString.trim();
    if (input.length() > 1 && input.charAt(0) == '?') {
        IExpr doc = Documentation.findDocumentation(input);
        return JSONBuilder.createJSONResult(engine, doc, outWriter, errorWriter);
    }
    try {
        EvalEngine.setReset(engine);
        ExprParser parser = new ExprParser(engine, isRelaxedSyntax());
        // throws SyntaxError exception, if syntax isn't valid
        IExpr inExpr = parser.parse(input);
        if (inExpr != null) {
            long numberOfLeaves = inExpr.leafCount();
            if (numberOfLeaves > Config.MAX_INPUT_LEAVES) {
                return JSONBuilder.createJSONError("Input expression too big!");
            }
            if (numericMode.equals("N")) {
                inExpr = F.N(inExpr);
            }
            // inExpr contains the user input from the web interface in
            // internal format now
            StringWriter outBuffer = new StringWriter();
            IExpr outExpr;
            outExpr = evalTopLevel(engine, outBuffer, inExpr);
            if (outExpr != null) {
                if (outExpr.isAST(S.Graphics)) {
                    try {
                        String html = Config.SVG_PAGE;
                        StringBuilder stw = new StringBuilder();
                        GraphicsFunctions.graphicsToSVG((IAST) outExpr, stw);
                        html = StringUtils.replace(html, "`1`", stw.toString());
                        html = StringEscapeUtils.escapeHtml4(html);
                        return JSONBuilder.createJSONJavaScript("<iframe srcdoc=\"" + html + "\" style=\"display: block; width: 100%; height: 100%; border: none;\" ></iframe>");
                    } catch (Exception ex) {
                        LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
                    }
                } else if (outExpr.isASTSizeGE(S.Graphics3D, 2)) {
                    StringBuilder buf = new StringBuilder();
                    if (GraphicsFunctions.renderGraphics3D(buf, (IAST) outExpr, engine)) {
                        try {
                            return JSONBuilder.createGraphics3DIFrame(JSBuilder.GRAPHICS3D_IFRAME_TEMPLATE, buf.toString());
                        } catch (Exception ex) {
                            LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
                        }
                    }
                }
                if (outExpr.isASTSizeGE(S.Show, 2)) {
                    IAST show = (IAST) outExpr;
                    return JSONBuilder.createJSONShow(engine, show);
                } else if (outExpr instanceof GraphExpr) {
                    String javaScriptStr = GraphFunctions.graphToJSForm((GraphExpr) outExpr);
                    if (javaScriptStr != null) {
                        String html = VISJS_IFRAME;
                        html = StringUtils.replace(html, "`1`", javaScriptStr);
                        html = // 
                        StringUtils.replace(// 
                        html, // 
                        "`2`", // 
                        "  var options = { };\n");
                        html = StringEscapeUtils.escapeHtml4(html);
                        return JSONBuilder.createJSONJavaScript("<iframe srcdoc=\"" + html + "\" style=\"display: block; width: 100%; height: 100%; border: none;\" ></iframe>");
                    }
                } else if (outExpr instanceof ASTDataset) {
                    String javaScriptStr = ((ASTDataset) outExpr).datasetToJSForm();
                    if (javaScriptStr != null) {
                        String htmlSnippet = javaScriptStr.trim();
                        // html = StringEscapeUtils.escapeHtml4(html);
                        return JSONBuilder.createJSONHTML(engine, htmlSnippet, outWriter, errorWriter);
                    // return JSONBuilder.createJSONJavaScript(
                    // "<iframe srcdoc=\""
                    // + html
                    // + "\" style=\"display: block; width: 100%; height: 100%;
                    // border: none;\"></iframe>");
                    }
                } else if (outExpr.isAST(S.JSFormData, 3)) {
                    IAST jsFormData = (IAST) outExpr;
                    String jsLibraryType = jsFormData.arg2().toString();
                    if (jsLibraryType.equals("mathcell")) {
                        try {
                            return JSONBuilder.createMathcellIFrame(JSBuilder.MATHCELL_IFRAME_TEMPLATE, jsFormData.arg1().toString());
                        } catch (Exception ex) {
                            LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
                        }
                    } else if (jsLibraryType.equals("jsxgraph")) {
                        try {
                            return JSONBuilder.createJSXGraphIFrame(JSBuilder.JSXGRAPH_IFRAME_TEMPLATE, jsFormData.arg1().toString());
                        } catch (Exception ex) {
                            LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
                        }
                    } else if (jsLibraryType.equals("plotly")) {
                        try {
                            return JSONBuilder.createPlotlyIFrame(JSBuilder.PLOTLY_IFRAME_TEMPLATE, jsFormData.arg1().toString());
                        } catch (Exception ex) {
                            LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
                        }
                    } else if (jsLibraryType.equals("treeform")) {
                        try {
                            String manipulateStr = jsFormData.arg1().toString();
                            String html = VISJS_IFRAME;
                            html = StringUtils.replace(html, "`1`", manipulateStr);
                            html = // 
                            StringUtils.replace(// 
                            html, // 
                            "`2`", "  var options = {\n" + "		  edges: {\n" + "              smooth: {\n" + "                  type: 'cubicBezier',\n" + "                  forceDirection:  'vertical',\n" + "                  roundness: 0.4\n" + "              }\n" + "          },\n" + "          layout: {\n" + "              hierarchical: {\n" + "                  direction: \"UD\"\n" + "              }\n" + "          },\n" + "          nodes: {\n" + "            shape: 'box'\n" + "          },\n" + "          physics:false\n" + // 
                            "      }; ");
                            html = StringEscapeUtils.escapeHtml4(html);
                            return JSONBuilder.createJSONJavaScript("<iframe srcdoc=\"" + html + "\" style=\"display: block; width: 100%; height: 100%; border: none;\" ></iframe>");
                        } catch (Exception ex) {
                            LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
                        }
                    }
                } else if (outExpr.isString()) {
                    IStringX str = (IStringX) outExpr;
                    if (str.getMimeType() == IStringX.TEXT_HTML) {
                        String htmlSnippet = str.toString();
                        String htmlPage = HTML_IFRAME;
                        htmlPage = StringUtils.replace(htmlPage, "`1`", htmlSnippet);
                        return JSONBuilder.createJSONJavaScript("<iframe srcdoc=\"" + htmlPage + "\" style=\"display: block; width: 100%; height: 100%; border: none;\" ></iframe>");
                    }
                }
                return JSONBuilder.createJSONResult(engine, outExpr, outWriter, errorWriter);
            }
            return createOutput(outBuffer, null, engine, function);
        } else {
            return JSONBuilder.createJSONError("Input string parsed to null");
        }
    } catch (AbortException se) {
        return JSONBuilder.createJSONResult(engine, S.$Aborted, outWriter, errorWriter);
    } catch (FailedException se) {
        return JSONBuilder.createJSONResult(engine, S.$Failed, outWriter, errorWriter);
    } catch (SyntaxError se) {
        return JSONBuilder.createJSONSyntaxError(se.getMessage());
    } catch (MathException se) {
        return JSONBuilder.createJSONError(se.getMessage());
    } catch (IOException e) {
        String msg = e.getMessage();
        if (msg != null) {
            return JSONBuilder.createJSONError("IOException occured: " + msg);
        }
        return JSONBuilder.createJSONError("IOException occured");
    } catch (Exception e) {
        // error message
        LOGGER.error("{}.evaluateString() failed", getClass().getSimpleName(), e);
        String msg = e.getMessage();
        if (msg != null) {
            return JSONBuilder.createJSONError("Error in evaluateString: " + msg);
        }
        return JSONBuilder.createJSONError("Error in evaluateString: " + e.getClass().getSimpleName());
    }
}
Also used : ASTDataset(org.matheclipse.io.expression.ASTDataset) IOException(java.io.IOException) ExprParser(org.matheclipse.core.parser.ExprParser) ServletException(javax.servlet.ServletException) MathException(org.matheclipse.parser.client.math.MathException) AbortException(org.matheclipse.core.eval.exception.AbortException) FailedException(org.matheclipse.core.eval.exception.FailedException) IOException(java.io.IOException) StringWriter(java.io.StringWriter) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) SyntaxError(org.matheclipse.parser.client.SyntaxError) FailedException(org.matheclipse.core.eval.exception.FailedException) MathException(org.matheclipse.parser.client.math.MathException) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST) IStringX(org.matheclipse.core.interfaces.IStringX) AbortException(org.matheclipse.core.eval.exception.AbortException)

Example 3 with FailedException

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

the class AbstractRubiTestCase method interpreter.

/**
 * Evaluates the given string-expression and returns the result in <code>OutputForm</code>
 */
public String interpreter(final String inputExpression, final String expectedResult, String manuallyCheckedResult) {
    IExpr result;
    final StringWriter buf = new StringWriter();
    IExpr integral = fEvaluator.parse(inputExpression).first();
    try {
        if (fSeconds <= 0) {
            result = fEvaluator.eval(inputExpression);
        } else {
            EvalEngine engine = fEvaluator.getEvalEngine();
            engine.setSeconds(fSeconds);
            result = fEvaluator.evaluateWithTimeout(inputExpression, fSeconds, TimeUnit.SECONDS, true, new EvalControlledCallable(fEvaluator.getEvalEngine()));
        }
        if (result != null) {
            return printResult(integral, result, expectedResult, manuallyCheckedResult);
        }
    } catch (final AbortException re) {
        return printResult(integral, F.$Aborted, expectedResult, manuallyCheckedResult);
    } catch (final FailedException re) {
        return printResult(integral, F.$Failed, expectedResult, manuallyCheckedResult);
    } catch (final SyntaxError se) {
        String msg = se.getMessage();
        System.err.println(msg);
        System.err.println();
        System.err.flush();
        return "";
    } catch (final RuntimeException re) {
        Throwable me = re.getCause();
        if (me instanceof MathException) {
            Validate.printException(buf, me);
        } else {
            Validate.printException(buf, re);
        }
        System.err.println(buf.toString());
        System.err.flush();
        return "";
    } catch (final Exception e) {
        Validate.printException(buf, e);
        System.err.println(buf.toString());
        System.err.flush();
        return "";
    } catch (final OutOfMemoryError e) {
        Validate.printException(buf, e);
        System.err.println(buf.toString());
        System.err.flush();
        return "";
    } catch (final StackOverflowError e) {
        Validate.printException(buf, e);
        System.err.println(buf.toString());
        System.err.flush();
        return "";
    }
    return buf.toString();
}
Also used : MathException(org.matheclipse.parser.client.math.MathException) AbortException(org.matheclipse.core.eval.exception.AbortException) FailedException(org.matheclipse.core.eval.exception.FailedException) StringWriter(java.io.StringWriter) SyntaxError(org.matheclipse.parser.client.SyntaxError) FailedException(org.matheclipse.core.eval.exception.FailedException) MathException(org.matheclipse.parser.client.math.MathException) EvalEngine(org.matheclipse.core.eval.EvalEngine) EvalControlledCallable(org.matheclipse.core.eval.EvalControlledCallable) IExpr(org.matheclipse.core.interfaces.IExpr) AbortException(org.matheclipse.core.eval.exception.AbortException)

Example 4 with FailedException

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

the class AbstractRubiTestCase method interpreter.

/**
 * Evaluates the given string-expression and returns the result in <code>OutputForm</code>
 */
public String interpreter(final String inputExpression, final String expectedResult, String manuallyCheckedResult) {
    IExpr result;
    final StringWriter buf = new StringWriter();
    try {
        if (fSeconds <= 0) {
            result = fEvaluator.eval(inputExpression);
        } else {
            EvalEngine engine = fEvaluator.getEvalEngine();
            engine.setSeconds(fSeconds);
            result = fEvaluator.evaluateWithTimeout(inputExpression, fSeconds, TimeUnit.SECONDS, true, new EvalControlledCallable(fEvaluator.getEvalEngine()));
        }
        if (result != null) {
            return printResult(result, expectedResult, manuallyCheckedResult);
        }
    } catch (final AbortException re) {
        return printResult(F.$Aborted, expectedResult, manuallyCheckedResult);
    } catch (final FailedException re) {
        return printResult(F.$Failed, expectedResult, manuallyCheckedResult);
    } catch (final SyntaxError se) {
        String msg = se.getMessage();
        System.err.println(msg);
        System.err.println();
        System.err.flush();
        return "";
    } catch (final RuntimeException re) {
        Throwable me = re.getCause();
        if (me instanceof MathException) {
            Validate.printException(buf, me);
        } else {
            Validate.printException(buf, re);
        }
        System.err.println(buf.toString());
        System.err.flush();
        return "";
    } catch (final Exception e) {
        Validate.printException(buf, e);
        System.err.println(buf.toString());
        System.err.flush();
        return "";
    } catch (final OutOfMemoryError e) {
        Validate.printException(buf, e);
        System.err.println(buf.toString());
        System.err.flush();
        return "";
    } catch (final StackOverflowError e) {
        Validate.printException(buf, e);
        System.err.println(buf.toString());
        System.err.flush();
        return "";
    }
    return buf.toString();
}
Also used : MathException(org.matheclipse.parser.client.math.MathException) AbortException(org.matheclipse.core.eval.exception.AbortException) FailedException(org.matheclipse.core.eval.exception.FailedException) StringWriter(java.io.StringWriter) SyntaxError(org.matheclipse.parser.client.SyntaxError) FailedException(org.matheclipse.core.eval.exception.FailedException) MathException(org.matheclipse.parser.client.math.MathException) EvalEngine(org.matheclipse.core.eval.EvalEngine) EvalControlledCallable(org.matheclipse.core.eval.EvalControlledCallable) IExpr(org.matheclipse.core.interfaces.IExpr) AbortException(org.matheclipse.core.eval.exception.AbortException)

Example 5 with FailedException

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

the class SymjaBot method interpreter.

private static String interpreter(final String trimmedInput) {
    ExprEvaluator evaluator = new ExprEvaluator(false, (short) 100);
    IExpr result;
    final StringWriter buf = new StringWriter();
    try {
        if (trimmedInput.length() > 1 && trimmedInput.charAt(0) == '?') {
            StringBuilder docBuf = new StringBuilder();
            Documentation.getMarkdown(docBuf, trimmedInput.substring(1));
            String docString = docBuf.toString();
            if (docString.length() > 0) {
                int indx = docString.indexOf("### Github");
                if (indx > 0) {
                    docString = docString.substring(0, indx);
                }
                return docString;
            }
            Documentation.usageDocumentation(docBuf, trimmedInput.substring(1));
            docString = docBuf.toString();
            if (docString.length() > 0) {
                int indx = docString.indexOf("### Github");
                if (indx > 0) {
                    docString = docString.substring(0, indx);
                }
                return docString;
            }
            return "No help page found";
        }
        System.out.println(trimmedInput);
        result = evaluator.evaluateWithTimeout(trimmedInput, 30, TimeUnit.SECONDS, true, new EvalControlledCallable(evaluator.getEvalEngine()));
        if (result != null) {
            return printResultShortened(trimmedInput, result);
        }
    } catch (final AbortException re) {
        // try {
        return printResultShortened(trimmedInput, S.$Aborted);
    // } catch (IOException e) {
    // Validate.printException(buf, e);
    // stderr.println(buf.toString());
    // stderr.flush();
    // return "";
    // }
    } catch (final FailedException re) {
        // try {
        return printResultShortened(trimmedInput, S.$Failed);
    // } catch (IOException e) {
    // Validate.printException(buf, e);
    // stderr.println(buf.toString());
    // stderr.flush();
    // return "";
    // }
    } catch (final SyntaxError se) {
        String msg = se.getMessage();
        // stderr.flush();
        return msg;
    } catch (final RuntimeException re) {
        Throwable me = re.getCause();
        if (me instanceof MathException) {
            Validate.printException(buf, me);
        } else {
            Validate.printException(buf, re);
        }
        // stderr.flush();
        return "";
    } catch (final Exception e) {
        Validate.printException(buf, e);
        // stderr.flush();
        return "";
    } catch (final OutOfMemoryError e) {
        Validate.printException(buf, e);
        // stderr.flush();
        return "";
    } catch (final StackOverflowError e) {
        Validate.printException(buf, e);
        // stderr.flush();
        return "";
    }
    return buf.toString();
}
Also used : ExprEvaluator(org.matheclipse.core.eval.ExprEvaluator) MathException(org.matheclipse.parser.client.math.MathException) AbortException(org.matheclipse.core.eval.exception.AbortException) FailedException(org.matheclipse.core.eval.exception.FailedException) StringWriter(java.io.StringWriter) SyntaxError(org.matheclipse.parser.client.SyntaxError) FailedException(org.matheclipse.core.eval.exception.FailedException) MathException(org.matheclipse.parser.client.math.MathException) EvalControlledCallable(org.matheclipse.core.eval.EvalControlledCallable) IExpr(org.matheclipse.core.interfaces.IExpr) AbortException(org.matheclipse.core.eval.exception.AbortException)

Aggregations

FailedException (org.matheclipse.core.eval.exception.FailedException)9 IExpr (org.matheclipse.core.interfaces.IExpr)9 AbortException (org.matheclipse.core.eval.exception.AbortException)8 MathException (org.matheclipse.parser.client.math.MathException)7 StringWriter (java.io.StringWriter)6 SyntaxError (org.matheclipse.parser.client.SyntaxError)6 EvalControlledCallable (org.matheclipse.core.eval.EvalControlledCallable)5 IOException (java.io.IOException)4 EvalEngine (org.matheclipse.core.eval.EvalEngine)2 ReturnException (org.matheclipse.core.eval.exception.ReturnException)2 ISymbol (org.matheclipse.core.interfaces.ISymbol)2 ScriptException (javax.script.ScriptException)1 ServletException (javax.servlet.ServletException)1 Level (org.apache.logging.log4j.Level)1 ApfloatRuntimeException (org.apfloat.ApfloatRuntimeException)1 ExprEvaluator (org.matheclipse.core.eval.ExprEvaluator)1 RecursionLimitExceeded (org.matheclipse.core.eval.exception.RecursionLimitExceeded)1 RuleCreationError (org.matheclipse.core.eval.exception.RuleCreationError)1 PatternNested (org.matheclipse.core.expression.PatternNested)1 GraphExpr (org.matheclipse.core.expression.data.GraphExpr)1