Search in sources :

Example 16 with FunctionType

use of com.sri.ai.expresso.type.FunctionType in project aic-expresso by aic-sri-international.

the class AssignmentsSamplingIterator method getTypeToSampleFrom.

public static Type getTypeToSampleFrom(Expression variable, Expression condition, Context context) {
    Type result = GrinderUtil.getTypeOfExpression(variable, context);
    if (result instanceof FunctionType) {
        FunctionType functionType = (FunctionType) result;
        result = new LazySampledFunctionType(functionType.getCodomain(), functionType.getArgumentTypes().toArray(new Type[functionType.getArity()]));
    } else {
        if (condition.equals(false)) {
            result = null;
        } else if (condition.equals(true)) {
        // we leave as is.
        } else if (result instanceof RealExpressoType || result instanceof RealInterval) {
            LinearRealArithmeticTheory theory = new LinearRealArithmeticTheory(true, true);
            SingleVariableLinearRealArithmeticConstraint constraint = (SingleVariableLinearRealArithmeticConstraint) theory.makeSingleVariableConstraint(variable, context);
            constraint = (SingleVariableLinearRealArithmeticConstraint) constraint.conjoin(condition, context);
            IntervalWithMeasureEquivalentToSingleVariableLinearRealArithmeticConstraintStepSolver solver = new IntervalWithMeasureEquivalentToSingleVariableLinearRealArithmeticConstraintStepSolver(constraint);
            Expression realInterval = solver.solve(context);
            if (Sets.isEmptySet(realInterval)) {
                // used to indicate an empty set.
                result = null;
            } else if (ExtensionalSets.isExtensionalSet(realInterval) && ExtensionalSets.isSingleton(realInterval)) {
                String singletonValue = realInterval.get(0).toString();
                result = new RealInterval("[" + singletonValue + ";" + singletonValue + "]");
            } else {
                result = new RealInterval(realInterval.toString());
            }
        } else if (result instanceof IntegerExpressoType || result instanceof IntegerInterval) {
            DifferenceArithmeticTheory theory = new DifferenceArithmeticTheory(true, true);
            SingleVariableDifferenceArithmeticConstraint constraint = (SingleVariableDifferenceArithmeticConstraint) theory.makeSingleVariableConstraint(variable, context);
            constraint = (SingleVariableDifferenceArithmeticConstraint) constraint.conjoin(condition, context);
            ValuesOfSingleVariableDifferenceArithmeticConstraintStepSolver solver = new ValuesOfSingleVariableDifferenceArithmeticConstraintStepSolver(constraint);
            // NOTE: the exceptions set returned here is implicit in the condition so no need to use it here.
            RangeAndExceptionsSet rangeAndExceptionsSet = (RangeAndExceptionsSet) solver.solve(context);
            if (rangeAndExceptionsSet.isEmpty()) {
                // used to indicate an empty set.
                result = null;
            } else if (rangeAndExceptionsSet.isSingleton()) {
                result = new IntegerInterval(rangeAndExceptionsSet.getSingleValue().intValueExact(), rangeAndExceptionsSet.getSingleValue().intValueExact());
            } else {
                result = new IntegerInterval(rangeAndExceptionsSet.getStrictLowerBound().intValueExact() + 1, rangeAndExceptionsSet.getNonStrictUpperBound().intValueExact());
            }
        }
    }
    if (result != null && !result.isSampleUniquelyNamedConstantSupported()) {
        throw new IllegalArgumentException("Unable to sample " + variable + " from " + result);
    }
    return result;
}
Also used : RangeAndExceptionsSet(com.sri.ai.grinder.theory.differencearithmetic.RangeAndExceptionsSet) FunctionType(com.sri.ai.expresso.type.FunctionType) IntegerInterval(com.sri.ai.expresso.type.IntegerInterval) DifferenceArithmeticTheory(com.sri.ai.grinder.theory.differencearithmetic.DifferenceArithmeticTheory) LinearRealArithmeticTheory(com.sri.ai.grinder.theory.linearrealarithmetic.LinearRealArithmeticTheory) IntervalWithMeasureEquivalentToSingleVariableLinearRealArithmeticConstraintStepSolver(com.sri.ai.grinder.theory.linearrealarithmetic.IntervalWithMeasureEquivalentToSingleVariableLinearRealArithmeticConstraintStepSolver) RealInterval(com.sri.ai.expresso.type.RealInterval) Type(com.sri.ai.expresso.api.Type) RealExpressoType(com.sri.ai.expresso.type.RealExpressoType) IntegerExpressoType(com.sri.ai.expresso.type.IntegerExpressoType) FunctionType(com.sri.ai.expresso.type.FunctionType) ValuesOfSingleVariableDifferenceArithmeticConstraintStepSolver(com.sri.ai.grinder.theory.differencearithmetic.ValuesOfSingleVariableDifferenceArithmeticConstraintStepSolver) Expression(com.sri.ai.expresso.api.Expression) IntegerExpressoType(com.sri.ai.expresso.type.IntegerExpressoType) RealExpressoType(com.sri.ai.expresso.type.RealExpressoType) SingleVariableDifferenceArithmeticConstraint(com.sri.ai.grinder.theory.differencearithmetic.SingleVariableDifferenceArithmeticConstraint) SingleVariableLinearRealArithmeticConstraint(com.sri.ai.grinder.theory.linearrealarithmetic.SingleVariableLinearRealArithmeticConstraint)

Example 17 with FunctionType

use of com.sri.ai.expresso.type.FunctionType in project aic-expresso by aic-sri-international.

the class Measure method get.

public static Rational get(Expression intensionalSetExpression, Context context) {
    Rational result;
    if (Sets.isIntensionalSet(intensionalSetExpression)) {
        IntensionalSet intensionalSet = (IntensionalSet) intensionalSetExpression;
        IndexExpressionsSet indexExpressionsSet = intensionalSet.getIndexExpressions();
        List<Expression> indices = IndexExpressions.getIndices(indexExpressionsSet);
        if (indices.size() == 1) {
            Expression evaluatedResult;
            Expression intensionalSetIndex = indices.get(0);
            Expression intensionalSetHead = intensionalSet.getHead();
            if (!intensionalSetHead.equals(intensionalSetIndex)) {
                throw new UnsupportedOperationException("Index and Head must be the same to calculate the meaure of an Intensional : " + intensionalSet);
            }
            Expression intensionalSetCondition = intensionalSet.getCondition();
            Context intensionalSetContext = context.extendWith(indexExpressionsSet);
            Type indexType = GrinderUtil.getTypeOfExpression(intensionalSetIndex, intensionalSetContext);
            if (intensionalSetCondition.equals(false)) {
                // short circuit known empty sets up front.
                evaluatedResult = Expressions.ZERO;
            } else if (indexType instanceof RealExpressoType || indexType instanceof RealInterval) {
                // NOTE : For Reals can always assume the condition is of this type.
                SingleVariableLinearRealArithmeticConstraint svConstraint = (SingleVariableLinearRealArithmeticConstraint) intensionalSetCondition;
                MeasureOfSingleVariableLinearRealArithmeticConstraintStepSolver realSolver = new MeasureOfSingleVariableLinearRealArithmeticConstraintStepSolver(svConstraint);
                evaluatedResult = realSolver.solve(intensionalSetContext);
            } else if (indexType instanceof FunctionType) {
                if (!intensionalSetCondition.equals(true)) {
                    throw new UnsupportedOperationException("Measure of intensional set with a function type domain currently do not support conditions: " + intensionalSet);
                }
                // measure(co-domain)^measure(domain)
                FunctionType indexFunctionType = (FunctionType) indexType;
                Expression condomainIntensionalSet = constructComponentIntensionalSet(indexFunctionType.getCodomain(), intensionalSet, ZERO, intensionalSetContext);
                Rational codomainMeasure = get(condomainIntensionalSet, intensionalSetContext);
                Rational domainMeasure = Rational.ONE;
                for (Type argDomainType : indexFunctionType.getArgumentTypes()) {
                    Expression argDomainIntensionalSet = constructComponentIntensionalSet(argDomainType, intensionalSet, ZERO, intensionalSetContext);
                    Rational argMeasure = get(argDomainIntensionalSet, intensionalSetContext);
                    domainMeasure = domainMeasure.multiply(argMeasure);
                }
                evaluatedResult = Expressions.makeSymbol(codomainMeasure.pow(domainMeasure.intValueExact()));
            } else if (indexType instanceof TupleType) {
                if (!intensionalSetCondition.equals(true)) {
                    throw new UnsupportedOperationException("Measure of intensional set with a tuple type domain currently do not support conditions: " + intensionalSet);
                }
                // (element_1, ..., element_n) = measure(element_1) * ... * measure(element_n)
                TupleType indexTupleType = (TupleType) indexType;
                Rational elementMeasuresProduct = Rational.ONE;
                for (Type elementType : indexTupleType.getElementTypes()) {
                    Expression elementDomainIntensionalSet = constructComponentIntensionalSet(elementType, intensionalSet, ZERO, intensionalSetContext);
                    Rational elementMeasure = get(elementDomainIntensionalSet, intensionalSetContext);
                    elementMeasuresProduct = elementMeasuresProduct.multiply(elementMeasure);
                }
                evaluatedResult = Expressions.makeSymbol(elementMeasuresProduct);
            } else {
                Expression countingFormula = new DefaultCountingFormula(indexExpressionsSet, intensionalSet.getCondition());
                evaluatedResult = context.getTheory().evaluate(countingFormula, context);
            }
            if (Expressions.isNumber(evaluatedResult)) {
                result = evaluatedResult.rationalValue();
            } else {
                throw new UnsupportedOperationException("Unable to compute a finite measure for: " + intensionalSet + ", got : " + evaluatedResult);
            }
        } else {
            throw new UnsupportedOperationException("Currently only support the measure of single indexed intensional sets: " + intensionalSet);
        }
    } else {
        throw new IllegalArgumentException("Not an intensional set: " + intensionalSetExpression);
    }
    return result;
}
Also used : Context(com.sri.ai.grinder.api.Context) Rational(com.sri.ai.util.math.Rational) FunctionType(com.sri.ai.expresso.type.FunctionType) DefaultCountingFormula(com.sri.ai.expresso.core.DefaultCountingFormula) RealInterval(com.sri.ai.expresso.type.RealInterval) Type(com.sri.ai.expresso.api.Type) RealExpressoType(com.sri.ai.expresso.type.RealExpressoType) FunctionType(com.sri.ai.expresso.type.FunctionType) TupleType(com.sri.ai.expresso.type.TupleType) IntensionalSet(com.sri.ai.expresso.api.IntensionalSet) Expression(com.sri.ai.expresso.api.Expression) RealExpressoType(com.sri.ai.expresso.type.RealExpressoType) TupleType(com.sri.ai.expresso.type.TupleType) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) IndexExpressionsSet(com.sri.ai.expresso.api.IndexExpressionsSet) SingleVariableLinearRealArithmeticConstraint(com.sri.ai.grinder.theory.linearrealarithmetic.SingleVariableLinearRealArithmeticConstraint) MeasureOfSingleVariableLinearRealArithmeticConstraintStepSolver(com.sri.ai.grinder.theory.linearrealarithmetic.MeasureOfSingleVariableLinearRealArithmeticConstraintStepSolver)

Example 18 with FunctionType

use of com.sri.ai.expresso.type.FunctionType in project aic-expresso by aic-sri-international.

the class InversionSimplifier method applyInversion.

private static Expression applyInversion(Expression summationIndexedByFunction, Expression summationIndexFunctionName, FunctionType summationIndexFunctionType, List<Expression> originalQuantifierOrder, List<Expression> inversionQuantifierOrder, Context context) {
    Expression result;
    int indexOfSummationIndexedByFunction = inversionQuantifierOrder.indexOf(summationIndexedByFunction);
    // NOTE: only products will bubble up before the summation.
    List<Expression> productsBefore = inversionQuantifierOrder.subList(0, indexOfSummationIndexedByFunction);
    Expression lastQuantifierHead = getHead(originalQuantifierOrder.get(originalQuantifierOrder.size() - 1));
    Context innerContext = context;
    for (Expression quantifier : originalQuantifierOrder) {
        innerContext = innerContext.extendWith(getIndexExpressions(quantifier));
    }
    Context lastQuantifierHeadContext = innerContext;
    // TODO - remove temporary hack which collapses the function's argument domains
    // due to all the domain arguments being treated as constants. Instead should be using
    // set expression types on singletons.
    // Determine which domain arguments from the summation function can be collapsed
    List<Expression> productsBeforeIndices = new ArrayList<>();
    for (Expression productBefore : productsBefore) {
        productsBeforeIndices.add(getIndexAndType(productBefore).first);
    }
    Set<Integer> domainArgsToRemove = new HashSet<>();
    Set<Integer> domainArgsHaveVar = new HashSet<>();
    new SubExpressionsDepthFirstIterator(lastQuantifierHead).forEachRemaining(e -> {
        if (e.hasFunctor(summationIndexFunctionName)) {
            for (int i = 0; i < e.numberOfArguments(); i++) {
                if (lastQuantifierHeadContext.getTheory().isVariable(e.get(0), lastQuantifierHeadContext)) {
                    domainArgsHaveVar.add(i);
                }
                if (productsBeforeIndices.contains(e.get(i)) || Util.thereExists(new SubExpressionsDepthFirstIterator(e.get(i)), es -> productsBeforeIndices.contains(es))) {
                    domainArgsToRemove.add(i);
                }
            }
        }
    });
    // Remove arg positions that were not populated by a variable.
    for (int i = 0; i < summationIndexFunctionType.getArity(); i++) {
        if (!domainArgsHaveVar.contains(i)) {
            domainArgsToRemove.add(i);
        }
    }
    List<Expression> argTypes = new ArrayList<>();
    for (int i = 0; i < summationIndexFunctionType.getArity(); i++) {
        if (!domainArgsToRemove.contains(i)) {
            argTypes.add(parse(summationIndexFunctionType.getArgumentTypes().get(i).getName()));
        }
    }
    Expression codomainType = parse(summationIndexFunctionType.getCodomain().getName());
    Expression summationIndexReducedType;
    if (argTypes.size() == 0) {
        summationIndexReducedType = codomainType;
    } else {
        summationIndexReducedType = FunctionType.make(codomainType, argTypes);
    }
    Expression summationIndex = IndexExpressions.makeIndexExpression(summationIndexFunctionName, summationIndexReducedType);
    Expression phi = lastQuantifierHead.replaceAllOccurrences(e -> {
        Expression r = e;
        if (e.hasFunctor(summationIndexFunctionName)) {
            List<Expression> argsToKeep = new ArrayList<>();
            for (int i = 0; i < e.numberOfArguments(); i++) {
                if (!domainArgsToRemove.contains(i)) {
                    argsToKeep.add(e.get(i));
                }
            }
            if (argsToKeep.size() > 0) {
                r = Expressions.apply(summationIndexFunctionName, argsToKeep);
            } else {
                r = summationIndexFunctionName;
            }
        }
        return r;
    }, lastQuantifierHeadContext);
    Expression summationHead = phi;
    for (int i = indexOfSummationIndexedByFunction + 1; i < inversionQuantifierOrder.size(); i++) {
        Expression quantifier = inversionQuantifierOrder.get(i);
        Expression quantifierIntensionalSet = IntensionalSet.intensionalMultiSet(getIndexExpressions(quantifier), summationHead, getCondition(quantifier));
        summationHead = Expressions.apply(quantifier.getFunctor(), quantifierIntensionalSet);
    }
    Expression innerSummation = IntensionalSet.intensionalMultiSet(new ExtensionalIndexExpressionsSet(summationIndex), summationHead, getCondition(summationIndexedByFunction));
    result = Expressions.apply(FunctorConstants.SUM, innerSummation);
    for (int i = productsBefore.size() - 1; i >= 0; i--) {
        Expression product = productsBefore.get(i);
        product = IntensionalSet.intensionalMultiSet(getIndexExpressions(product), result, getCondition(product));
        result = Expressions.apply(FunctorConstants.PRODUCT, product);
    }
    return result;
}
Also used : Context(com.sri.ai.grinder.api.Context) SubExpressionsDepthFirstIterator(com.sri.ai.expresso.helper.SubExpressionsDepthFirstIterator) Expressions(com.sri.ai.expresso.helper.Expressions) Expression(com.sri.ai.expresso.api.Expression) Sets(com.sri.ai.grinder.library.set.Sets) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) GrinderUtil(com.sri.ai.grinder.helper.GrinderUtil) And(com.sri.ai.grinder.library.boole.And) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) Equality(com.sri.ai.grinder.library.Equality) IndexExpressions(com.sri.ai.grinder.library.indexexpression.IndexExpressions) Expressions.parse(com.sri.ai.expresso.helper.Expressions.parse) IndexExpressionsSet(com.sri.ai.expresso.api.IndexExpressionsSet) Context(com.sri.ai.grinder.api.Context) Pair(com.sri.ai.util.base.Pair) Implication(com.sri.ai.grinder.library.boole.Implication) Type(com.sri.ai.expresso.api.Type) Disequality(com.sri.ai.grinder.library.Disequality) Set(java.util.Set) IntensionalSet(com.sri.ai.expresso.api.IntensionalSet) FunctionType(com.sri.ai.expresso.type.FunctionType) List(java.util.List) ForAll(com.sri.ai.grinder.library.boole.ForAll) Simplifier(com.sri.ai.grinder.rewriter.api.Simplifier) Util(com.sri.ai.util.Util) FunctorConstants(com.sri.ai.grinder.library.FunctorConstants) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) Expression(com.sri.ai.expresso.api.Expression) ArrayList(java.util.ArrayList) SubExpressionsDepthFirstIterator(com.sri.ai.expresso.helper.SubExpressionsDepthFirstIterator) HashSet(java.util.HashSet)

Example 19 with FunctionType

use of com.sri.ai.expresso.type.FunctionType in project aic-expresso by aic-sri-international.

the class InversionSimplifier method getIndexAndFunctionType.

private static Pair<Expression, FunctionType> getIndexAndFunctionType(Expression functionOnIntensionalSet, Context context) {
    IndexExpressionsSet indexExpressionsSet = getIndexExpressions(functionOnIntensionalSet);
    List<Expression> indices = IndexExpressions.getIndices(indexExpressionsSet);
    if (indices.size() != 1) {
        throw new UnsupportedOperationException("Currently only support singular indices");
    }
    Expression index = indices.get(0);
    Context intensionalSetContext = context.extendWith(indexExpressionsSet);
    Type type = GrinderUtil.getTypeOfExpression(index, intensionalSetContext);
    FunctionType functionType = null;
    if (type instanceof FunctionType) {
        functionType = (FunctionType) type;
    }
    Pair<Expression, FunctionType> result = new Pair<>(index, functionType);
    return result;
}
Also used : Context(com.sri.ai.grinder.api.Context) Type(com.sri.ai.expresso.api.Type) FunctionType(com.sri.ai.expresso.type.FunctionType) Expression(com.sri.ai.expresso.api.Expression) FunctionType(com.sri.ai.expresso.type.FunctionType) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) IndexExpressionsSet(com.sri.ai.expresso.api.IndexExpressionsSet) Pair(com.sri.ai.util.base.Pair)

Example 20 with FunctionType

use of com.sri.ai.expresso.type.FunctionType in project aic-expresso by aic-sri-international.

the class InversionSimplifier method simplify.

public static Expression simplify(Expression expression, Context context) {
    Expression result = expression;
    if (isSummationIndexedByFunctionOfQuantifiers(expression, context)) {
        // NOTE: at this point we know we have a summation indexed by a function
        Expression summationIndexedByFunction = expression;
        Pair<Expression, FunctionType> indexAndFunctionType = getIndexAndFunctionType(summationIndexedByFunction, context);
        Expression summationIndexFunctionName = indexAndFunctionType.first;
        FunctionType summationIndexFunctionType = indexAndFunctionType.second;
        List<Expression> originalQuantifierOrder = new ArrayList<>();
        collectQuantifiers(summationIndexedByFunction, originalQuantifierOrder);
        List<Expression> inversionQuantifierOrder = new ArrayList<>();
        if (isInversionPossible(summationIndexedByFunction, summationIndexFunctionName, summationIndexFunctionType, originalQuantifierOrder, inversionQuantifierOrder, context)) {
            result = applyInversion(summationIndexedByFunction, summationIndexFunctionName, summationIndexFunctionType, originalQuantifierOrder, inversionQuantifierOrder, context);
        }
    }
    return result;
}
Also used : Expression(com.sri.ai.expresso.api.Expression) FunctionType(com.sri.ai.expresso.type.FunctionType) ArrayList(java.util.ArrayList)

Aggregations

FunctionType (com.sri.ai.expresso.type.FunctionType)57 Test (org.junit.Test)28 Expression (com.sri.ai.expresso.api.Expression)23 Type (com.sri.ai.expresso.api.Type)22 IntegerInterval (com.sri.ai.expresso.type.IntegerInterval)17 Context (com.sri.ai.grinder.api.Context)15 Context (com.sri.ai.grinder.sgdpllt.api.Context)14 IndexExpressionsSet (com.sri.ai.expresso.api.IndexExpressionsSet)13 ArrayList (java.util.ArrayList)13 RealInterval (com.sri.ai.expresso.type.RealInterval)12 TheoryTestingSupport (com.sri.ai.grinder.sgdpllt.tester.TheoryTestingSupport)11 TheoryTestingSupport (com.sri.ai.grinder.tester.TheoryTestingSupport)11 TupleType (com.sri.ai.expresso.type.TupleType)10 StepSolver (com.sri.ai.grinder.api.StepSolver)10 StepSolver (com.sri.ai.grinder.sgdpllt.api.StepSolver)10 UnificationStepSolver (com.sri.ai.grinder.sgdpllt.theory.base.UnificationStepSolver)10 UnificationStepSolver (com.sri.ai.grinder.theory.base.UnificationStepSolver)10 Ignore (org.junit.Ignore)10 IntensionalSet (com.sri.ai.expresso.api.IntensionalSet)9 ExtensionalIndexExpressionsSet (com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet)9