Search in sources :

Example 16 with Theory

use of com.sri.ai.grinder.api.Theory in project aic-expresso by aic-sri-international.

the class VariableComponent method calculate.

public Expression calculate() {
    Theory theory = this.model.theory;
    Context context = this.model.context;
    Expression childrenMessage = parse("1");
    for (FactorComponent children : this.children) {
        childrenMessage = apply(TIMES, childrenMessage, children.calculate());
        childrenMessage = theory.evaluate(childrenMessage, context);
    }
    for (Expression cutsetVariable : this.cutsetInsideSubModel) {
        // childrenMessage = theory.evaluate(childrenMessage, context);
        // String str = "sum({{ (on " + cutsetVariable + " in " + this.model.getValues(cutsetVariable) +" ) " + childrenMessage + " }})";
        // childrenMessage = parse(str);
        Expression valuesTakenByVariableToSum = this.model.getValues(cutsetVariable);
        IndexExpressionsSet indices = new ExtensionalIndexExpressionsSet(apply(IN, cutsetVariable, valuesTakenByVariableToSum));
        Expression intensionalMultiSet = IntensionalSet.makeMultiSet(indices, childrenMessage, parse("true"));
        Expression summation = apply(SUM, intensionalMultiSet);
        childrenMessage = summation;
    }
    return theory.evaluate(childrenMessage, context);
}
Also used : Context(com.sri.ai.grinder.api.Context) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) Theory(com.sri.ai.grinder.api.Theory) Expression(com.sri.ai.expresso.api.Expression) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) IndexExpressionsSet(com.sri.ai.expresso.api.IndexExpressionsSet)

Example 17 with Theory

use of com.sri.ai.grinder.api.Theory in project aic-expresso by aic-sri-international.

the class ClearExampleEvaluation method main.

public static void main(String[] args) {
    // /// Evaluating expressions
    // The above code shows how to deal with the syntax of expressions.
    // Evaluating expressions requires knowing about the semantics, that is, to what functions each operator corresponds to ("+" to addition, etc).
    // This is provided by a theory, which for now it suffices to know is a collection of methods for evaluating expressions
    // according to an interpretation to some symbols.
    Theory theory = new CompoundTheory(new EqualityTheory(false, true), new DifferenceArithmeticTheory(false, false), new LinearRealArithmeticTheory(false, false), new TupleTheory(), new PropositionalTheory());
    // Because this evaluation is symbolic, evaluated expressions may involve free variables.
    // In this case, the result of the evaluation will be a simplified expression that
    // is equivalent to the original expression for all possible assignments to the free variables.
    // For example, X + 0*Y is evaluate to X because, for any assignment to (X,Y), X + 0*Y = X.
    // true context: all assignments to free variables are of interest
    Context context = new TrueContext(theory);
    // We will later see how we can use contexts that restrict the free variable assignments of interest.
    context = context.makeNewContextWithAddedType(BOOLEAN_TYPE);
    context = context.extendWithSymbolsAndTypes("B", "Integer");
    context = context.extendWithSymbolsAndTypes("J", "Integer");
    // Now that we have a theory and a context, we can evaluate expressions:
    println("1 + 0*X + 1  =  " + theory.evaluate(parse("1 + 1"), context));
    /*evaluate(new String[] {
				"sum({{ (on C in Boolean) (if C then if A then 50 else 50 else if A then 50 else 50) * (if C then if B then 60 else 40 else if B then 40 else 60) }})", "",
		}, theory, context);
		*/
    Expression test = theory.evaluate(parse("sum({{ (on C in Boolean) (if C then if A then 50 else 50 else if A then 50 else 50) * (if C then if B then 60 else 40 else if B then 40 else 60) }})"), context);
    println(test);
    String str = "sum({{ (on I in 1..10) I : I != J }})";
    Expression expr = parse(str);
    Expression test2 = theory.evaluate(expr, context);
    println(test2);
    // Here's how to do it from scratch, but see next the way we typically actually do it.
    Expression p = makeSymbol("P");
    context = context.extendWithSymbolsAndTypes("P", "Integer");
    IndexExpressionsSet indices = new ExtensionalIndexExpressionsSet(apply(IN, p, parse("1..4")));
    println("plop");
    // The "extensional" in ExtensionalIndexExpressionsSet means that the list/set of indices is extensionally defined,
    // even though they will be the indices of an intensionally defined set.
    Expression intensionalUniSet = // IntensionalSet.intensionalUniSet, or simply intensionalUniSet, also works
    IntensionalSet.makeMultiSet(indices, parse("5"), parse("true"));
    // Note that Equality.make(p, "Rodrigo") is the same as apply(FunctorConstants.EQUAL, p, "Rodrigo").
    // We often have 'make' methods for many operators: And.make, Or.make and so on.
    // packages in com.sri.ai.expresso.grinder.sgdpllt.library have many such operator-specific classes.
    println(intensionalUniSet);
    Expression sum = apply(SUM, intensionalUniSet);
    println(sum);
    Expression resultat = theory.evaluate(sum, context);
    println(resultat);
}
Also used : TrueContext(com.sri.ai.grinder.core.TrueContext) Context(com.sri.ai.grinder.api.Context) EqualityTheory(com.sri.ai.grinder.theory.equality.EqualityTheory) EqualityTheory(com.sri.ai.grinder.theory.equality.EqualityTheory) PropositionalTheory(com.sri.ai.grinder.theory.propositional.PropositionalTheory) LinearRealArithmeticTheory(com.sri.ai.grinder.theory.linearrealarithmetic.LinearRealArithmeticTheory) Theory(com.sri.ai.grinder.api.Theory) DifferenceArithmeticTheory(com.sri.ai.grinder.theory.differencearithmetic.DifferenceArithmeticTheory) CompoundTheory(com.sri.ai.grinder.theory.compound.CompoundTheory) TupleTheory(com.sri.ai.grinder.theory.tuple.TupleTheory) DifferenceArithmeticTheory(com.sri.ai.grinder.theory.differencearithmetic.DifferenceArithmeticTheory) LinearRealArithmeticTheory(com.sri.ai.grinder.theory.linearrealarithmetic.LinearRealArithmeticTheory) PropositionalTheory(com.sri.ai.grinder.theory.propositional.PropositionalTheory) CompoundTheory(com.sri.ai.grinder.theory.compound.CompoundTheory) TupleTheory(com.sri.ai.grinder.theory.tuple.TupleTheory) TrueContext(com.sri.ai.grinder.core.TrueContext) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) Expression(com.sri.ai.expresso.api.Expression) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) IndexExpressionsSet(com.sri.ai.expresso.api.IndexExpressionsSet)

Example 18 with Theory

use of com.sri.ai.grinder.api.Theory in project aic-expresso by aic-sri-international.

the class Compilation method compile.

/**
 * Compiles an expression to a normalized (decision-tree-like) expression.
 * @param inputExpression
 * @param mapFromVariableNameToTypeName
 * @param mapFromCategoricalTypeNameToSizeString
 * @param additionalTypes
 * @param solverListener if not null, invoked on solver used for compilation, before and after compilation starts; returned solver on 'before' invocation is used (it may be the same one used as argument, of course).
 * @return
 */
public static Expression compile(Expression inputExpression, Theory theory, Map<String, String> mapFromVariableNameToTypeName, Map<String, String> mapFromUniquelyNamedConstantToTypeName, Map<String, String> mapFromCategoricalTypeNameToSizeString, Collection<Type> additionalTypes, Function<MultiQuantifierEliminator, MultiQuantifierEliminator> solverListener) {
    // the group actually does not matter, because we are not going to have any indices.
    AssociativeCommutativeGroup group = new Max();
    // The solver for the parameters above.
    MultiQuantifierEliminator solver = new DefaultMultiQuantifierEliminator();
    if (solverListener != null) {
        solver = solverListener.apply(solver);
    }
    // We use the Prolog convention of small-letter initials for constants, but we need an exception for the random variables.
    Predicate<Expression> isPrologConstant = new PrologConstantPredicate();
    Predicate<Expression> isUniquelyNamedConstantPredicate = e -> isPrologConstant.apply(e) && !mapFromVariableNameToTypeName.containsKey(e);
    Map<String, String> mapFromSymbolNameToTypeName = new LinkedHashMap<>(mapFromVariableNameToTypeName);
    mapFromSymbolNameToTypeName.putAll(mapFromUniquelyNamedConstantToTypeName);
    // Solve the problem.
    // no indices; we want to keep all variables
    List<Expression> indices = Util.list();
    Expression result = solver.solve(group, inputExpression, indices, mapFromSymbolNameToTypeName, mapFromCategoricalTypeNameToSizeString, additionalTypes, isUniquelyNamedConstantPredicate, theory);
    if (solverListener != null) {
        solverListener.apply(null);
    }
    return result;
}
Also used : Type(com.sri.ai.expresso.api.Type) Collection(java.util.Collection) Expression(com.sri.ai.expresso.api.Expression) DefaultMultiQuantifierEliminator(com.sri.ai.grinder.core.solver.DefaultMultiQuantifierEliminator) Function(java.util.function.Function) LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) Theory(com.sri.ai.grinder.api.Theory) AssociativeCommutativeGroup(com.sri.ai.grinder.group.AssociativeCommutativeGroup) Predicate(com.google.common.base.Predicate) Map(java.util.Map) Util(com.sri.ai.util.Util) PrologConstantPredicate(com.sri.ai.grinder.core.PrologConstantPredicate) Max(com.sri.ai.grinder.group.Max) MultiQuantifierEliminator(com.sri.ai.grinder.api.MultiQuantifierEliminator) Max(com.sri.ai.grinder.group.Max) Expression(com.sri.ai.expresso.api.Expression) PrologConstantPredicate(com.sri.ai.grinder.core.PrologConstantPredicate) AssociativeCommutativeGroup(com.sri.ai.grinder.group.AssociativeCommutativeGroup) DefaultMultiQuantifierEliminator(com.sri.ai.grinder.core.solver.DefaultMultiQuantifierEliminator) MultiQuantifierEliminator(com.sri.ai.grinder.api.MultiQuantifierEliminator) DefaultMultiQuantifierEliminator(com.sri.ai.grinder.core.solver.DefaultMultiQuantifierEliminator) LinkedHashMap(java.util.LinkedHashMap)

Example 19 with Theory

use of com.sri.ai.grinder.api.Theory in project aic-expresso by aic-sri-international.

the class DefaultIntensionalBound method boundProduct.

public static DefaultIntensionalBound boundProduct(Theory theory, Context context, Bound... listOfBounds) {
    if (listOfBounds.length == 0) {
        DefaultIntensionalBound result = new DefaultIntensionalBound();
        return result;
    }
    Set<Expression> alreadyDefined = Util.set();
    alreadyDefined.addAll(context.getSymbols());
    Predicate<Expression> isAlreadyDefined = e -> alreadyDefined.contains(e);
    ArrayList<Expression> productIndexExpressionList = new ArrayList<>();
    Object[] productHeadArray = new Expression[listOfBounds.length];
    Object[] productConditionArray = new Expression[listOfBounds.length];
    int k = 0;
    for (Bound bound : Arrays.asList(listOfBounds)) {
        if (!bound.isIntensionalBound()) {
            return null;
        }
        DefaultIntensionalBound intensionalBound = (DefaultIntensionalBound) bound;
        ExtensionalIndexExpressionsSet indexExpressions = (ExtensionalIndexExpressionsSet) intensionalBound.getIndexExpressions();
        Expression Head = intensionalBound.getHead();
        Expression condition = intensionalBound.getCondition();
        ArrayList<Expression> newIndexExpressionsList = new ArrayList<>(indexExpressions.getList());
        for (int i = 0; i != newIndexExpressionsList.size(); i++) {
            Expression indexExpression = newIndexExpressionsList.get(i);
            Symbol index = (Symbol) indexExpression.get(0);
            Expression type = indexExpression.get(1);
            PairOf<Expression> newIndexAndNewExpressionInScope = Expressions.standardizeApart(index, isAlreadyDefined, Head);
            Expression newIndex = newIndexAndNewExpressionInScope.first;
            Head = newIndexAndNewExpressionInScope.second;
            // type should not contain the index
            Expression newIndexExpression = apply(IN, newIndex, type);
            context = context.extendWithSymbolsAndTypes(newIndex, type);
            newIndexExpressionsList.set(i, newIndexExpression);
            alreadyDefined.add(newIndex);
            for (int j = i + 1; j != newIndexExpressionsList.size(); j++) {
                Expression anotherIndexExpression = newIndexExpressionsList.get(j);
                Expression anotherIndex = anotherIndexExpression.get(0);
                Expression anotherType = anotherIndexExpression.get(1);
                Expression newAnotherType = anotherType.replaceSymbol(index, newIndex, context);
                // anotherIndex is a symbols and does not contain index
                Expression newAnotherIndexExpression = apply(IN, anotherIndex, newAnotherType);
                newIndexExpressionsList.set(j, newAnotherIndexExpression);
            }
        }
        productIndexExpressionList.addAll(newIndexExpressionsList);
        productHeadArray[k] = Head;
        productConditionArray[k] = condition;
        k++;
    }
    Expression productCondition = apply(AND, productConditionArray);
    productCondition = theory.evaluate(productCondition, context);
    Expression productHead = apply(TIMES, productHeadArray);
    productHead = theory.evaluate(productHead, context);
    DefaultIntensionalBound result = new DefaultIntensionalBound(productIndexExpressionList, productHead, productCondition);
    return result;
}
Also used : Arrays(java.util.Arrays) Model(com.sri.ai.grinder.anytime.Model) Expressions(com.sri.ai.expresso.helper.Expressions) PairOf(com.sri.ai.util.base.PairOf) SUM(com.sri.ai.grinder.library.FunctorConstants.SUM) Expression(com.sri.ai.expresso.api.Expression) ArrayList(java.util.ArrayList) EQUAL(com.sri.ai.grinder.library.FunctorConstants.EQUAL) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) Symbol(com.sri.ai.expresso.api.Symbol) Expressions.apply(com.sri.ai.expresso.helper.Expressions.apply) IN(com.sri.ai.grinder.library.FunctorConstants.IN) IndexExpressions(com.sri.ai.grinder.library.indexexpression.IndexExpressions) IndexExpressionsSet(com.sri.ai.expresso.api.IndexExpressionsSet) AND(com.sri.ai.grinder.library.FunctorConstants.AND) Context(com.sri.ai.grinder.api.Context) DefaultExtensionalUniSet(com.sri.ai.expresso.core.DefaultExtensionalUniSet) Set(java.util.Set) IntensionalSet(com.sri.ai.expresso.api.IntensionalSet) IF_THEN_ELSE(com.sri.ai.grinder.library.FunctorConstants.IF_THEN_ELSE) List(java.util.List) Theory(com.sri.ai.grinder.api.Theory) Expressions.makeSymbol(com.sri.ai.expresso.helper.Expressions.makeSymbol) Predicate(com.google.common.base.Predicate) GrinderUtil.getIndexExpressionsOfFreeVariablesIn(com.sri.ai.grinder.helper.GrinderUtil.getIndexExpressionsOfFreeVariablesIn) Util(com.sri.ai.util.Util) TIMES(com.sri.ai.grinder.library.FunctorConstants.TIMES) Symbol(com.sri.ai.expresso.api.Symbol) Expressions.makeSymbol(com.sri.ai.expresso.helper.Expressions.makeSymbol) ArrayList(java.util.ArrayList) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) Expression(com.sri.ai.expresso.api.Expression)

Example 20 with Theory

use of com.sri.ai.grinder.api.Theory in project aic-expresso by aic-sri-international.

the class Derivative method productCase.

public static Expression productCase(Expression expression, Expression variable, Context context) {
    Theory theory = context.getTheory();
    List<Expression> arguments = expression.getArguments();
    Expression factor = arguments.get(1);
    for (int i = 2; i < arguments.size(); i++) {
        factor = apply(TIMES, factor, arguments.get(i));
    }
    Expression toEvaluate = apply("+", apply("*", computeDerivative(arguments.get(0), variable, context), factor), apply("*", arguments.get(0), computeDerivative(factor, variable, context)));
    return theory.simplify(toEvaluate, context);
}
Also used : Theory(com.sri.ai.grinder.api.Theory) Expression(com.sri.ai.expresso.api.Expression)

Aggregations

Theory (com.sri.ai.grinder.api.Theory)46 Expression (com.sri.ai.expresso.api.Expression)32 Context (com.sri.ai.grinder.api.Context)23 Type (com.sri.ai.expresso.api.Type)14 DifferenceArithmeticTheory (com.sri.ai.grinder.theory.differencearithmetic.DifferenceArithmeticTheory)9 Expressions.makeSymbol (com.sri.ai.expresso.helper.Expressions.makeSymbol)7 SingleQuantifierEliminationProblem (com.sri.ai.grinder.api.SingleQuantifierEliminationProblem)7 SingleVariableConstraint (com.sri.ai.grinder.api.SingleVariableConstraint)7 TrueContext (com.sri.ai.grinder.core.TrueContext)7 DefaultSingleQuantifierEliminationProblem (com.sri.ai.grinder.core.solver.DefaultSingleQuantifierEliminationProblem)7 AssociativeCommutativeGroup (com.sri.ai.grinder.group.AssociativeCommutativeGroup)7 BruteForceCommonInterpreter (com.sri.ai.grinder.interpreter.BruteForceCommonInterpreter)7 IndexExpressions (com.sri.ai.grinder.library.indexexpression.IndexExpressions)7 CompoundTheory (com.sri.ai.grinder.theory.compound.CompoundTheory)7 EqualityTheory (com.sri.ai.grinder.theory.equality.EqualityTheory)7 Beta (com.google.common.annotations.Beta)6 IndexExpressionsSet (com.sri.ai.expresso.api.IndexExpressionsSet)6 QuantifiedExpression (com.sri.ai.expresso.api.QuantifiedExpression)6 TRUE (com.sri.ai.expresso.helper.Expressions.TRUE)6 ZERO (com.sri.ai.expresso.helper.Expressions.ZERO)6