Search in sources :

Example 1 with InferenceForFactorGraphAndEvidence

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;
}
Also used : HOGModelException(com.sri.ai.praise.model.v1.HOGModelException) Expressions(com.sri.ai.expresso.helper.Expressions) Parser(com.sri.ai.expresso.api.Parser) ParsedHOGModel(com.sri.ai.praise.model.v1.hogm.antlr.ParsedHOGModel) Expression(com.sri.ai.expresso.api.Expression) FactorsAndTypes(com.sri.ai.praise.sgsolver.solver.FactorsAndTypes) Context(com.sri.ai.grinder.sgdpllt.api.Context) HOGModelException(com.sri.ai.praise.model.v1.HOGModelException) Theory(com.sri.ai.grinder.sgdpllt.api.Theory) HOGMParserWrapper(com.sri.ai.praise.model.v1.hogm.antlr.HOGMParserWrapper) ArrayList(java.util.ArrayList) Beta(com.google.common.annotations.Beta) GrinderUtil(com.sri.ai.grinder.helper.GrinderUtil) List(java.util.List) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes) RecognitionException(org.antlr.v4.runtime.RecognitionException) InferenceForFactorGraphAndEvidence(com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence) UnableToParseAllTheInputError(com.sri.ai.praise.model.v1.hogm.antlr.UnableToParseAllTheInputError) HOGMSortDeclaration(com.sri.ai.praise.model.v1.HOGMSortDeclaration) Collections(java.util.Collections) ParsedHOGModel(com.sri.ai.praise.model.v1.hogm.antlr.ParsedHOGModel) FactorsAndTypes(com.sri.ai.praise.sgsolver.solver.FactorsAndTypes) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes) ArrayList(java.util.ArrayList) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes) HOGMParserWrapper(com.sri.ai.praise.model.v1.hogm.antlr.HOGMParserWrapper) InferenceForFactorGraphAndEvidence(com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence) Expression(com.sri.ai.expresso.api.Expression) UnableToParseAllTheInputError(com.sri.ai.praise.model.v1.hogm.antlr.UnableToParseAllTheInputError) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 2 with InferenceForFactorGraphAndEvidence

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);
}
Also used : InferenceForFactorGraphAndEvidence(com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence) Expression(com.sri.ai.expresso.api.Expression) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes) Test(org.junit.Test)

Example 3 with InferenceForFactorGraphAndEvidence

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();
}
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 4 with InferenceForFactorGraphAndEvidence

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;
}
Also used : InferenceForFactorGraphAndEvidence(com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes)

Example 5 with InferenceForFactorGraphAndEvidence

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);
}
Also used : InferenceForFactorGraphAndEvidence(com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence) Expression(com.sri.ai.expresso.api.Expression) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes)

Aggregations

InferenceForFactorGraphAndEvidence (com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence)7 Expression (com.sri.ai.expresso.api.Expression)6 ExpressionFactorsAndTypes (com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes)6 Context (com.sri.ai.grinder.sgdpllt.api.Context)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Test (org.junit.Test)2 Beta (com.google.common.annotations.Beta)1 Parser (com.sri.ai.expresso.api.Parser)1 Expressions (com.sri.ai.expresso.helper.Expressions)1 GrinderUtil (com.sri.ai.grinder.helper.GrinderUtil)1 Theory (com.sri.ai.grinder.sgdpllt.api.Theory)1 TrueContext (com.sri.ai.grinder.sgdpllt.core.TrueContext)1 HOGMSortDeclaration (com.sri.ai.praise.model.v1.HOGMSortDeclaration)1 HOGModelException (com.sri.ai.praise.model.v1.HOGModelException)1 HOGMParserWrapper (com.sri.ai.praise.model.v1.hogm.antlr.HOGMParserWrapper)1 ParsedHOGModel (com.sri.ai.praise.model.v1.hogm.antlr.ParsedHOGModel)1 UnableToParseAllTheInputError (com.sri.ai.praise.model.v1.hogm.antlr.UnableToParseAllTheInputError)1 FactorsAndTypes (com.sri.ai.praise.sgsolver.solver.FactorsAndTypes)1 Triple (com.sri.ai.util.base.Triple)1