Search in sources :

Example 51 with Context

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

the class SGDPLLTTester method testModelCountingForSingleVariableConstraints.

/**
	 * Given a theory and a number <code>n</code> of single-variable constraint tests,
	 * generates <code>n</code> formulas in the theory
	 * and see if the model counting solver works (checked by brute force).
	 * Throws an {@link Error} with the failure description if a test fails.
	 * @param theoryTestingSupport
	 * @param numberOfTests
	 * @param maxNumberOfLiterals
	 * @param outputCount
	 */
public static void testModelCountingForSingleVariableConstraints(boolean testAgainstBruteForce, TheoryTestingSupport theoryTestingSupport, long numberOfTests, int maxNumberOfLiterals, boolean outputCount) {
    Context context = theoryTestingSupport.makeContextWithTestingInformation();
    Expression variable = parse(theoryTestingSupport.pickTestingVariableAtRandom());
    NullaryFunction<Constraint> makeInitialConstraint = () -> theoryTestingSupport.getTheory().makeSingleVariableConstraint(variable, theoryTestingSupport.getTheory(), context);
    Function<Constraint, Expression> makeRandomLiteral = c -> theoryTestingSupport.makeRandomLiteralOn(((SingleVariableConstraint) c).getVariable().toString(), context);
    TestRunner tester = (ls, c, tB, cT, p) -> runModelCountingTestForSingleVariableConstraint(variable, ls, c, tB, cT.getTheory(), p);
    runTesterGivenOnSuccessiveConjunctionsOfLiterals("model counting", tester, numberOfTests, maxNumberOfLiterals, testAgainstBruteForce, theoryTestingSupport, makeInitialConstraint, makeRandomLiteral, outputCount, context);
}
Also used : CompleteMultiVariableContext(com.sri.ai.grinder.sgdpllt.core.constraint.CompleteMultiVariableContext) Context(com.sri.ai.grinder.sgdpllt.api.Context) BinaryFunction(com.sri.ai.util.base.BinaryFunction) Util.removeFromSetNonDestructively(com.sri.ai.util.Util.removeFromSetNonDestructively) SubExpressionsDepthFirstIterator(com.sri.ai.expresso.helper.SubExpressionsDepthFirstIterator) Expression(com.sri.ai.expresso.api.Expression) Constraint(com.sri.ai.grinder.sgdpllt.api.Constraint) Function(java.util.function.Function) GrinderUtil(com.sri.ai.grinder.helper.GrinderUtil) Util.in(com.sri.ai.util.Util.in) ThereExists(com.sri.ai.grinder.sgdpllt.library.boole.ThereExists) AbstractIterativeMultiIndexQuantifierElimination(com.sri.ai.grinder.sgdpllt.interpreter.AbstractIterativeMultiIndexQuantifierElimination) Expressions.parse(com.sri.ai.expresso.helper.Expressions.parse) Map(java.util.Map) CompleteMultiVariableContext(com.sri.ai.grinder.sgdpllt.core.constraint.CompleteMultiVariableContext) And(com.sri.ai.grinder.sgdpllt.library.boole.And) DefaultMultiVariableConstraint(com.sri.ai.grinder.sgdpllt.core.constraint.DefaultMultiVariableConstraint) ZERO(com.sri.ai.expresso.helper.Expressions.ZERO) LinkedHashSet(java.util.LinkedHashSet) Sets(com.sri.ai.grinder.sgdpllt.library.set.Sets) Type(com.sri.ai.expresso.api.Type) NullaryFunction(com.sri.ai.util.base.NullaryFunction) Util.join(com.sri.ai.util.Util.join) SingleVariableConstraint(com.sri.ai.grinder.sgdpllt.api.SingleVariableConstraint) Simplifier(com.sri.ai.grinder.sgdpllt.rewriter.api.Simplifier) Collection(java.util.Collection) Util.list(com.sri.ai.util.Util.list) Set(java.util.Set) Expressions.getVariableReferences(com.sri.ai.expresso.helper.Expressions.getVariableReferences) Context(com.sri.ai.grinder.sgdpllt.api.Context) QuantifiedExpression(com.sri.ai.expresso.api.QuantifiedExpression) Theory(com.sri.ai.grinder.sgdpllt.api.Theory) Beta(com.google.common.annotations.Beta) IndexExpressions(com.sri.ai.grinder.sgdpllt.library.indexexpression.IndexExpressions) Expressions.makeSymbol(com.sri.ai.expresso.helper.Expressions.makeSymbol) Util(com.sri.ai.util.Util) AssociativeCommutativeGroup(com.sri.ai.grinder.sgdpllt.group.AssociativeCommutativeGroup) Util.pickKElementsWithoutReplacement(com.sri.ai.util.Util.pickKElementsWithoutReplacement) TRUE(com.sri.ai.expresso.helper.Expressions.TRUE) BruteForceCommonInterpreter(com.sri.ai.grinder.sgdpllt.interpreter.BruteForceCommonInterpreter) AssignmentsIterator(com.sri.ai.grinder.helper.AssignmentsIterator) SingleVariableConstraint(com.sri.ai.grinder.sgdpllt.api.SingleVariableConstraint) Expression(com.sri.ai.expresso.api.Expression) QuantifiedExpression(com.sri.ai.expresso.api.QuantifiedExpression) Constraint(com.sri.ai.grinder.sgdpllt.api.Constraint) DefaultMultiVariableConstraint(com.sri.ai.grinder.sgdpllt.core.constraint.DefaultMultiVariableConstraint) SingleVariableConstraint(com.sri.ai.grinder.sgdpllt.api.SingleVariableConstraint)

Example 52 with Context

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

the class TupleValuedFreeVariablesSimplifier method simplify.

public static Expression simplify(Expression expression, Context context) {
    Expression result = expression;
    // First see if we have any free variables.
    Map<Expression, Expression> freeVariablesAndTypes = Expressions.freeVariablesAndTypes(expression, context);
    if (freeVariablesAndTypes.size() > 0) {
        // Retrieve those that are tuples
        Map<Expression, TupleType> freeVariablesOfTupleType = freeVariablesAndTypes.entrySet().stream().filter(entry -> entry.getValue() != null && TupleType.isTupleType(entry.getValue())).collect(Collectors.toMap(e -> e.getKey(), e -> (TupleType) GrinderUtil.fromTypeExpressionToItsIntrinsicMeaning(e.getValue(), context)));
        if (freeVariablesOfTupleType.size() > 0) {
            final Map<Expression, List<Pair<Expression, Integer>>> freeVariableComponentsMap = constructComponentMap(freeVariablesOfTupleType, expression, context);
            // Replace the free tuple variables with their componentised forms
            // e.g. N --> (N1, N2)
            Expression componentisedExpression = expression.replaceAllOccurrences(expr -> {
                Expression replacement = expr;
                List<Pair<Expression, Integer>> replacementComponents = freeVariableComponentsMap.get(expr);
                if (replacementComponents != null) {
                    replacement = constructComponentTuple(replacementComponents);
                }
                return replacement;
            }, context);
            // Evaluate the expression with the un-componentized free tuple variables, within an extended
            // context that knows about the newly componentized variables
            Context contextExtendedWithComponentVariables = extendContextWithComponentVariables(context, freeVariablesOfTupleType, freeVariableComponentsMap);
            Expression evaluatedResult = context.getTheory().evaluate(componentisedExpression, contextExtendedWithComponentVariables);
            // Translate back the free variable components
            // e.g: 
            // if N1 = 2 then 29 else 30
            // ---->
            // if get(N, 1) = 2 then 29 else 30
            final Map<Expression, Pair<Expression, Integer>> componentToFreeVariableMap = createReverseLookupMap(freeVariableComponentsMap);
            result = evaluatedResult.replaceAllOccurrences(expr -> {
                Expression replacement = expr;
                Pair<Expression, Integer> correspondingFreeVariableWithIndex = componentToFreeVariableMap.get(expr);
                if (correspondingFreeVariableWithIndex != null) {
                    replacement = Expressions.apply(FunctorConstants.GET, correspondingFreeVariableWithIndex.first, correspondingFreeVariableWithIndex.second);
                }
                return replacement;
            }, contextExtendedWithComponentVariables);
        }
    }
    return result;
}
Also used : Type(com.sri.ai.expresso.api.Type) Simplifier(com.sri.ai.grinder.sgdpllt.rewriter.api.Simplifier) Expressions(com.sri.ai.expresso.helper.Expressions) Set(java.util.Set) Expression(com.sri.ai.expresso.api.Expression) Context(com.sri.ai.grinder.sgdpllt.api.Context) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) GrinderUtil(com.sri.ai.grinder.helper.GrinderUtil) List(java.util.List) TupleType(com.sri.ai.expresso.type.TupleType) Map(java.util.Map) LinkedHashSet(java.util.LinkedHashSet) FunctorConstants(com.sri.ai.grinder.sgdpllt.library.FunctorConstants) Pair(com.sri.ai.util.base.Pair) Context(com.sri.ai.grinder.sgdpllt.api.Context) Expression(com.sri.ai.expresso.api.Expression) TupleType(com.sri.ai.expresso.type.TupleType) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.sri.ai.util.base.Pair)

Example 53 with Context

use of com.sri.ai.grinder.sgdpllt.api.Context in project aic-praise by aic-sri-international.

the class HOGModelGrounding method ground.

public static void ground(FactorsAndTypes factorsAndTypes, List<Expression> evidence, Listener listener) {
    if (factorsAndTypes.getMapFromNonUniquelyNamedConstantNameToTypeName().size() > 0) {
        throw new IllegalArgumentException("Constants cannot be grounded");
    }
    Map<Expression, Triple<Expression, Integer, List<Expression>>> randomVariableNameToTypeSizeAndUniqueConstants = createRandomVariableNameToTypeSizeAndUniqueConstantsMap(factorsAndTypes);
    Map<Expression, Integer> randomVariableIndexes = new LinkedHashMap<>();
    AtomicInteger atomicVariableIndex = new AtomicInteger(-1);
    listener.numberGroundVariables(randomVariableNameToTypeSizeAndUniqueConstants.size());
    randomVariableNameToTypeSizeAndUniqueConstants.entrySet().forEach(entry -> {
        randomVariableIndexes.put(entry.getKey(), atomicVariableIndex.addAndGet(1));
        listener.groundVariableCardinality(atomicVariableIndex.get(), entry.getValue().second);
    });
    Map<Expression, List<Expression>> typeToValues = createTypeToValuesMap(factorsAndTypes, randomVariableNameToTypeSizeAndUniqueConstants);
    Map<String, String> newUniqueConstantToTypeMap = createGroundedUniqueConstantToTypeMap(typeToValues);
    InferenceForFactorGraphAndEvidence inferencer = makeInferencer(factorsAndTypes, newUniqueConstantToTypeMap);
    Context context = inferencer.makeContextWithTypeInformation();
    listener.numberFactors(factorsAndTypes.getFactors().size());
    int factorIndex = 0;
    for (Expression factor : factorsAndTypes.getFactors()) {
        ArrayList<Expression> randomVariablesInFactor = new ArrayList<>(Expressions.getSubExpressionsSatisfying(factor, randomVariableNameToTypeSizeAndUniqueConstants::containsKey));
        if (randomVariablesInFactor.size() == 0) {
            throw new IllegalArgumentException("Factor contains no random variables: " + factor);
        }
        int[] participantVariableIndexes = new int[randomVariablesInFactor.size()];
        for (int i = 0; i < randomVariablesInFactor.size(); i++) {
            Expression randomVariable = randomVariablesInFactor.get(i);
            participantVariableIndexes[i] = randomVariableIndexes.get(randomVariable);
        }
        listener.factorParticipants(factorIndex, participantVariableIndexes);
        if (!useContextSensitiveGrounding) {
            fullGrounding(factor, randomVariablesInFactor, listener, randomVariableNameToTypeSizeAndUniqueConstants, typeToValues, inferencer, context);
        } else {
            contextSensitiveGrounding(factor, randomVariablesInFactor, listener, randomVariableNameToTypeSizeAndUniqueConstants, typeToValues, inferencer, context);
        }
        factorIndex++;
    }
    // Handle the evidence
    for (Expression evidenceAssignment : evidence) {
        if (Expressions.isFunctionApplicationWithArguments(evidenceAssignment)) {
            // TODO - add support for 'not <variable>' and 'variable = value' and 'value = variable'
            throw new UnsupportedOperationException("Function application of evidence currently not supported: " + evidenceAssignment);
        } else if (Expressions.isSymbol(evidenceAssignment)) {
            int evidenceVariableIndex = randomVariableIndexes.get(evidenceAssignment);
            int evidenceValueIndex = typeToValues.get(randomVariableNameToTypeSizeAndUniqueConstants.get(evidenceAssignment).first).indexOf(Expressions.TRUE);
            listener.evidence(evidenceVariableIndex, evidenceValueIndex);
        }
    }
    listener.groundingComplete();
}
Also used : Context(com.sri.ai.grinder.sgdpllt.api.Context) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Triple(com.sri.ai.util.base.Triple) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) InferenceForFactorGraphAndEvidence(com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence) Expression(com.sri.ai.expresso.api.Expression) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) List(java.util.List)

Example 54 with Context

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

the class CompoundTheoryWithoutDifferenceArithmeticTest method runCompleteSatisfiabilityTest.

/**
	 * @param conjunction
	 * @param expected
	 */
private void runCompleteSatisfiabilityTest(String conjunction, Expression expected, Map<String, Type> variableNamesAndTypesForTesting) {
    TheoryTestingSupport equalityTheoryTestingSupport = TheoryTestingSupport.make(makeRandom(), new EqualityTheory(true, true));
    equalityTheoryTestingSupport.setVariableNamesAndTypesForTesting(variableNamesAndTypesForTesting);
    TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(makeRandom(), equalityTheoryTestingSupport, TheoryTestingSupport.make(makeRandom(), new PropositionalTheory()));
    Context context = theoryTestingSupport.makeContextWithTestingInformation();
    Constraint constraint = new CompleteMultiVariableContext(theoryTestingSupport.getTheory(), context);
    for (Expression literal : And.getConjuncts(parse(conjunction))) {
        constraint = constraint.conjoin(literal, context);
    }
    assertEquals(expected, constraint);
}
Also used : Context(com.sri.ai.grinder.sgdpllt.api.Context) TrueContext(com.sri.ai.grinder.sgdpllt.core.TrueContext) CompleteMultiVariableContext(com.sri.ai.grinder.sgdpllt.core.constraint.CompleteMultiVariableContext) CompleteMultiVariableContext(com.sri.ai.grinder.sgdpllt.core.constraint.CompleteMultiVariableContext) EqualityTheory(com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheory) Constraint(com.sri.ai.grinder.sgdpllt.api.Constraint) Expression(com.sri.ai.expresso.api.Expression) AbstractTheoryTestingSupport(com.sri.ai.grinder.sgdpllt.core.constraint.AbstractTheoryTestingSupport) TheoryTestingSupport(com.sri.ai.grinder.sgdpllt.tester.TheoryTestingSupport) PropositionalTheory(com.sri.ai.grinder.sgdpllt.theory.propositional.PropositionalTheory)

Example 55 with Context

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

the class CompoundTheoryWithoutDifferenceArithmeticTest method basicTests.

@Test
public void basicTests() {
    TheoryTestingSupport theoryTestingSupport = makeTheoryTestingSupport();
    Expression condition = parse("X = Y and Y = X and P and not Q and P and X = a and X != b");
    Context context = theoryTestingSupport.extendWithTestingInformation(new TrueContext(theoryTestingSupport.getTheory()));
    Constraint constraint = new CompleteMultiVariableContext(theoryTestingSupport.getTheory(), context);
    constraint = constraint.conjoin(condition, context);
    Expression expected = parse("(Y = a) and not Q and P and (X = Y)");
    assertEquals(expected, constraint);
}
Also used : Context(com.sri.ai.grinder.sgdpllt.api.Context) TrueContext(com.sri.ai.grinder.sgdpllt.core.TrueContext) CompleteMultiVariableContext(com.sri.ai.grinder.sgdpllt.core.constraint.CompleteMultiVariableContext) CompleteMultiVariableContext(com.sri.ai.grinder.sgdpllt.core.constraint.CompleteMultiVariableContext) Expression(com.sri.ai.expresso.api.Expression) Constraint(com.sri.ai.grinder.sgdpllt.api.Constraint) AbstractTheoryTestingSupport(com.sri.ai.grinder.sgdpllt.core.constraint.AbstractTheoryTestingSupport) TheoryTestingSupport(com.sri.ai.grinder.sgdpllt.tester.TheoryTestingSupport) TrueContext(com.sri.ai.grinder.sgdpllt.core.TrueContext) AbstractTheoryTest(com.sri.ai.test.grinder.sgdpllt.theory.base.AbstractTheoryTest) Test(org.junit.Test)

Aggregations

Context (com.sri.ai.grinder.sgdpllt.api.Context)105 Expression (com.sri.ai.expresso.api.Expression)80 Test (org.junit.Test)48 TheoryTestingSupport (com.sri.ai.grinder.sgdpllt.tester.TheoryTestingSupport)36 TrueContext (com.sri.ai.grinder.sgdpllt.core.TrueContext)30 Type (com.sri.ai.expresso.api.Type)28 DifferenceArithmeticTheory (com.sri.ai.grinder.sgdpllt.theory.differencearithmetic.DifferenceArithmeticTheory)28 PropositionalTheory (com.sri.ai.grinder.sgdpllt.theory.propositional.PropositionalTheory)22 EqualityTheory (com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheory)20 CompoundTheory (com.sri.ai.grinder.sgdpllt.theory.compound.CompoundTheory)18 Constraint (com.sri.ai.grinder.sgdpllt.api.Constraint)17 Map (java.util.Map)17 Beta (com.google.common.annotations.Beta)16 CompleteMultiVariableContext (com.sri.ai.grinder.sgdpllt.core.constraint.CompleteMultiVariableContext)16 Expressions.parse (com.sri.ai.expresso.helper.Expressions.parse)14 Theory (com.sri.ai.grinder.sgdpllt.api.Theory)14 LinearRealArithmeticTheory (com.sri.ai.grinder.sgdpllt.theory.linearrealarithmetic.LinearRealArithmeticTheory)14 FunctionType (com.sri.ai.expresso.type.FunctionType)13 Util (com.sri.ai.util.Util)13 SingleVariableConstraint (com.sri.ai.grinder.sgdpllt.api.SingleVariableConstraint)12