Search in sources :

Example 66 with IASTMutable

use of org.matheclipse.core.interfaces.IASTMutable in project symja_android_library by axkr.

the class TeXParser method convert.

private IExpr convert(NodeList list, int[] position, int end, IExpr lhs, int precedence) {
    final int listSize = list.getLength();
    if (end > 1) {
        if (lhs == null) {
            Node lhsNode = list.item(position[0]++);
            String name = lhsNode.getNodeName();
            if (name.equals("mo")) {
                String text = lhsNode.getTextContent();
                PrefixOperator operator = PREFIX_OPERATOR_MAP.get(text);
                if (operator != null) {
                    int currPrec = operator.getPrecedence();
                    IExpr x = convert(list, position, end, null, currPrec);
                    lhs = operator.createFunction(x);
                }
            }
            if (lhs == null) {
                lhs = toHeadExpr(lhsNode, list, position, precedence);
                if (position[0] >= listSize) {
                    return lhs;
                }
            }
            int attribute = ISymbol.NOATTRIBUTE;
            if (lhs.isSymbol()) {
                attribute = ((ISymbol) lhs).getAttributes();
            }
            if ((attribute & ISymbol.CONSTANT) != ISymbol.CONSTANT) {
                if (// 
                (lhs.isFunction() || lhs.isSymbol() || lhs.isDerivative() != null) && position[0] < listSize) {
                    boolean isNumericFunction = ((attribute & ISymbol.NUMERICFUNCTION) == ISymbol.NUMERICFUNCTION);
                    Node arg2 = list.item(position[0]);
                    if (arg2.getNodeName().equals("mfenced")) {
                        position[0]++;
                        int[] position2 = new int[] { 0 };
                        NodeList childNodes = arg2.getChildNodes();
                        IExpr args = convertArgs(childNodes, position2);
                        if (args.isSequence()) {
                            ((IASTMutable) args).set(0, lhs);
                            return args;
                        }
                        lhs = F.unaryAST1(lhs, args);
                        if (position[0] == listSize) {
                            return lhs;
                        }
                    } else if (isNumericFunction || (lhs.isBuiltInSymbol() && !(lhs instanceof BuiltInDummy)) || lhs.isFunction()) {
                        if (lhs.equals(S.Integrate)) {
                            ISymbol test = F.Dummy("test");
                            return integrate(list, position, test, test);
                        }
                        IExpr args = convert(list, position, end, null, 0);
                        if (args.isSequence()) {
                            ((IASTMutable) args).set(0, lhs);
                            return args;
                        }
                        if (lhs.isFunction() && lhs.size() == 2) {
                            IExpr temp = Lambda.replaceSlots(lhs.first(), F.list(args));
                            if (temp.isPresent()) {
                                lhs = temp;
                            }
                        } else {
                            lhs = F.unaryAST1(lhs, args);
                        }
                        if (position[0] == listSize) {
                            return lhs;
                        }
                    }
                }
            }
        }
        IExpr result = lhs;
        int currPrec = 0;
        while (position[0] < end) {
            Node op = list.item(position[0]);
            String name = op.getNodeName();
            if (name.equals("mo")) {
                String text = op.getTextContent();
                if (SHOW_UNICODE) {
                    LOGGER.info("mo: {} - {}", () -> text, () -> toUnicodeString(text, "UTF-8"));
                }
                BinaryOperator binaryOperator = BINARY_OPERATOR_MAP.get(text);
                if (binaryOperator != null) {
                    currPrec = binaryOperator.getPrecedence();
                    if (precedence >= currPrec) {
                        return result;
                    }
                    position[0]++;
                    IExpr rhs = convert(list, position, end, null, currPrec);
                    result = binaryOperator.createFunction(result, rhs);
                    continue;
                } else {
                    PostfixOperator postfixOperator = POSTFIX_OPERATOR_MAP.get(text);
                    if (postfixOperator != null) {
                        currPrec = postfixOperator.getPrecedence();
                        if (precedence >= currPrec) {
                            return result;
                        }
                        result = postfixOperator.createFunction(lhs);
                        position[0]++;
                        continue;
                    }
                }
                throw new AbortException();
            } else if (name.equals("mspace")) {
                position[0]++;
                continue;
            }
            // try to build a Times(...) expression
            currPrec = Precedence.TIMES;
            IExpr rhs = convert(list, position, end, null, currPrec);
            // invisible times?
            result = F.Times(lhs, rhs);
        }
        if (result.isPresent() && position[0] >= end) {
            return result;
        }
    }
    return convertArgs(list, position);
}
Also used : ISymbol(org.matheclipse.core.interfaces.ISymbol) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) IASTMutable(org.matheclipse.core.interfaces.IASTMutable) BuiltInDummy(org.matheclipse.core.expression.BuiltInDummy) IExpr(org.matheclipse.core.interfaces.IExpr) AbortException(org.matheclipse.core.eval.exception.AbortException)

Example 67 with IASTMutable

use of org.matheclipse.core.interfaces.IASTMutable in project symja_android_library by axkr.

the class RulePreprocessor method convertToRule.

private static void convertToRule(IExpr expr, String rulePostfix, final PrintWriter out, String symbolName, EvalEngine engine) {
    boolean last;
    StringBuilder buffer = new StringBuilder();
    // ArraySet<ISymbol> headerSymbols = new ArraySet<ISymbol>();
    if (expr.isAST()) {
        IAST list = (IAST) expr;
        if (symbolName != null) {
            int equalsRuleCounter = 0;
            int simpleRuleCounter = 0;
            for (int i = 1; i < list.size(); i++) {
                last = i == (list.argSize());
                expr = list.get(i);
                if (expr.isAST(S.SetDelayed, 3)) {
                    IAST ast = (IAST) expr;
                    if (!RulesData.isComplicatedPatternRule(ast.arg1())) {
                        simpleRuleCounter++;
                    }
                } else if (expr.isAST(S.Set, 3)) {
                    equalsRuleCounter++;
                }
            }
            if (equalsRuleCounter > 0 || simpleRuleCounter > 0) {
                out.print(SIZES);
                out.append(Integer.toString(equalsRuleCounter));
                out.append(", ");
                out.append(Integer.toString(simpleRuleCounter));
                out.append(" };\n\n");
                buffer.append("    IInit(");
                buffer.append(symbolName);
                buffer.append(", SIZES),\n");
            }
        }
        for (int i = 1; i < list.size(); i++) {
            last = i == (list.argSize());
            expr = list.get(i);
            if (expr.isAST(S.SetDelayed, 3)) {
                IASTMutable ast = ((IAST) expr).copy();
                if (ast.arg1().isAST()) {
                    // if (ast.arg1().isAST(S.Sum)) {
                    // HoldAll in Sum prevents evaluation in evalHoldPattern
                    // System.out.println(ast.arg1().toString());
                    // }
                    ast.set(1, engine.evalHoldPattern((IAST) ast.arg1()));
                }
                buffer.append("    // " + ast.toString().replaceAll("\\n", "") + "\n");
                buffer.append("    ISetDelayed(");
                appendSetDelayedToRule(ast, buffer, false, last);
            } else if (expr.isAST(S.Set, 3)) {
                IASTMutable ast = ((IAST) expr).copy();
                if (ast.arg1().isAST()) {
                    ast.set(1, engine.evalHoldPattern((IAST) ast.arg1()));
                }
                buffer.append("    // " + ast.toString().replaceAll("\\n", "") + "\n");
                buffer.append("    ISet(");
                appendSetDelayedToRule(ast, buffer, true, last);
            } else if (expr.isAST(S.Rule, 3)) {
                IASTMutable ast = ((IAST) expr).copy();
                if (ast.arg1().isAST()) {
                    ast.set(1, engine.evalHoldPattern((IAST) ast.arg1()));
                }
                buffer.append("    // " + ast.toString().replaceAll("\\n", "") + "\n");
                buffer.append("    Rule(");
                appendSetDelayedToRule(ast, buffer, true, last);
            }
        }
    } else {
        if (expr.isAST(S.SetDelayed, 3)) {
            IAST ast = (IAST) expr;
            buffer.append("    ISetDelayed(");
            appendSetDelayedToRule(ast, buffer, false, true);
        } else if (expr.isAST(S.Set, 3)) {
            IAST ast = (IAST) expr;
            buffer.append("    ISet(");
            appendSetDelayedToRule(ast, buffer, true, true);
        } else if (expr.isAST(S.Rule, 3)) {
            IAST ast = (IAST) expr;
            buffer.append("    Rule(");
            appendSetDelayedToRule(ast, buffer, true, true);
        }
    }
    out.print(LIST0);
    out.print(rulePostfix);
    out.println(LIST1);
    out.print(buffer.toString());
    out.print(FOOTER0);
}
Also used : IAST(org.matheclipse.core.interfaces.IAST) IASTMutable(org.matheclipse.core.interfaces.IASTMutable)

Example 68 with IASTMutable

use of org.matheclipse.core.interfaces.IASTMutable in project symja_android_library by axkr.

the class BooleanFunctions method xorToDNF.

/**
 * Convert the XOR expression into DNF format.
 *
 * @param xorForm the <code>Xor(...)</code> expression
 * @return
 */
private static IAST xorToDNF(IAST xorForm) {
    int size = xorForm.argSize();
    if (size > 2) {
        if (size <= 15) {
            IASTAppendable orAST = F.Or();
            // allBits filled with '1' up to size of bits
            final int allBits = FULL_BITSETS[size - 1];
            for (int i = allBits; i >= 0; i--) {
                int singleBit = 0b1;
                int count = 0;
                for (int j = 0; j < size; j++) {
                    if ((singleBit & i) != 0) {
                        count++;
                    }
                    singleBit <<= 1;
                }
                if ((count & 1) == 1) {
                    IASTMutable andAST = F.astMutable(S.And, size);
                    singleBit = 0b1;
                    int startPos = 1;
                    int startNotPos = count + 1;
                    for (int j = 0; j < size; j++) {
                        if ((singleBit & i) == 0) {
                            andAST.set(startNotPos++, F.Not(xorForm.get(j + 1)));
                        } else {
                            andAST.set(startPos++, xorForm.get(j + 1));
                        }
                        singleBit <<= 1;
                    }
                    orAST.append(andAST);
                }
            }
            return orAST;
        }
        throw new ASTElementLimitExceeded(Short.MAX_VALUE);
    }
    IExpr arg1 = xorForm.arg1();
    IExpr arg2 = xorForm.arg2();
    return F.Or(F.And(arg1, F.Not(arg2)), F.And(F.Not(arg1), arg2));
}
Also used : IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) IASTMutable(org.matheclipse.core.interfaces.IASTMutable) IExpr(org.matheclipse.core.interfaces.IExpr) ASTElementLimitExceeded(org.matheclipse.core.eval.exception.ASTElementLimitExceeded)

Example 69 with IASTMutable

use of org.matheclipse.core.interfaces.IASTMutable in project symja_android_library by axkr.

the class Combinatoric method permutationReplace.

public static IExpr permutationReplace(IAST list1, IAST mainList) {
    IASTMutable result = list1.copy();
    boolean changed = false;
    for (int i = 1; i < list1.size(); i++) {
        IExpr arg = list1.get(i);
        if (arg.isInteger()) {
            IInteger element = PermutationReplace.replaceSingleElement(mainList, (IInteger) arg);
            if (!element.equals(arg)) {
                result.set(i, element);
                changed = true;
            }
        }
    }
    return changed ? result : list1;
}
Also used : IInteger(org.matheclipse.core.interfaces.IInteger) IASTMutable(org.matheclipse.core.interfaces.IASTMutable) IExpr(org.matheclipse.core.interfaces.IExpr)

Example 70 with IASTMutable

use of org.matheclipse.core.interfaces.IASTMutable in project symja_android_library by axkr.

the class OptimizeExpression method optimizeExpression.

/**
 * Try to optimize/extract common sub-<code>IASTMutables</code> expressions to minimize the number
 * of operations
 *
 * @param ast the ast whose internal memory consumption should be minimized
 * @return the number of shared sub-expressions
 */
private static IExpr optimizeExpression(final IASTMutable ast) {
    ShareFunction function = new ShareFunction();
    ShareReplaceAll sra = new ShareReplaceAll(function);
    IExpr sharedExpr = ast.accept(sra);
    if (sharedExpr.isPresent()) {
        ArrayList<ReferenceCounter> list = new ArrayList<ReferenceCounter>();
        for (Map.Entry<IASTMutable, ReferenceCounter> entry : function.map.entrySet()) {
            ReferenceCounter rc = entry.getValue();
            if (rc.counter > 1) {
                list.add(rc);
            }
        }
        int varCounter = 1;
        Collections.sort(list, Collections.reverseOrder());
        IASTAppendable variableSubstitutions = F.ListAlloc(list.size());
        IASTAppendable replaceList = F.ListAlloc(list.size());
        for (ReferenceCounter referenceCounter : list) {
            IExpr reference = referenceCounter.reference;
            IExpr temp = reference.replaceAll(variableSubstitutions).orElse(reference);
            ISymbol dummyVariable = F.Dummy("v" + varCounter);
            replaceList.append(F.Rule(dummyVariable, temp));
            variableSubstitutions.append(F.Rule(reference, dummyVariable));
            varCounter++;
        }
        sharedExpr = sharedExpr.replaceRepeated(variableSubstitutions);
        if (sharedExpr.isPresent()) {
            return F.list(sharedExpr, replaceList);
        }
    }
    return F.list(ast);
}
Also used : IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) ISymbol(org.matheclipse.core.interfaces.ISymbol) ArrayList(java.util.ArrayList) IExpr(org.matheclipse.core.interfaces.IExpr) IASTMutable(org.matheclipse.core.interfaces.IASTMutable) TreeMap(java.util.TreeMap) Map(java.util.Map)

Aggregations

IASTMutable (org.matheclipse.core.interfaces.IASTMutable)92 IExpr (org.matheclipse.core.interfaces.IExpr)60 IAST (org.matheclipse.core.interfaces.IAST)34 IASTAppendable (org.matheclipse.core.interfaces.IASTAppendable)26 ISymbol (org.matheclipse.core.interfaces.ISymbol)12 IInteger (org.matheclipse.core.interfaces.IInteger)5 Map (java.util.Map)4 IComplex (org.matheclipse.core.interfaces.IComplex)4 IRational (org.matheclipse.core.interfaces.IRational)4 ArrayList (java.util.ArrayList)3 TreeMap (java.util.TreeMap)3 EvalEngine (org.matheclipse.core.eval.EvalEngine)3 JASConversionException (org.matheclipse.core.eval.exception.JASConversionException)3 ValidateException (org.matheclipse.core.eval.exception.ValidateException)3 INumber (org.matheclipse.core.interfaces.INumber)3 IPatternObject (org.matheclipse.core.interfaces.IPatternObject)3 ISparseArray (org.matheclipse.core.interfaces.ISparseArray)3 ASTNode (org.matheclipse.parser.client.ast.ASTNode)3 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)2 AST2Expr (org.matheclipse.core.convert.AST2Expr)2