Search in sources :

Example 1 with GraphExpr

use of org.matheclipse.core.expression.data.GraphExpr 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 2 with GraphExpr

use of org.matheclipse.core.expression.data.GraphExpr in project symja_android_library by axkr.

the class SimpleVisGraphExample method main.

// 
public static void main(String[] args) {
    try {
        Config.USE_VISJS = true;
        ExprEvaluator util = new ExprEvaluator();
        // IExpr result = util
        // .eval("Graph({a \\\\[UndirectedEdge] b, b \\\\[UndirectedEdge] c, c \\\\[UndirectedEdge]
        // a})");
        // IExpr result = util.eval("Graph({1 \\\\[DirectedEdge] 2, 2 \\\\[DirectedEdge] 3, 3
        // \\\\[DirectedEdge]
        // 1})");
        // IExpr result = util
        // .eval("Graph({1 \\\\[UndirectedEdge] 2, 2 \\\\[UndirectedEdge] 3, 3 \\\\[UndirectedEdge]
        // 1})");
        IExpr result = util.eval("Graph({1 \\[UndirectedEdge] 2, 2 \\[UndirectedEdge] 3, 3 \\[UndirectedEdge] 1}, {EdgeWeight -> {2, 3, 4}})");
        if (result instanceof GraphExpr) {
            String javaScriptStr = GraphFunctions.graphToJSForm((GraphExpr) result);
            if (javaScriptStr != null) {
                String js = VISJS_PAGE;
                js = StringUtils.replace(js, "`1`", javaScriptStr);
                System.out.println(js);
            }
        }
    } catch (SyntaxError e) {
        // catch Symja parser errors here
        System.out.println(e.getMessage());
    } catch (MathException me) {
        // catch Symja math errors here
        System.out.println(me.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    } catch (final StackOverflowError soe) {
        System.out.println(soe.getMessage());
    } catch (final OutOfMemoryError oome) {
        System.out.println(oome.getMessage());
    }
}
Also used : ExprEvaluator(org.matheclipse.core.eval.ExprEvaluator) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) SyntaxError(org.matheclipse.parser.client.SyntaxError) MathException(org.matheclipse.parser.client.math.MathException) IExpr(org.matheclipse.core.interfaces.IExpr) MathException(org.matheclipse.parser.client.math.MathException)

Example 3 with GraphExpr

use of org.matheclipse.core.expression.data.GraphExpr in project symja_android_library by axkr.

the class Pods method createResult.

public static ObjectNode createResult(String inputStr, int formats, boolean strictSymja) {
    ObjectNode messageJSON = JSON_OBJECT_MAPPER.createObjectNode();
    ObjectNode queryresult = JSON_OBJECT_MAPPER.createObjectNode();
    messageJSON.putPOJO("queryresult", queryresult);
    queryresult.put("success", "false");
    queryresult.put("error", "false");
    queryresult.put("numpods", 0);
    queryresult.put("version", "0.1");
    boolean error = false;
    int numpods = 0;
    IExpr inExpr = S.Null;
    IExpr outExpr = S.Null;
    EvalEngine engine = EvalEngine.get();
    ArrayNode podsArray = JSON_OBJECT_MAPPER.createArrayNode();
    if (strictSymja) {
        engine.setPackageMode(false);
        final ExprParser parser = new ExprParser(engine, true);
        try {
            inExpr = parser.parse(inputStr);
            if (inExpr.isPresent()) {
                long numberOfLeaves = inExpr.leafCount();
                if (numberOfLeaves < Config.MAX_INPUT_LEAVES) {
                    outExpr = inExpr;
                    final StringWriter errorWriter = new StringWriter();
                    WriterOutputStream werrors = new WriterOutputStream(errorWriter);
                    PrintStream errors = new PrintStream(werrors);
                    IExpr firstEval = F.NIL;
                    try (ThreadLocalNotifierClosable c = setLogEventNotifier(errors)) {
                        engine.setErrorPrintStream(errors);
                        firstEval = engine.evaluateNIL(inExpr);
                    } finally {
                        engine.setErrorPrintStream(null);
                    }
                    addSymjaPod(podsArray, inExpr, inExpr, "Input", "Identity", formats, engine);
                    numpods++;
                    String errorString = "";
                    if (firstEval.isPresent()) {
                        outExpr = firstEval;
                    } else {
                        errorString = errorWriter.toString().trim();
                    }
                    outExpr = engine.evaluate(inExpr);
                    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);
                            int form = internFormat(SYMJA, "visjs");
                            addPod(podsArray, inExpr, outExpr, html, "Graph data", "Graph", form, engine);
                            numpods++;
                        } else {
                            addSymjaPod(podsArray, inExpr, outExpr, errorString, "Evaluated result", "Expression", formats, engine, true);
                            numpods++;
                        }
                    } else {
                        addSymjaPod(podsArray, inExpr, outExpr, errorString, "Evaluated result", "Expression", formats, engine, true);
                        numpods++;
                    }
                    resultStatistics(queryresult, error, numpods, podsArray);
                    return messageJSON;
                }
            }
        } catch (SyntaxError serr) {
            // this includes syntax errors
            LOGGER.debug("Pods.createResult() failed", serr);
            return errorJSON("0", serr.getMessage());
        }
        queryresult.put("error", error ? "true" : "false");
        return messageJSON;
    }
    inExpr = parseInput(inputStr, engine);
    if (inExpr.isPresent()) {
        long numberOfLeaves = inExpr.leafCount();
        if (numberOfLeaves < Config.MAX_INPUT_LEAVES) {
            outExpr = inExpr;
            final StringWriter errorWriter = new StringWriter();
            WriterOutputStream werrors = new WriterOutputStream(errorWriter);
            PrintStream errors = new PrintStream(werrors);
            IExpr firstEval = F.NIL;
            try (ThreadLocalNotifierClosable c = setLogEventNotifier(errors)) {
                engine.setErrorPrintStream(errors);
                firstEval = engine.evaluateNIL(inExpr);
            } finally {
                engine.setErrorPrintStream(null);
            }
            addSymjaPod(podsArray, inExpr, inExpr, "Input", "Identity", formats, engine);
            numpods++;
            String errorString = "";
            if (firstEval.isPresent()) {
                outExpr = firstEval;
            } else {
                errorString = errorWriter.toString().trim();
            }
            IExpr podOut = outExpr;
            IExpr numExpr = F.NIL;
            IExpr evaledNumExpr = F.NIL;
            if (outExpr.isNumericFunction(true)) {
                numExpr = inExpr.isAST(S.N) ? inExpr : F.N(inExpr);
                evaledNumExpr = engine.evaluate(F.N(outExpr));
            }
            if (outExpr.isNumber() || outExpr.isQuantity()) {
                if (outExpr.isInteger()) {
                    numpods += integerPods(podsArray, inExpr, (IInteger) outExpr, formats, engine);
                    resultStatistics(queryresult, error, numpods, podsArray);
                    return messageJSON;
                } else {
                    podOut = outExpr;
                    if (outExpr.isRational()) {
                        addSymjaPod(podsArray, inExpr, podOut, "Exact result", "Rational", formats, engine);
                        numpods++;
                    }
                    if (// 
                    numExpr.isPresent() && (evaledNumExpr.isInexactNumber() || evaledNumExpr.isQuantity())) {
                        addSymjaPod(podsArray, numExpr, evaledNumExpr, "Decimal form", "Numeric", formats, engine);
                        numpods++;
                        if (!outExpr.isRational()) {
                            if (evaledNumExpr.isInexactNumber()) {
                                inExpr = F.Rationalize(evaledNumExpr);
                                podOut = engine.evaluate(inExpr);
                                addSymjaPod(podsArray, inExpr, podOut, "Rational form", "Numeric", formats, engine);
                                numpods++;
                            }
                        }
                    }
                    if (outExpr.isFraction()) {
                        IFraction frac = (IFraction) outExpr;
                        if (!frac.integerPart().equals(F.C0)) {
                            inExpr = F.List(F.IntegerPart(outExpr), F.FractionalPart(outExpr));
                            podOut = engine.evaluate(inExpr);
                            String plaintext = podOut.first().toString() + " " + podOut.second().toString();
                            addSymjaPod(podsArray, inExpr, podOut, plaintext, "Mixed fraction", "Rational", formats, engine);
                            numpods++;
                            inExpr = F.ContinuedFraction(outExpr);
                            podOut = engine.evaluate(inExpr);
                            StringBuilder plainBuf = new StringBuilder();
                            if (podOut.isNonEmptyList()) {
                                IAST list = (IAST) podOut;
                                plainBuf.append('[');
                                plainBuf.append(list.arg1().toString());
                                plainBuf.append(';');
                                for (int i = 2; i < list.size(); i++) {
                                    plainBuf.append(' ');
                                    plainBuf.append(list.get(i).toString());
                                    if (i < list.size() - 1) {
                                        plainBuf.append(',');
                                    }
                                }
                                plainBuf.append(']');
                            }
                            addSymjaPod(podsArray, inExpr, podOut, plainBuf.toString(), "Continued fraction", "ContinuedFraction", formats, engine);
                            numpods++;
                        }
                    }
                    resultStatistics(queryresult, error, numpods, podsArray);
                    return messageJSON;
                }
            } else {
                if (outExpr.isAST(S.Plot, 2) && outExpr.first().isList()) {
                    outExpr = outExpr.first();
                }
                if (outExpr.isList()) {
                    IAST list = (IAST) outExpr;
                    ListPod listPod = new ListPod(list);
                    numpods += listPod.addJSON(podsArray, formats, engine);
                }
                if (// 
                numExpr.isPresent() && (evaledNumExpr.isInexactNumber() || evaledNumExpr.isQuantity())) {
                    addSymjaPod(podsArray, numExpr, evaledNumExpr, "Decimal form", "Numeric", formats, engine);
                    numpods++;
                }
                if (outExpr.isSymbol() || outExpr.isString()) {
                    String inputWord = outExpr.toString();
                    StringBuilder buf = new StringBuilder();
                    // }
                    if (outExpr.isSymbol() && Documentation.getMarkdown(buf, inputWord)) {
                        numpods += DocumentationPod.addDocumentationPod(new DocumentationPod((ISymbol) outExpr), podsArray, buf, formats);
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    } else {
                        if (outExpr.isString()) {
                            int mimeTyp = ((IStringX) outExpr).getMimeType();
                            if (mimeTyp == IStringX.APPLICATION_SYMJA || mimeTyp == IStringX.APPLICATION_JAVA || mimeTyp == IStringX.APPLICATION_JAVASCRIPT) {
                                String html = toHighligthedCode(outExpr.toString());
                                addSymjaPod(podsArray, inExpr, F.NIL, html, "Result", "String form", HTML, engine);
                                numpods++;
                                resultStatistics(queryresult, error, numpods, podsArray);
                                return messageJSON;
                            } else if (outExpr.isString()) {
                                podOut = outExpr;
                                addSymjaPod(podsArray, inExpr, podOut, "String form", "String", formats, engine);
                                numpods++;
                            }
                        }
                        ArrayList<IPod> soundsLike = listOfPods(inputWord);
                        if (soundsLike != null) {
                            boolean evaled = false;
                            for (int i = 0; i < soundsLike.size(); i++) {
                                IPod pod = soundsLike.get(i);
                                if (pod.keyWord().equalsIgnoreCase(inputWord)) {
                                    int numberOfEntries = pod.addJSON(podsArray, formats, engine);
                                    if (numberOfEntries > 0) {
                                        numpods += numberOfEntries;
                                        evaled = true;
                                        break;
                                    }
                                }
                            }
                            if (!evaled) {
                                for (int i = 0; i < soundsLike.size(); i++) {
                                    IPod pod = soundsLike.get(i);
                                    int numberOfEntries = pod.addJSON(podsArray, formats, engine);
                                    if (numberOfEntries > 0) {
                                        numpods += numberOfEntries;
                                    }
                                }
                            }
                            resultStatistics(queryresult, error, numpods, podsArray);
                            return messageJSON;
                        }
                    }
                } else {
                    if (inExpr.isAST(S.D, 2, 3)) {
                        if (inExpr.isAST1()) {
                            VariablesSet varSet = new VariablesSet(inExpr.first());
                            IAST variables = varSet.getVarList();
                            IASTAppendable result = ((IAST) inExpr).copyAppendable();
                            result.appendArgs(variables);
                            inExpr = result;
                        }
                        outExpr = engine.evaluate(inExpr);
                        podOut = outExpr;
                        addSymjaPod(podsArray, inExpr, podOut, "Derivative", "Derivative", formats, engine);
                        numpods++;
                        if (!outExpr.isFreeAST(x -> x.isTrigFunction())) {
                            inExpr = F.TrigToExp(outExpr);
                            podOut = engine.evaluate(inExpr);
                            // if (!S.PossibleZeroQ.ofQ(engine, F.Subtract(podOut, outExpr))) {
                            if (!podOut.equals(outExpr)) {
                                addSymjaPod(// 
                                podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                numpods++;
                            }
                        }
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    } else if (inExpr.isAST(S.Integrate, 2, 3)) {
                        if (inExpr.isAST1()) {
                            VariablesSet varSet = new VariablesSet(inExpr.first());
                            IAST variables = varSet.getVarList();
                            IASTAppendable result = ((IAST) inExpr).copyAppendable();
                            result.appendArgs(variables);
                            inExpr = result;
                        }
                        outExpr = engine.evaluate(inExpr);
                        podOut = outExpr;
                        addSymjaPod(podsArray, inExpr, podOut, "Integration", "Integral", formats, engine);
                        numpods++;
                        if (!outExpr.isFreeAST(x -> x.isTrigFunction())) {
                            inExpr = F.TrigToExp(outExpr);
                            podOut = engine.evaluate(inExpr);
                            if (!podOut.equals(outExpr)) {
                                addSymjaPod(podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                numpods++;
                            }
                        }
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    } else if (inExpr.isAST(S.Solve, 2, 4)) {
                        if (inExpr.isAST1()) {
                            VariablesSet varSet = new VariablesSet(inExpr.first());
                            IAST variables = varSet.getVarList();
                            IASTAppendable result = ((IAST) inExpr).copyAppendable();
                            result.append(variables);
                            inExpr = result;
                        }
                        outExpr = engine.evaluate(inExpr);
                        podOut = outExpr;
                        addSymjaPod(podsArray, inExpr, podOut, "Solve equation", "Solver", formats, engine);
                        numpods++;
                        if (!outExpr.isFreeAST(x -> x.isTrigFunction())) {
                            inExpr = F.TrigToExp(outExpr);
                            podOut = engine.evaluate(inExpr);
                            // if (!S.PossibleZeroQ.ofQ(engine, F.Subtract(podOut, outExpr))) {
                            if (!podOut.equals(outExpr)) {
                                addSymjaPod(// 
                                podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                numpods++;
                            }
                        }
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    } else {
                        IExpr expr = inExpr;
                        if (outExpr.isAST(S.JSFormData, 3)) {
                            podOut = outExpr;
                            int form = internFormat(SYMJA, podOut.second().toString());
                            addPod(podsArray, inExpr, podOut, podOut.first().toString(), StringFunctions.inputForm(inExpr), "Function", "Plotter", form, engine);
                            numpods++;
                        } 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);
                                int form = internFormat(SYMJA, "visjs");
                                addPod(podsArray, inExpr, podOut, html, "Graph data", "Graph", form, engine);
                                numpods++;
                            }
                        } else {
                            IExpr head = outExpr.head();
                            if (head instanceof IBuiltInSymbol && outExpr.size() > 1) {
                                IEvaluator evaluator = ((IBuiltInSymbol) head).getEvaluator();
                                if (evaluator instanceof IDistribution) {
                                    // if (evaluator instanceof IDiscreteDistribution) {
                                    int snumpods = statisticsPods(podsArray, (IAST) outExpr, podOut, formats, engine);
                                    numpods += snumpods;
                                }
                            }
                            VariablesSet varSet = new VariablesSet(outExpr);
                            IAST variables = varSet.getVarList();
                            if (outExpr.isBooleanFormula()) {
                                numpods += booleanPods(podsArray, outExpr, variables, formats, engine);
                            }
                            if (outExpr.isAST(S.Equal, 3)) {
                                IExpr arg1 = outExpr.first();
                                IExpr arg2 = outExpr.second();
                                if (// 
                                arg1.isNumericFunction(varSet) && arg2.isNumericFunction(varSet)) {
                                    if (variables.argSize() == 1) {
                                        IExpr plot2D = F.Plot(F.List(arg1, arg2), F.List(variables.arg1(), F.num(-20), F.num(20)));
                                        podOut = engine.evaluate(plot2D);
                                        if (podOut.isAST(S.JSFormData, 3)) {
                                            int form = internFormat(SYMJA, podOut.second().toString());
                                            addPod(podsArray, inExpr, podOut, podOut.first().toString(), StringFunctions.inputForm(plot2D), "Function", "Plotter", form, engine);
                                            numpods++;
                                        }
                                    }
                                    if (!arg1.isZero() && !arg2.isZero()) {
                                        inExpr = F.Equal(engine.evaluate(F.Subtract(arg1, arg2)), F.C0);
                                        podOut = inExpr;
                                        addSymjaPod(podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                        numpods++;
                                    }
                                    inExpr = F.Solve(F.binaryAST2(S.Equal, arg1, arg2), variables);
                                    podOut = engine.evaluate(inExpr);
                                    addSymjaPod(podsArray, inExpr, podOut, "Solution", "Reduce", formats, engine);
                                    numpods++;
                                }
                                resultStatistics(queryresult, error, numpods, podsArray);
                                return messageJSON;
                            } else {
                                if (!inExpr.equals(outExpr)) {
                                    addSymjaPod(podsArray, inExpr, outExpr, "Result", "Identity", formats, engine);
                                    numpods++;
                                }
                            }
                            boolean isNumericFunction = outExpr.isNumericFunction(varSet);
                            if (isNumericFunction) {
                                if (variables.argSize() == 1) {
                                    IExpr plot2D = F.Plot(outExpr, F.List(variables.arg1(), F.num(-7), F.num(7)));
                                    podOut = engine.evaluate(plot2D);
                                    if (podOut.isAST(S.JSFormData, 3)) {
                                        int form = internFormat(SYMJA, podOut.second().toString());
                                        addPod(podsArray, inExpr, podOut, podOut.first().toString(), StringFunctions.inputForm(plot2D), "Function", "Plotter", form, engine);
                                        numpods++;
                                    }
                                } else if (variables.argSize() == 2) {
                                    IExpr plot3D = F.Plot3D(outExpr, F.List(variables.arg1(), F.num(-3.5), F.num(3.5)), F.List(variables.arg2(), F.num(-3.5), F.num(3.5)));
                                    podOut = engine.evaluate(plot3D);
                                    if (podOut.isAST(S.JSFormData, 3)) {
                                        int form = internFormat(SYMJA, podOut.second().toString());
                                        addPod(podsArray, inExpr, podOut, podOut.first().toString(), StringFunctions.inputForm(plot3D), "3D plot", "Plot", form, engine);
                                        numpods++;
                                    }
                                }
                            }
                            if (!outExpr.isFreeAST(x -> x.isTrigFunction())) {
                                inExpr = F.TrigToExp(outExpr);
                                podOut = engine.evaluate(inExpr);
                                // {
                                if (!podOut.equals(outExpr)) {
                                    addSymjaPod(podsArray, inExpr, podOut, "Alternate form", "Simplification", formats, engine);
                                    numpods++;
                                }
                            }
                            if (isNumericFunction && variables.argSize() == 1) {
                                if (outExpr.isPolynomial(variables) && !outExpr.isAtom()) {
                                    inExpr = F.Factor(outExpr);
                                    podOut = engine.evaluate(inExpr);
                                    addSymjaPod(podsArray, inExpr, podOut, "Factor", "Polynomial", formats, engine);
                                    numpods++;
                                    IExpr x = variables.first();
                                    inExpr = F.Minimize(outExpr, x);
                                    podOut = engine.evaluate(inExpr);
                                    if (podOut.isAST(S.List, 3) && podOut.first().isNumber() && podOut.second().isAST(S.List, 2)) {
                                        IExpr rule = podOut.second().first();
                                        if (rule.isRule()) {
                                            StringBuilder buf = new StringBuilder();
                                            buf.append("min{");
                                            buf.append(outExpr.toString());
                                            buf.append("} = ");
                                            buf.append(podOut.first());
                                            buf.append(" at ");
                                            buf.append(rule.first().toString());
                                            buf.append(" = ");
                                            buf.append(rule.second().toString());
                                            addSymjaPod(podsArray, inExpr, podOut, buf.toString(), "GlobalExtrema", "GlobalMinimum", formats, engine);
                                            numpods++;
                                        }
                                    }
                                    inExpr = F.Maximize(outExpr, x);
                                    podOut = engine.evaluate(inExpr);
                                    if (podOut.isAST(S.List, 3) && podOut.first().isNumber() && podOut.second().isAST(S.List, 2)) {
                                        IExpr rule = podOut.second().first();
                                        if (rule.isRule()) {
                                            StringBuilder buf = new StringBuilder();
                                            buf.append("max{");
                                            buf.append(outExpr.toString());
                                            buf.append("} = ");
                                            buf.append(podOut.first());
                                            buf.append(" at ");
                                            buf.append(rule.first().toString());
                                            buf.append(" = ");
                                            buf.append(rule.second().toString());
                                            addSymjaPod(podsArray, inExpr, podOut, buf.toString(), "GlobalExtrema", "GlobalMaximum", formats, engine);
                                            numpods++;
                                        }
                                    }
                                }
                                inExpr = F.D(outExpr, variables.arg1());
                                podOut = engine.evaluate(inExpr);
                                addSymjaPod(podsArray, inExpr, podOut, "Derivative", "Derivative", formats, engine);
                                numpods++;
                                inExpr = F.Integrate(outExpr, variables.arg1());
                                podOut = engine.evaluate(inExpr);
                                addSymjaPod(podsArray, inExpr, podOut, "Indefinite integral", "Integral", formats, engine);
                                numpods++;
                            }
                        }
                        if (numpods == 1) {
                            // only Identity pod was appended
                            if (// 
                            errorString.length() == 0 && !firstEval.isPresent()) {
                                addSymjaPod(podsArray, expr, outExpr, "Evaluated result", "Expression", formats, engine);
                                numpods++;
                            } else {
                                addSymjaPod(podsArray, expr, outExpr, errorString, "Evaluated result", "Expression", formats, engine, true);
                                numpods++;
                            }
                        }
                        resultStatistics(queryresult, error, numpods, podsArray);
                        return messageJSON;
                    }
                }
            }
            if (numpods > 0) {
                resultStatistics(queryresult, error, numpods, podsArray);
                return messageJSON;
            }
        }
    }
    queryresult.put("error", error ? "true" : "false");
    return messageJSON;
}
Also used : IStringX(org.matheclipse.core.interfaces.IStringX) Level(org.apache.logging.log4j.Level) IInteger(org.matheclipse.core.interfaces.IInteger) StringUtils(org.apache.commons.lang3.StringUtils) ThreadLocalNotifyingAppender(org.matheclipse.logging.ThreadLocalNotifyingAppender) TeXUtilities(org.matheclipse.core.eval.TeXUtilities) IDistribution(org.matheclipse.core.interfaces.IDistribution) Trie(org.matheclipse.parser.trie.Trie) VariablesSet(org.matheclipse.core.convert.VariablesSet) Map(java.util.Map) EvalEngine(org.matheclipse.core.eval.EvalEngine) ID(org.matheclipse.core.expression.ID) IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) Set(java.util.Set) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) JSBuilder(org.matheclipse.core.form.output.JSBuilder) ISymbol(org.matheclipse.core.interfaces.ISymbol) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) MathMLUtilities(org.matheclipse.core.eval.MathMLUtilities) Logger(org.apache.logging.log4j.Logger) StringFunctions(org.matheclipse.core.builtin.StringFunctions) ExprParser(org.matheclipse.core.parser.ExprParser) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) StandardTokenizer(org.apache.lucene.analysis.standard.StandardTokenizer) TrieBuilder(org.matheclipse.parser.trie.TrieBuilder) IEvaluator(org.matheclipse.core.interfaces.IEvaluator) IFraction(org.matheclipse.core.interfaces.IFraction) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Encode(org.owasp.encoder.Encode) Message(org.apache.logging.log4j.message.Message) WriterOutputStream(org.matheclipse.core.eval.util.WriterOutputStream) Documentation(org.matheclipse.core.form.Documentation) TrieMatch(org.matheclipse.parser.trie.TrieMatch) Suppliers(com.google.common.base.Suppliers) FuzzyParser(org.matheclipse.api.parser.FuzzyParser) ThreadLocalNotifierClosable(org.matheclipse.logging.ThreadLocalNotifyingAppender.ThreadLocalNotifierClosable) SyntaxError(org.matheclipse.parser.client.SyntaxError) Soundex(org.apache.commons.codec.language.Soundex) PrintStream(java.io.PrintStream) CharTermAttribute(org.apache.lucene.analysis.tokenattributes.CharTermAttribute) TokenStream(org.apache.lucene.analysis.TokenStream) F(org.matheclipse.core.expression.F) IAST(org.matheclipse.core.interfaces.IAST) IBuiltInSymbol(org.matheclipse.core.interfaces.IBuiltInSymbol) StringWriter(java.io.StringWriter) PorterStemFilter(org.apache.lucene.analysis.en.PorterStemFilter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Config(org.matheclipse.core.basic.Config) GraphFunctions(org.matheclipse.core.builtin.GraphFunctions) IOException(java.io.IOException) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) S(org.matheclipse.core.expression.S) StringReader(java.io.StringReader) ElementData1(org.matheclipse.core.data.ElementData1) TeXParser(org.matheclipse.core.form.tex.TeXParser) IExpr(org.matheclipse.core.interfaces.IExpr) Comparator(java.util.Comparator) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) RomanArabicConverter(com.baeldung.algorithms.romannumerals.RomanArabicConverter) WriterOutputStream(org.matheclipse.core.eval.util.WriterOutputStream) IBuiltInSymbol(org.matheclipse.core.interfaces.IBuiltInSymbol) StringWriter(java.io.StringWriter) SyntaxError(org.matheclipse.parser.client.SyntaxError) IInteger(org.matheclipse.core.interfaces.IInteger) EvalEngine(org.matheclipse.core.eval.EvalEngine) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) IAST(org.matheclipse.core.interfaces.IAST) IStringX(org.matheclipse.core.interfaces.IStringX) IDistribution(org.matheclipse.core.interfaces.IDistribution) IFraction(org.matheclipse.core.interfaces.IFraction) PrintStream(java.io.PrintStream) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ThreadLocalNotifierClosable(org.matheclipse.logging.ThreadLocalNotifyingAppender.ThreadLocalNotifierClosable) VariablesSet(org.matheclipse.core.convert.VariablesSet) ExprParser(org.matheclipse.core.parser.ExprParser) IEvaluator(org.matheclipse.core.interfaces.IEvaluator) IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) IExpr(org.matheclipse.core.interfaces.IExpr)

Example 4 with GraphExpr

use of org.matheclipse.core.expression.data.GraphExpr in project symja_android_library by axkr.

the class Export method evaluate.

@Override
public IExpr evaluate(final IAST ast, EvalEngine engine) {
    if (Config.isFileSystemEnabled(engine)) {
        if (!(ast.arg1() instanceof IStringX)) {
            return F.NIL;
        }
        IStringX arg1 = (IStringX) ast.arg1();
        Extension format = Extension.exportFilename(arg1.toString());
        if (ast.size() == 4) {
            if (!(ast.arg3() instanceof IStringX)) {
                return F.NIL;
            }
            // format = ((IStringX) ast.arg3()).toString();
            format = Extension.exportExtension(((IStringX) ast.arg3()).toString());
        }
        IExpr arg2 = ast.arg2();
        try (FileWriter writer = new FileWriter(arg1.toString())) {
            if (arg2 instanceof GraphExpr) {
                graphExport(((GraphExpr<DefaultEdge>) arg2).toData(), writer, format);
                return arg1;
            }
            if (format.equals(Extension.CSV) || format.equals(Extension.TSV)) {
                if (arg2.isDataset()) {
                    ((IASTDataset) arg2).csv(writer);
                    return arg1;
                }
            } else if (format.equals(Extension.TABLE)) {
                int[] dims = arg2.isMatrix();
                if (dims != null) {
                    for (int j = 0; j < dims[0]; j++) {
                        IAST rowList = (IAST) arg2.getAt(j + 1);
                        for (int i = 1; i <= dims[1]; i++) {
                            if (rowList.get(i).isReal()) {
                                writer.append(rowList.get(i).toString());
                            } else {
                                writer.append("\"");
                                writer.append(rowList.get(i).toString());
                                writer.append("\"");
                            }
                            if (i < dims[1]) {
                                writer.append(" ");
                            }
                        }
                        writer.append("\n");
                    }
                    return arg1;
                } else {
                    if (arg2.isList()) {
                    }
                }
            } else if (format.equals(Extension.DAT)) {
                File file = new File(arg1.toString());
                com.google.common.io.Files.write(arg2.toString(), file, Charset.defaultCharset());
                return arg1;
            } else if (format.equals(Extension.WXF)) {
                File file = new File(arg1.toString());
                byte[] bArray = WL.serialize(arg2);
                com.google.common.io.Files.write(bArray, file);
                return arg1;
            }
        } catch (IOException ioe) {
            LOGGER.log(engine.getLogLevel(), "Export: file {} not found!", arg1, ioe);
        } catch (Exception ex) {
            LOGGER.log(engine.getLogLevel(), "Export: file {}", arg1, ex);
        }
    }
    return F.NIL;
}
Also used : Extension(org.matheclipse.core.io.Extension) IASTDataset(org.matheclipse.core.interfaces.IASTDataset) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) FileWriter(java.io.FileWriter) DefaultEdge(org.jgrapht.graph.DefaultEdge) IStringX(org.matheclipse.core.interfaces.IStringX) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST) IOException(java.io.IOException) File(java.io.File) ExportException(org.jgrapht.nio.ExportException) IOException(java.io.IOException)

Example 5 with GraphExpr

use of org.matheclipse.core.expression.data.GraphExpr in project symja_android_library by axkr.

the class ExportString method evaluate.

@Override
public IExpr evaluate(final IAST ast, EvalEngine engine) {
    IExpr arg1 = ast.arg1();
    if (!(ast.arg2() instanceof IStringX)) {
        return F.NIL;
    }
    Extension format = Extension.exportExtension(((IStringX) ast.arg2()).toString());
    try (StringWriter writer = new StringWriter()) {
        if (format.equals(Extension.EXPRESSIONJSON)) {
            if (arg1.isNumber() || arg1.isSymbol()) {
                return F.stringx(arg1.toString());
            } else if (arg1.isString()) {
                return F.stringx("'" + arg1.toString() + "'");
            }
            return ExpressionJSONConvert.exportExpressionJSONIStringX(arg1);
        }
        if (arg1 instanceof GraphExpr) {
            graphExport(((GraphExpr<DefaultEdge>) arg1).toData(), writer, format);
            return F.stringx(writer.toString());
        }
        if (format.equals(Extension.CSV) || format.equals(Extension.TSV)) {
            if (arg1.isDataset()) {
                ((IASTDataset) arg1).csv(writer);
                return F.stringx(writer.toString());
            }
        } else if (format.equals(Extension.TABLE)) {
            int[] dims = arg1.isMatrix();
            if (dims != null) {
                for (int j = 0; j < dims[0]; j++) {
                    IAST rowList = (IAST) arg1.getAt(j + 1);
                    for (int i = 1; i <= dims[1]; i++) {
                        if (rowList.get(i).isReal()) {
                            writer.append(rowList.get(i).toString());
                        } else {
                            writer.append("\"");
                            writer.append(rowList.get(i).toString());
                            writer.append("\"");
                        }
                        if (i < dims[1]) {
                            writer.append(" ");
                        }
                    }
                    writer.append("\n");
                }
                return F.stringx(writer.toString());
            } else {
                if (arg1.isList()) {
                }
            }
        // } else if (format.equals(Extension.DAT)) {
        // File file = new File(arg1.toString());
        // com.google.common.io.Files.write(arg2.toString(), file, Charset.defaultCharset());
        // return arg1;
        // } else if (format.equals(Extension.WXF)) {
        // File file = new File(arg1.toString());
        // byte[] bArray = WL.serialize(arg2);
        // com.google.common.io.Files.write(bArray, file);
        // return arg1;
        }
    // } catch (IOException ioe) {
    // return engine.printMessage("ExportString: " + arg1.toString() + " not found!");
    } catch (Exception ex) {
        LOGGER.log(engine.getLogLevel(), "format: {}", arg1, ex);
        return F.NIL;
    }
    return F.NIL;
}
Also used : Extension(org.matheclipse.core.io.Extension) IASTDataset(org.matheclipse.core.interfaces.IASTDataset) StringWriter(java.io.StringWriter) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) DefaultEdge(org.jgrapht.graph.DefaultEdge) IExpr(org.matheclipse.core.interfaces.IExpr) IStringX(org.matheclipse.core.interfaces.IStringX) IAST(org.matheclipse.core.interfaces.IAST) ExportException(org.jgrapht.nio.ExportException)

Aggregations

GraphExpr (org.matheclipse.core.expression.data.GraphExpr)7 IExpr (org.matheclipse.core.interfaces.IExpr)7 IAST (org.matheclipse.core.interfaces.IAST)6 IOException (java.io.IOException)4 IStringX (org.matheclipse.core.interfaces.IStringX)4 StringWriter (java.io.StringWriter)3 SyntaxError (org.matheclipse.parser.client.SyntaxError)3 File (java.io.File)2 FileWriter (java.io.FileWriter)2 Collections (java.util.Collections)2 Map (java.util.Map)2 StringUtils (org.apache.commons.lang3.StringUtils)2 LogManager (org.apache.logging.log4j.LogManager)2 Logger (org.apache.logging.log4j.Logger)2 DefaultEdge (org.jgrapht.graph.DefaultEdge)2 ExportException (org.jgrapht.nio.ExportException)2 IASTDataset (org.matheclipse.core.interfaces.IASTDataset)2 Extension (org.matheclipse.core.io.Extension)2 ExprParser (org.matheclipse.core.parser.ExprParser)2 MathException (org.matheclipse.parser.client.math.MathException)2