Search in sources :

Example 41 with IASTMutable

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

the class IndexedLevel method visitAST.

public IExpr visitAST(IAST ast, int[] indx) {
    int[] minDepth = new int[] { 0 };
    IASTMutable[] result = new IASTMutable[] { F.NIL };
    try {
        int size = indx.length;
        final int[] newIndx = new int[size + 1];
        for (int j = 0; j < size; j++) {
            newIndx[j] = indx[j];
        }
        fCurrentLevel++;
        if (fIncludeHeads) {
            newIndx[size] = 0;
            IExpr element = ast.get(0);
            if (element.isAST()) {
                IExpr temp = visitAST((IAST) element, newIndx);
                if (temp.isPresent()) {
                    element = temp;
                }
            }
            final IExpr temp = visitExpr(element, newIndx);
            if (temp.isPresent()) {
                if (!result[0].isPresent()) {
                    result[0] = createResult(ast, temp);
                }
                result[0].set(0, temp);
            }
            if (fCurrentDepth < minDepth[0]) {
                minDepth[0] = fCurrentDepth;
            }
        }
        ast.forEach((x, i) -> {
            newIndx[size] = i;
            IExpr element = x;
            boolean evaled = false;
            if (element.isAST()) {
                IExpr temp = visitAST((IAST) element, newIndx);
                if (temp.isPresent()) {
                    evaled = true;
                    element = temp;
                }
            }
            final IExpr temp = visitExpr(element, newIndx);
            if (temp.isPresent()) {
                if (!result[0].isPresent()) {
                    result[0] = createResult(ast, temp);
                }
                result[0].set(i, temp);
            } else if (evaled) {
                if (!result[0].isPresent()) {
                    result[0] = createResult(ast, temp);
                }
                result[0].set(i, element);
            }
            if (fCurrentDepth < minDepth[0]) {
                minDepth[0] = fCurrentDepth;
            }
        });
        fCurrentDepth = --minDepth[0];
    } finally {
        fCurrentLevel--;
    }
    return result[0];
}
Also used : IASTMutable(org.matheclipse.core.interfaces.IASTMutable) IExpr(org.matheclipse.core.interfaces.IExpr)

Example 42 with IASTMutable

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

the class IPatternMap method substituteASTPatternOrSymbols.

/**
 * Substitute all already find matchings in <code>lhsPatternExpr</code> and return the new pattern
 * expression.
 *
 * @param lhsPatternExpr
 * @param onlyNamedPatterns
 * @return {@link F#NIL} if no substitution can be found.
 */
default IExpr substituteASTPatternOrSymbols(final IAST lhsPatternExpr, boolean onlyNamedPatterns) {
    VisitorReplaceAllWithPatternFlags visitor = new VisitorReplaceAllWithPatternFlags(input -> {
        if (input instanceof IPatternObject) {
            if (onlyNamedPatterns && !(input instanceof Pattern)) {
                return F.NIL;
            }
            IExpr symbolOrPatternObject = ((IPatternObject) input).getSymbol();
            if (symbolOrPatternObject == null) {
                if (onlyNamedPatterns) {
                    return F.NIL;
                }
                symbolOrPatternObject = input;
            }
            return substitute(symbolOrPatternObject);
        }
        return F.NIL;
    }, onlyNamedPatterns);
    IASTMutable result = F.NIL;
    for (int i = 1; i < lhsPatternExpr.size(); i++) {
        IExpr temp = lhsPatternExpr.get(i).accept(visitor);
        if (temp.isPresent()) {
            if (!result.isPresent()) {
                result = lhsPatternExpr.setAtCopy(i, temp);
            // result.setEvalFlags(lhsPatternExpr.getEvalFlags());
            } else {
                result.set(i, temp);
            }
        }
    }
    if (result.isPresent()) {
        return EvalAttributes.simpleEval(result);
    // if (result.isFlatAST()) {
    // IASTMutable temp = EvalAttributes.flattenDeep((IAST) result);
    // if (temp.isPresent()) {
    // result = temp;
    // }
    // }
    // // don't test for OneIdentity attribute here !
    // if (result.isOrderlessAST()) {
    // EvalAttributes.sort(result);
    // }
    // // set the eval flags
    // result.isFreeOfPatterns();
    // return result;
    }
    return F.NIL;
}
Also used : OptionsPattern(org.matheclipse.core.expression.OptionsPattern) Pattern(org.matheclipse.core.expression.Pattern) IPatternMap.addOptionsPattern(org.matheclipse.core.patternmatching.IPatternMap.addOptionsPattern) IPatternObject(org.matheclipse.core.interfaces.IPatternObject) VisitorReplaceAllWithPatternFlags(org.matheclipse.core.visit.VisitorReplaceAllWithPatternFlags) IExpr(org.matheclipse.core.interfaces.IExpr) IASTMutable(org.matheclipse.core.interfaces.IASTMutable)

Example 43 with IASTMutable

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

the class Solve method solveEquations.

/**
 * @param termsEqualZeroList the list of expressions, which should equal <code>0</code>
 * @param variables the variables for which the equations should be solved
 * @param maximumNumberOfResults the maximum number of results which should be returned
 * @param engine the evaluation engine
 * @return a &quot;list of rules list&quot; which solves the equations, or an empty list if no
 *         solution exists, or <code>F.NIL</code> if the equations are not solvable by this
 *         algorithm.
 */
protected static IASTMutable solveEquations(IASTMutable termsEqualZeroList, IAST inequationsList, IAST variables, int maximumNumberOfResults, EvalEngine engine) {
    try {
        IASTMutable list = PolynomialFunctions.solveGroebnerBasis(termsEqualZeroList, variables);
        if (list.isPresent()) {
            termsEqualZeroList = list;
        }
    } catch (JASConversionException e) {
        LOGGER.debug("Solve.solveEquations() failed", e);
    }
    // rewrite some special expressions
    for (int i = 1; i < termsEqualZeroList.size(); i++) {
        IExpr equationTerm = termsEqualZeroList.get(i);
        if (equationTerm.isPlus()) {
            IExpr eq = S.Equal.of(equationTerm, F.C0);
            if (eq.isEqual()) {
                IExpr arg1 = eq.first();
                if (arg1.isPlus2()) {
                    if (arg1.first().isSqrtExpr() && arg1.second().isSqrtExpr()) {
                        // Sqrt() + Sqrt() == constant
                        termsEqualZeroList.set(i, S.Subtract.of(S.Expand.of(F.Sqr(arg1.second())), S.Expand.of(F.Sqr(F.Subtract(eq.second(), arg1.first())))));
                    }
                }
            }
        }
    }
    ExprAnalyzer exprAnalyzer;
    ArrayList<ExprAnalyzer> analyzerList = new ArrayList<ExprAnalyzer>();
    IsWrongSolveExpression predicate = new IsWrongSolveExpression();
    // collect linear and univariate polynomial equations:
    for (IExpr expr : termsEqualZeroList) {
        if (expr.has(predicate, true)) {
            LOGGER.log(engine.getLogLevel(), "Solve: the system contains the wrong object: {}", predicate.getWrongExpr());
            throw new NoEvalException();
        }
        exprAnalyzer = new ExprAnalyzer(expr, variables, engine);
        exprAnalyzer.simplifyAndAnalyze();
        analyzerList.add(exprAnalyzer);
    }
    IASTAppendable matrix = F.ListAlloc();
    IASTAppendable vector = F.ListAlloc();
    try {
        IASTAppendable resultList = F.ListAlloc();
        resultList = analyzeSublist(analyzerList, variables, resultList, maximumNumberOfResults, matrix, vector, engine);
        if (vector.size() > 1) {
            // solve a linear equation <code>matrix.x == vector</code>
            FieldMatrix<IExpr> augmentedMatrix = Convert.list2Matrix(matrix, vector);
            if (augmentedMatrix != null) {
                IAST subSolutionList = LinearAlgebra.rowReduced2RulesList(augmentedMatrix, variables, resultList, engine);
                return solveInequations((IASTMutable) subSolutionList, inequationsList, maximumNumberOfResults, engine);
            }
            return F.NIL;
        }
        return solveInequations(resultList, inequationsList, maximumNumberOfResults, engine);
    // return sortASTArguments(resultList);
    } catch (NoSolution e) {
        if (e.getType() == NoSolution.WRONG_SOLUTION) {
            return F.ListAlloc();
        }
        return F.NIL;
    }
}
Also used : ArrayList(java.util.ArrayList) IASTMutable(org.matheclipse.core.interfaces.IASTMutable) JASConversionException(org.matheclipse.core.eval.exception.JASConversionException) NoEvalException(org.matheclipse.core.eval.exception.NoEvalException) IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST)

Example 44 with IASTMutable

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

the class Solve method solveTimesAST.

private static void solveTimesAST(IAST times, IAST termsEqualZeroList, IAST inequationsList, boolean numericFlag, IAST variables, boolean multipleValues, EvalEngine engine, Set<IExpr> subSolutionSet, int i) {
    IAST temp;
    for (int j = 1; j < times.size(); j++) {
        if (!times.get(j).isFree(Predicates.in(variables), true)) {
            // try to get a solution from this Times() factor
            IASTMutable clonedEqualZeroList = termsEqualZeroList.setAtCopy(i, times.get(j));
            temp = solveEquations(clonedEqualZeroList, inequationsList, variables, 0, engine);
            if (temp.size() > 1) {
                for (int k = 1; k < temp.size(); k++) {
                    IExpr solution = temp.get(k);
                    IExpr replaceAll = engine.evalQuiet(F.ReplaceAll(times, solution));
                    IExpr zeroCrossCheck = engine.evalN(replaceAll);
                    if (zeroCrossCheck.isZero()) {
                        subSolutionSet.add(solution);
                    } else {
                        if (// 
                        replaceAll.isPlusTimesPower() && S.PossibleZeroQ.ofQ(engine, replaceAll)) {
                            subSolutionSet.add(solution);
                        }
                    }
                }
            } else {
                if (clonedEqualZeroList.size() == 2 && variables.size() == 2) {
                    IExpr firstVariable = variables.arg1();
                    IExpr res = eliminateOneVariable(clonedEqualZeroList, firstVariable, multipleValues, engine);
                    if (!res.isPresent()) {
                        if (numericFlag) {
                            // find numerically with start value 0
                            res = S.FindRoot.ofNIL(engine, clonedEqualZeroList.arg1(), F.list(firstVariable, F.C0));
                        }
                    }
                    if (!res.isList() || !res.isFree(t -> t.isIndeterminate() || t.isDirectedInfinity(), true)) {
                        continue;
                    }
                    IAST subResult = (IAST) res;
                    for (int k = 1; k < subResult.size(); k++) {
                        subSolutionSet.add(solveNumeric(subResult.get(i), numericFlag, engine));
                    }
                }
            }
        }
    }
}
Also used : IAST(org.matheclipse.core.interfaces.IAST) IASTMutable(org.matheclipse.core.interfaces.IASTMutable) IExpr(org.matheclipse.core.interfaces.IExpr)

Example 45 with IASTMutable

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

the class OptimizeExpression method cseArray.

public static IAST cseArray(final IAST ast, int minReferences, int minLeafCounter) {
    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 >= minReferences && rc.reference.leafCount() > minLeafCounter) {
                list.add(rc);
            }
        }
        Collections.sort(list, Collections.reverseOrder());
        IASTAppendable result = F.ListAlloc(list.size());
        for (ReferenceCounter rc : list) {
            IASTMutable ref = rc.reference;
            result.append(ref);
        }
        return result;
    }
    return F.NIL;
}
Also used : IASTAppendable(org.matheclipse.core.interfaces.IASTAppendable) 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