use of com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence in project aic-praise by aic-sri-international.
the class HOGMQueryRunner method query.
public List<HOGMQueryResult> query() {
List<HOGMQueryResult> result = new ArrayList<>();
Expression queryExpr = null;
//
ParsedHOGModel parsedModel = null;
for (String query : queries) {
long startQuery = System.currentTimeMillis();
List<HOGMQueryError> errors = new ArrayList<>();
try {
if (model == null || model.trim().equals("")) {
errors.add(new HOGMQueryError(HOGMQueryError.Context.MODEL, "Model not specified", 0, 0, 0));
}
if (query == null || query.trim().equals("")) {
errors.add(new HOGMQueryError(HOGMQueryError.Context.QUERY, "Query not specified", 0, 0, 0));
}
if (errors.size() == 0) {
HOGMParserWrapper parser = new HOGMParserWrapper();
if (parsedModel == null) {
parsedModel = parser.parseModel(model, new QueryErrorListener(HOGMQueryError.Context.MODEL, errors));
}
queryExpr = parser.parseTerm(query, new QueryErrorListener(HOGMQueryError.Context.QUERY, errors));
if (errors.size() == 0) {
FactorsAndTypes factorsAndTypes = new ExpressionFactorsAndTypes(parsedModel);
if (!canceled) {
inferencer = new InferenceForFactorGraphAndEvidence(factorsAndTypes, false, null, true, getOptionalTheory());
startQuery = System.currentTimeMillis();
Expression marginal = inferencer.solve(queryExpr);
result.add(new HOGMQueryResult(query, queryExpr, parsedModel, marginal, System.currentTimeMillis() - startQuery));
}
}
}
} catch (RecognitionException re) {
errors.add(new HOGMQueryError(HOGMQueryError.Context.MODEL, re.getMessage(), re.getOffendingToken().getLine(), re.getOffendingToken().getStartIndex(), re.getOffendingToken().getStopIndex()));
} catch (UnableToParseAllTheInputError utpai) {
errors.add(new HOGMQueryError(utpai));
} catch (HOGModelException me) {
me.getErrors().forEach(modelError -> {
String inStatement = modelError.getInStatementInfo().statement.toString();
String inSource = modelError.getInStatementInfo().sourceText;
String inSubStatement = modelError.getMessage();
String inInfo = "";
if (inSubStatement.equals("") || inSubStatement.equals(inSource)) {
inInfo = " in '" + inStatement + "'";
} else {
inInfo = " ('" + inSubStatement + "') in '" + inStatement + "'";
}
if (!inSource.replaceAll(" ", "").replaceAll(";", "").equals(inStatement.replaceAll(" ", ""))) {
inInfo = inInfo + " derived from '" + inSource + "'";
}
errors.add(new HOGMQueryError(HOGMQueryError.Context.MODEL, modelError.getErrorType().formattedMessage() + inInfo, modelError.getInStatementInfo().line, modelError.getInStatementInfo().startIndex, modelError.getInStatementInfo().endIndex));
});
} catch (Throwable t) {
// Unexpected
errors.add(new HOGMQueryError(t));
}
if (errors.size() > 0) {
result.add(new HOGMQueryResult(query, queryExpr, parsedModel, errors, System.currentTimeMillis() - startQuery));
}
}
return result;
}
use of com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence in project aic-praise by aic-sri-international.
the class InferenceForFactorGraphAndEvidenceTest method testAPI.
@Test
public void testAPI() {
// IMPORTANT: this test is reproduced in the User Guide as an example,
// so it should be kept in sync with it.
String modelString = "" + "random earthquake: Boolean;" + "random burglary: Boolean;" + "random alarm: Boolean;" + "" + "earthquake 0.01;" + "burglary 0.1;" + "" + "if earthquake" + " then if burglary" + " then alarm 0.95" + " else alarm 0.6" + " else if burglary" + " then alarm 0.9" + " else alarm 0.01;" + " " + "not alarm;" + "";
Expression evidence = parse("not alarm");
// can be any boolean expression
boolean isBayesianNetwork = true;
// is a Bayesian network, that is, factors are normalized
// and the sum of their product over all assignments to random variables is 1.
boolean exploitFactorization = true;
// exploit factorization (that is, employ Variable Elimination,
// as opposed to summing over the entire joint probability distribution).
InferenceForFactorGraphAndEvidence inferencer = new InferenceForFactorGraphAndEvidence(new ExpressionFactorsAndTypes(modelString), isBayesianNetwork, evidence, exploitFactorization, null);
Expression queryExpression;
Expression marginal;
queryExpression = parse("not earthquake");
// can be any boolean expression, or any random variable
marginal = inferencer.solve(queryExpression);
System.out.println("Marginal is " + marginal);
queryExpression = parse("earthquake");
marginal = inferencer.solve(queryExpression);
System.out.println("Marginal is " + marginal);
}
use of com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence 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.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence in project aic-praise by aic-sri-international.
the class HOGModelGrounding method makeInferencer.
/**
* Provides an appropriate {@link InferenceForFactorGraphAndEvidence} object.
* @param factorsAndTypes
* @param newUniqueConstantToTypeMap
* @return
*/
private static InferenceForFactorGraphAndEvidence makeInferencer(FactorsAndTypes factorsAndTypes, Map<String, String> newUniqueConstantToTypeMap) {
ExpressionFactorsAndTypes groundedFactorsAndTypesInformation = new ExpressionFactorsAndTypes(// factors
Collections.emptyList(), factorsAndTypes.getMapFromRandomVariableNameToTypeName(), factorsAndTypes.getMapFromNonUniquelyNamedConstantNameToTypeName(), newUniqueConstantToTypeMap, factorsAndTypes.getMapFromCategoricalTypeNameToSizeString(), // additional types
list());
InferenceForFactorGraphAndEvidence inferencer = new InferenceForFactorGraphAndEvidence(groundedFactorsAndTypesInformation, false, null, true, null);
return inferencer;
}
use of com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence in project aic-praise by aic-sri-international.
the class InferenceForFactorGraphAndEvidenceTest method runSimplifyTest.
private void runSimplifyTest() {
InferenceForFactorGraphAndEvidence inferencer;
Expression simplification;
inferencer = new InferenceForFactorGraphAndEvidence(new ExpressionFactorsAndTypes(factors, mapFromRandomVariableNameToTypeName, mapFromNonUniquelyNamedConstantNameToTypeName, mapFromUniquelyNamedConstantNameToTypeName, mapFromCategoricalTypeNameToSizeString, list()), isBayesianNetwork, evidence, true, null);
simplification = inferencer.simplify(queryExpression);
assertEquals(expected, simplification);
}
Aggregations