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);
}
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;
}
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();
}
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);
}
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);
}
Aggregations