use of com.sri.ai.grinder.theory.equality.EqualityTheory in project aic-praise by aic-sri-international.
the class AnytimeExactBPTest method runGabriels.
private void runGabriels(String[] variableAndTypes, String factorNetworkString, String queryVariableString, Expression expected) {
Theory theory = new CompoundTheory(new EqualityTheory(false, true), new DifferenceArithmeticTheory(false, false), new LinearRealArithmeticTheory(false, false), new TupleTheory(), new PropositionalTheory());
Context context = new TrueContext(new CommonTheory()).extendWithSymbolsAndTypes(variableAndTypes);
ExpressionFactorNetwork factorNetwork = expressionFactorNetwork(factorNetworkString, context);
Expression query = Expressions.parse(queryVariableString);
// not sure it will work
Set<Expression> setOfFactors = new HashSet<>();
for (IdentityWrapper iw : factorNetwork.getAs()) {
ExpressionFactor f = (ExpressionFactor) iw.getObject();
Expression expressionFactor = f;
boolean successfullyAdded = setOfFactors.add(expressionFactor);
if (!successfullyAdded) {
setOfFactors.remove(expressionFactor);
Expression squareFactor = apply("*", expressionFactor, expressionFactor);
squareFactor = theory.evaluate(squareFactor, context);
setOfFactors.add(squareFactor);
}
}
// create model
Model m = new Model(setOfFactors, theory, context, false, query);
// do all iterations until the end, storing time
Iterator<PartitionTree> bfsExpander = new BFS(m);
IncrementalAnytimeBeliefPropagationWithSeparatorConditioning sbp = new IncrementalAnytimeBeliefPropagationWithSeparatorConditioning(m, bfsExpander);
long initialTime = System.currentTimeMillis();
Bound inferenceResult = null;
println("----------------solving with Gabriels----------------");
while (bfsExpander.hasNext()) {
inferenceResult = sbp.expandAndComputeInference();
// .normalize(theory, context));
println("Current bound on " + query + ": " + inferenceResult);
}
long finalTime = System.currentTimeMillis();
Expression normalizedResult = inferenceResult.normalize(theory, context);
normalizedResult = ((IntensionalSet) normalizedResult).getHead();
Expression normalizedexpected = PRAiSEUtil.normalize(query, expected, context);
println("Result factor: " + ((IntensionalSet) inferenceResult).getHead());
println("Normalized : " + normalizedResult);
// print the way it is done above
println("Time: " + (finalTime - initialTime) + " ms.");
println(normalizedexpected.equals(normalizedResult) ? "Correct!" : "Error!");
Expression test = parse("(" + normalizedResult + ") = (" + normalizedexpected + ")");
Expression testResult = context.evaluate(test);
assertEquals(TRUE, testResult);
}
use of com.sri.ai.grinder.theory.equality.EqualityTheory in project aic-praise by aic-sri-international.
the class RandomConditionalPotentialExpressionGenerator method newTheoryTestingSupport.
private TheoryTestingSupport newTheoryTestingSupport(Random random, RandomHOGMv1Generator.TheoryTypePropositionalArgs[] propositionTheoryArgs, RandomHOGMv1Generator.TheoryTypeEqualityArgs[] equalityTheoryArgs, RandomHOGMv1Generator.TheoryTypeInequalityArgs[] inequalityTheoryArgs) {
List<Theory> theories = new ArrayList<>();
if (propositionTheoryArgs.length > 0) {
theories.add(new PropositionalTheory());
}
if (equalityTheoryArgs.length > 0) {
EqualityTheory equalityTheory;
if (inequalityTheoryArgs.length == 0) {
// first flag is 'true' because all equalities are atoms in the final theory; there is no need to check arguments type
equalityTheory = new EqualityTheory(true, true);
} else {
// 'false' because not all equalities are atoms in this final theory; need to check arguments type
equalityTheory = new EqualityTheory(false, true);
}
theories.add(equalityTheory);
}
if (inequalityTheoryArgs.length > 0) {
DifferenceArithmeticTheory differenceArithmeticTheory;
if (equalityTheoryArgs.length == 0) {
// first flag is 'true' because all equalities are atoms in the final theory; there is no need to check arguments type
differenceArithmeticTheory = new DifferenceArithmeticTheory(true, true);
} else {
// 'false' because not all equalities are atoms in this final theory; need to check arguments type
differenceArithmeticTheory = new DifferenceArithmeticTheory(false, true);
}
theories.add(differenceArithmeticTheory);
}
Theory finalTheory;
if (theories.size() > 1) {
finalTheory = new CompoundTheory(theories.toArray(new Theory[theories.size()]));
} else {
finalTheory = theories.get(0);
}
TheoryTestingSupport result = TheoryTestingSupport.make(random, finalTheory);
return result;
}
use of com.sri.ai.grinder.theory.equality.EqualityTheory in project aic-praise by aic-sri-international.
the class UAIMARSolver method main.
public static void main(String[] args) throws IOException {
if (args.length != 4) {
throw new IllegalArgumentException("Usage: UAIMARSolver <file or directory with UAI-format files> <solution directory> <timeout in ms> equalities|difference_arithmetic");
}
File uaiInput = new File(args[0]);
if (!uaiInput.exists()) {
throw new IllegalArgumentException("File or directory specified does not exist: " + uaiInput.getAbsolutePath());
}
File solutionDir = new File(args[1]);
if (!solutionDir.exists() || !solutionDir.isDirectory()) {
throw new IllegalArgumentException("Solution directory is invalid: " + solutionDir.getAbsolutePath());
}
int maxSolverTimeInSeconds = Integer.parseInt(args[2]);
Theory theory;
if (args[3].equals("equalities")) {
theory = new CompoundTheory(new PropositionalTheory(), new EqualityTheory(true, true));
} else if (args[3].equals("difference_arithmetic")) {
theory = new CompoundTheory(new PropositionalTheory(), new DifferenceArithmeticTheory(true, true));
} else {
throw new IllegalArgumentException("4-th argument must be either 'equalities' or 'difference_arithmetic'");
}
List<UAIModel> models = new ArrayList<>();
Map<UAIModel, File> modelToFile = new HashMap<>();
if (uaiInput.isDirectory()) {
for (File uaiFile : uaiInput.listFiles((dir, name) -> name.endsWith(".uai"))) {
UAIModel model = read(uaiFile, solutionDir);
models.add(model);
modelToFile.put(model, uaiFile);
}
} else {
UAIModel model = read(uaiInput, solutionDir);
models.add(model);
modelToFile.put(model, uaiInput);
}
// Sort based on what we consider to be the simplest to hardest
// Collections.sort(models, (model1, model2) -> Double.compare(model1.ratioUniqueTablesToTables(), model2.ratioUniqueTablesToTables()));
// Collections.sort(models, (model1, model2) -> Integer.compare(model1.largestNumberOfFunctionTableEntries(), model2.largestNumberOfFunctionTableEntries()));
Collections.sort(models, (model1, model2) -> Integer.compare(model1.totalNumberEntriesForAllFunctionTables(), model2.totalNumberEntriesForAllFunctionTables()));
// Collections.sort(models, (model1, model2) -> Integer.compare(model1.numberTables(), model2.numberTables()));
Map<String, Boolean> modelSolvedStatus = new LinkedHashMap<>();
Map<String, Long> modelSolvedTime = new LinkedHashMap<>();
System.out.println("#models read=" + models.size());
final AtomicInteger cnt = new AtomicInteger(1);
models.stream().forEach(model -> {
System.out.println("Starting to Solve: " + modelToFile.get(model).getName() + " (" + cnt.getAndAdd(1) + " of " + models.size() + ")");
long start = System.currentTimeMillis();
boolean solved = solve(model, model.getEvidence(), model.getMARSolution(), maxSolverTimeInSeconds, theory);
long took = (System.currentTimeMillis() - start);
System.out.println("---- Took " + took + "ms. solved=" + solved);
modelSolvedStatus.put(modelToFile.get(model).getName(), solved);
modelSolvedTime.put(modelToFile.get(model).getName(), took);
});
System.out.println("MODELS SOLVE STATUS");
modelSolvedStatus.entrySet().stream().forEach(e -> System.out.printf("%-25s %-5b %12sms.\n", e.getKey(), e.getValue(), modelSolvedTime.get(e.getKey())));
System.out.println("SUMMARY");
System.out.println("#models solved=" + modelSolvedStatus.values().stream().filter(status -> status == true).count());
System.out.println("#models unsolved=" + modelSolvedStatus.values().stream().filter(status -> status == false).count());
}
use of com.sri.ai.grinder.theory.equality.EqualityTheory in project aic-praise by aic-sri-international.
the class UAIModelToExpressionFactorNetwork method convert.
public static ExpressionFactorNetwork convert(UAIModel uaiModel, Theory theory) {
List<Expression> factorsRepresentedAsExpressions = createListOfExpressionsrepresentingTheFactorsFromAUAIModel(uaiModel);
if (theory == null) {
theory = new CompoundTheory(new EqualityTheory(false, true), new DifferenceArithmeticTheory(false, true), new LinearRealArithmeticTheory(false, true), new PropositionalTheory());
}
// Add variables in the factors to the context...
ExpressionBasedModel factorsAndTypes = new UAI_to_ExpressionBased_Translator(factorsRepresentedAsExpressions, uaiModel);
// Context
Context context = fillingContext(theory, factorsAndTypes);
ExpressionFactorNetwork result = expressionFactorNetwork(factorsRepresentedAsExpressions, context);
return result;
}
use of com.sri.ai.grinder.theory.equality.EqualityTheory in project aic-expresso by aic-sri-international.
the class AssignmentsSamplingIteratorTest method setUp.
@Before
public void setUp() {
// Make tests repeatable
random = new Random(1);
conditionRewriter = new Recursive(new Exhaustive(new BruteForceCommonInterpreter()));
context = new TrueContext(new CompoundTheory(new DifferenceArithmeticTheory(false, false), new LinearRealArithmeticTheory(false, false), new EqualityTheory(false, false), new PropositionalTheory()));
}
Aggregations