Search in sources :

Example 1 with FunctionTable

use of com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable in project aic-praise by aic-sri-international.

the class TransformMarkovToBayes method newMegaFactor.

private static FactorTable newMegaFactor(MarkovNetwork markov, Set<Integer> varIdxs, List<FactorTable> factorsContainingC) {
    List<Integer> variableIndexes = new ArrayList<>(varIdxs);
    Map<Integer, Integer> varIdxToOffset = new LinkedHashMap<>();
    List<Integer> varCardinalities = new ArrayList<>();
    for (Integer varIdx : variableIndexes) {
        varIdxToOffset.put(varIdx, varIdxToOffset.size());
        varCardinalities.add(markov.cardinality(varIdx));
    }
    List<Double> entries = new ArrayList<>(FunctionTable.numEntriesFor(varCardinalities));
    List<Integer> varValues = new ArrayList<>();
    CartesianProductEnumeration<Integer> cpe = new CartesianProductEnumeration<>(FunctionTable.cardinalityValues(varCardinalities));
    while (cpe.hasMoreElements()) {
        List<Integer> assignments = cpe.nextElement();
        double product = 1;
        for (FactorTable ft : factorsContainingC) {
            varValues.clear();
            for (Integer varIdx : ft.getVariableIndexes()) {
                varValues.add(assignments.get(varIdxToOffset.get(varIdx)));
            }
            product *= ft.getTable().entryFor(varValues);
        }
        entries.add(product);
    }
    FactorTable result = new FactorTable(variableIndexes, new FunctionTable(varCardinalities, entries));
    return result;
}
Also used : FunctionTable(com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable) ArrayList(java.util.ArrayList) FactorTable(com.sri.ai.praise.core.representation.classbased.table.core.data.markov.FactorTable) CartesianProductEnumeration(com.sri.ai.util.collect.CartesianProductEnumeration) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with FunctionTable

use of com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable in project aic-praise by aic-sri-international.

the class UAIModelToExpressionFactorNetwork method createListOfExpressionsrepresentingTheFactorsFromAUAIModel.

private static List<Expression> createListOfExpressionsrepresentingTheFactorsFromAUAIModel(UAIModel uaiModel) {
    /*	This is similar to the way They do in the UAIMARSolver.
 *  However, I think it is easier to understand in my way(below, uncommented). 
 *  This code used the fact that one same factor can appear many times (e.g. to factors phi_i and phi_j 
 *  having the same table). 
 *  The UAI model Contains the following maps
 *   	-1 map that links a index to it's table (tableInstanceIdxToTable)
 *   	-one map that does the inverse operation (uniqueTableToTableInstanceIdxs). 
 *   Because a table can be used more than once, it links a FunctionTable to a list of indexes
 *   	-one map that each table to a unique index (sort of a id of each unique table)(getUniqueFunctionTable).
 *   My code only uses the 1st one, while the commented one uses the 2nd and third tables
 *   	
  		List<Expression> factorsRepresentedAsExpressions = new ArrayList<>();
		for (int i = 0; i < uaiModel.numberUniqueFunctionTables(); i++) {
			FunctionTable table = uaiModel.getUniqueFunctionTable(i);
			Expression genericTableExpression;
			genericTableExpression = constructGenericTableExpressionUsingEqualities(table);
			
			for (int tableIdx : uaiModel.getTableIndexes(i)) {
				Expression instanceTableExpression = 
						convertGenericTableToInstance(table, genericTableExpression, uaiModel.getVariableIndexesForTable(tableIdx));
				factorsRepresentedAsExpressions.add(instanceTableExpression);
			}	
		}
		return factorsRepresentedAsExpressions;*/
    List<Expression> factorsRepresentedAsExpressions = new ArrayList<>();
    for (int i = 0; i < uaiModel.numberTables(); i++) {
        FunctionTable table = uaiModel.getTable(i);
        Expression genericTableExpression = constructGenericTableExpressionUsingEqualities(table);
        Expression instanceTableExpression = convertGenericTableToInstance(table, genericTableExpression, uaiModel.getVariableIndexesForTable(i));
        factorsRepresentedAsExpressions.add(instanceTableExpression);
    }
    return factorsRepresentedAsExpressions;
}
Also used : Expression(com.sri.ai.expresso.api.Expression) FunctionTable(com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable) ArrayList(java.util.ArrayList)

Example 3 with FunctionTable

use of com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable in project aic-praise by aic-sri-international.

the class UAIModel method mergeEvidenceIntoModel.

public void mergeEvidenceIntoModel() {
    if (evidence.size() > 0) {
        // for the assignment value and 0 for all other values.
        for (Map.Entry<Integer, Integer> evidenceAssignment : evidence.entrySet()) {
            Integer evidenceVarIndex = evidenceAssignment.getKey();
            int evidenceValue = evidenceAssignment.getValue();
            int varCardinality = variableIndexToCardinality.get(evidenceVarIndex);
            List<Double> entries = new ArrayList<>();
            for (int i = 0; i < varCardinality; i++) {
                if (i == evidenceValue) {
                    entries.add(1.0);
                } else {
                    entries.add(0.0);
                }
            }
            FunctionTable evidenceFactor = new FunctionTable(Arrays.asList(varCardinality), entries);
            // 
            // Merge in with the other factor information
            tableInstanceVariableIndexes.add(Arrays.asList(evidenceVarIndex));
            tableInstanceIndexToTable.put(tableInstanceVariableIndexes.size() - 1, evidenceFactor);
        }
        // Ensure the unique mapping information is re-created.
        computeUniqueMappings();
    }
}
Also used : FunctionTable(com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 4 with FunctionTable

use of com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable in project aic-praise by aic-sri-international.

the class UAIUtil method constructGenericTableExpressionUsingEqualities.

/**
 * Returns an {@link Expression} equivalent to a given {@link FunctionTable} but in the form of a decision tree
 * (so hopefully more compact) using equalities.
 * @param functionTable
 * @param solverListener if not null, invoked on solver used for compilation, before and after compilation is performed; returned solver from "before" invocation is used (it may be the same one used as argument, of course).
 * @return
 */
public static Expression constructGenericTableExpressionUsingEqualities(FunctionTable functionTable, Function<MultiQuantifierEliminator, MultiQuantifierEliminator> solverListener) {
    StringBuilder table = new StringBuilder();
    CartesianProductEnumeration<Integer> cartesianProduct = new CartesianProductEnumeration<>(cardinalityValues(functionTable));
    int counter = 0;
    while (cartesianProduct.hasMoreElements()) {
        counter++;
        List<Integer> values = cartesianProduct.nextElement();
        Double entryValue = functionTable.entryFor(values);
        if (counter == cartesianProduct.size().intValue()) {
            // i.e. final value
            table.append(entryValue);
        } else {
            table.append("if ");
            for (int i = 0; i < values.size(); i++) {
                if (i > 0) {
                    table.append(" and ");
                }
                String value = genericConstantValueForVariable(values.get(i), i, functionTable.cardinality(i));
                if (value.equals("true")) {
                    table.append(genericVariableName(i));
                } else if (value.equals("false")) {
                    table.append("not " + genericVariableName(i));
                } else {
                    table.append(genericVariableName(i));
                    table.append(" = ");
                    table.append(value);
                }
            }
            table.append(" then ");
            table.append(entryValue);
            table.append(" else ");
        }
    }
    Expression inputExpression = Expressions.parse(table.toString());
    Function<Integer, Integer> cardinalityOfIthVariable = i -> functionTable.cardinality(i);
    Map<String, String> mapFromCategoricalTypeNameToSizeString = new LinkedHashMap<>();
    Map<String, String> mapFromVariableNameToTypeName = new LinkedHashMap<>();
    Map<String, String> mapFromUniquelyNamedConstantToTypeName = new LinkedHashMap<>();
    for (int i = 0; i < functionTable.numberVariables(); i++) {
        String typeName = genericTypeNameForVariable(i, cardinalityOfIthVariable.apply(i));
        mapFromCategoricalTypeNameToSizeString.put(typeName, "" + cardinalityOfIthVariable.apply(i));
        mapFromVariableNameToTypeName.put(genericVariableName(i), typeName);
        for (int j = 0; j != functionTable.cardinality(i); j++) {
            String jThConstant = genericConstantValueForVariable(j, i, functionTable.cardinality(i));
            mapFromUniquelyNamedConstantToTypeName.put(jThConstant, typeName);
        }
    }
    com.sri.ai.grinder.api.Theory theory = new EqualityTheory(true, true);
    Expression result = Compilation.compile(inputExpression, theory, mapFromVariableNameToTypeName, mapFromUniquelyNamedConstantToTypeName, mapFromCategoricalTypeNameToSizeString, list(), solverListener);
    return result;
}
Also used : EqualityTheory(com.sri.ai.grinder.theory.equality.EqualityTheory) CartesianProductEnumeration(com.sri.ai.util.collect.CartesianProductEnumeration) Expressions(com.sri.ai.expresso.helper.Expressions) Compilation(com.sri.ai.grinder.application.Compilation) Util.list(com.sri.ai.util.Util.list) IOException(java.io.IOException) Expression(com.sri.ai.expresso.api.Expression) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Beta(com.google.common.annotations.Beta) LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) TrueContext(com.sri.ai.grinder.core.TrueContext) Map(java.util.Map) Context(com.sri.ai.grinder.api.Context) SyntacticSubstitute(com.sri.ai.grinder.library.SyntacticSubstitute) BufferedReader(java.io.BufferedReader) FunctionTable(com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable) MultiQuantifierEliminator(com.sri.ai.grinder.api.MultiQuantifierEliminator) EqualityTheory(com.sri.ai.grinder.theory.equality.EqualityTheory) CartesianProductEnumeration(com.sri.ai.util.collect.CartesianProductEnumeration) LinkedHashMap(java.util.LinkedHashMap) Expression(com.sri.ai.expresso.api.Expression)

Example 5 with FunctionTable

use of com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable in project aic-praise by aic-sri-international.

the class UAIModelReader method read.

public static UAIModel read(Reader modelReader) throws IOException {
    UAIModel result = null;
    try (BufferedReader br = new BufferedReader(modelReader)) {
        Preamble preamble = readPreamble(br);
        Map<Integer, FunctionTable> tableIdxToTable = readFunctionTables(preamble, br);
        result = new UAIModel(preamble.type, preamble.variableToCardinality, preamble.tableVariableIdxs, tableIdxToTable);
    }
    return result;
}
Also used : FunctionTable(com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable) UAIModel(com.sri.ai.praise.core.representation.classbased.table.core.uai.UAIModel) BufferedReader(java.io.BufferedReader)

Aggregations

FunctionTable (com.sri.ai.praise.core.representation.classbased.table.core.data.FunctionTable)11 ArrayList (java.util.ArrayList)8 LinkedHashMap (java.util.LinkedHashMap)5 Expression (com.sri.ai.expresso.api.Expression)4 CartesianProductEnumeration (com.sri.ai.util.collect.CartesianProductEnumeration)4 Map (java.util.Map)3 Beta (com.google.common.annotations.Beta)2 MultiQuantifierEliminator (com.sri.ai.grinder.api.MultiQuantifierEliminator)2 FactorTable (com.sri.ai.praise.core.representation.classbased.table.core.data.markov.FactorTable)2 Pair (com.sri.ai.util.base.Pair)2 BufferedReader (java.io.BufferedReader)2 List (java.util.List)2 Function (java.util.function.Function)2 Expressions (com.sri.ai.expresso.helper.Expressions)1 FALSE (com.sri.ai.expresso.helper.Expressions.FALSE)1 TRUE (com.sri.ai.expresso.helper.Expressions.TRUE)1 Expressions.apply (com.sri.ai.expresso.helper.Expressions.apply)1 Expressions.makeSymbol (com.sri.ai.expresso.helper.Expressions.makeSymbol)1 Context (com.sri.ai.grinder.api.Context)1 Compilation (com.sri.ai.grinder.application.Compilation)1