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;
}
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;
}
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;
}
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;
}
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;
}
Aggregations