use of com.sri.ai.util.math.Rational in project aic-expresso by aic-sri-international.
the class DifferenceArithmeticTheory method monomialOfDegreeOneIsDifferenceArithmeticTerm.
private static boolean monomialOfDegreeOneIsDifferenceArithmeticTerm(Monomial monomial, Context context) {
boolean result;
Rational coefficient = monomial.getNumericFactor();
boolean coefficientIsEitherOneOrMinusOne = coefficient.equals(Rational.ONE) || coefficient.equals(Rational.MINUS_ONE);
if (!coefficientIsEitherOneOrMinusOne) {
result = false;
} else {
Expression variable = getFirst(monomial.getOrderedNonNumericFactors());
boolean variableIsSymbol = variable.getSyntacticFormType().equals("Symbol");
result = variableIsSymbol && symbolIsIntegerTyped(variable, context);
}
return result;
}
use of com.sri.ai.util.math.Rational in project aic-expresso by aic-sri-international.
the class GrinderUtil method getTypeExpressionOfExpression.
/**
* Returns the type of given expression according to registry.
*/
public static Expression getTypeExpressionOfExpression(Expression expression, Registry registry) {
Expression result;
if (FormulaUtil.isApplicationOfBooleanConnective(expression)) {
result = makeSymbol("Boolean");
} else if (expression.getSyntacticFormType().equals(FunctionApplication.SYNTACTIC_FORM_TYPE) && list(SUM, PRODUCT, MAX).contains(expression.getFunctor().toString())) {
Expression argument = expression.get(0);
if (argument.getSyntacticFormType().equals(IntensionalSet.SYNTACTIC_FORM_TYPE)) {
IntensionalSet intensionalSetArgument = (IntensionalSet) argument;
Expression head = intensionalSetArgument.getHead();
// NOTE: Need to extend the registry as the index expressions in the quantifier may
// declare new types (i.e. function types).
Registry headRegistry = registry.extendWith(intensionalSetArgument.getIndexExpressions());
result = getTypeExpressionOfExpression(head, headRegistry);
} else if (argument.getSyntacticFormType().equals(ExtensionalSets.SYNTACTIC_FORM_TYPE)) {
List<Expression> arguments = ((AbstractExtensionalSet) argument).getElementsDefinitions();
result = getTypeOfCollectionOfNumericExpressionsWithDefaultInteger(arguments, registry);
} else if (expression.hasFunctor(MAX)) {
// MAX can also be applied to a bunch of numbers
result = getTypeOfCollectionOfNumericExpressionsWithDefaultInteger(expression.getArguments(), registry);
} else {
throw new Error(expression.getFunctor() + " defined for sets only but got " + expression.get(0));
}
} else if (Equality.isEquality(expression) || Disequality.isDisequality(expression)) {
result = makeSymbol("Boolean");
} else if (expression.equals(FunctorConstants.REAL_INTERVAL_CLOSED_CLOSED) || expression.equals(FunctorConstants.REAL_INTERVAL_CLOSED_OPEN) || expression.equals(FunctorConstants.REAL_INTERVAL_OPEN_CLOSED) || expression.equals(FunctorConstants.REAL_INTERVAL_OPEN_OPEN)) {
result = FunctionType.make(parse("Set"), parse("Number"), parse("Number"));
} else if (IfThenElse.isIfThenElse(expression)) {
Expression thenType = getTypeExpressionOfExpression(IfThenElse.thenBranch(expression), registry);
Expression elseType = getTypeExpressionOfExpression(IfThenElse.elseBranch(expression), registry);
if (thenType != null && elseType != null && (thenType.equals("Number") && isIntegerOrReal(elseType) || isIntegerOrReal(thenType) && elseType.equals("Number"))) {
result = makeSymbol("Number");
} else if (thenType != null && elseType != null && (thenType.equals("Integer") && elseType.equals("Real") || thenType.equals("Real") && elseType.equals("Integer"))) {
result = makeSymbol("Real");
} else if (thenType != null && (elseType == null || thenType.equals(elseType))) {
result = thenType;
} else if (elseType != null && (thenType == null || elseType.equals(thenType))) {
result = elseType;
} else if (thenType == null) {
throw new Error("Could not determine the types of then and else branches of '" + expression + "'.");
} else if (thenType.equals("Integer") && elseType.hasFunctor(INTEGER_INTERVAL)) {
// TODO: I know, I know, this treatment of integers and interval is terrible... will fix at some point
result = thenType;
} else if (thenType.hasFunctor(INTEGER_INTERVAL) && elseType.equals("Integer")) {
result = elseType;
} else if (thenType.hasFunctor(INTEGER_INTERVAL) && elseType.hasFunctor(INTEGER_INTERVAL)) {
IntegerInterval thenInterval = (IntegerInterval) thenType;
IntegerInterval elseInterval = (IntegerInterval) elseType;
Expression minimumLowerBound = LessThan.simplify(apply(LESS_THAN, thenInterval.getNonStrictLowerBound(), elseInterval.getNonStrictLowerBound()), registry).booleanValue() ? thenInterval.getNonStrictLowerBound() : elseInterval.getNonStrictLowerBound();
Expression maximumUpperBound = GreaterThan.simplify(apply(GREATER_THAN, thenInterval.getNonStrictUpperBound(), elseInterval.getNonStrictUpperBound()), registry).booleanValue() ? thenInterval.getNonStrictUpperBound() : elseInterval.getNonStrictUpperBound();
if (minimumLowerBound.equals(MINUS_INFINITY) && maximumUpperBound.equals(INFINITY)) {
result = makeSymbol("Integer");
} else {
result = apply(INTEGER_INTERVAL, minimumLowerBound, maximumUpperBound);
}
} else {
throw new Error("'" + expression + "' then and else branches have different types (" + thenType + " and " + elseType + " respectively).");
}
} else if (isCardinalityExpression(expression)) {
result = makeSymbol("Integer");
} else if (isNumericFunctionApplication(expression)) {
List<Expression> argumentTypes = mapIntoList(expression.getArguments(), e -> getTypeExpressionOfExpression(e, registry));
int firstNullArgumentTypeIndexIfAny = Util.getIndexOfFirstSatisfyingPredicateOrMinusOne(argumentTypes, t -> t == null);
if (firstNullArgumentTypeIndexIfAny != -1) {
throw new Error("Cannot determine type of " + expression.getArguments().get(firstNullArgumentTypeIndexIfAny) + ", which is needed for determining type of " + expression);
}
/**
* commonDomain is the co-domain shared by all argument function types, or empty tuple for arguments that are not function-typed.
* Therefore, if no argument is function-typed, it will be equal to the empty tuple.
*/
Expression commonDomain = getCommonDomainIncludingConversionOfNonFunctionTypesToNullaryFunctions(argumentTypes, registry);
if (commonDomain == null) {
throw new Error("Operator " + expression.getFunctor() + " applied to arguments of non-compatible types: " + expression + ", types of arguments are " + argumentTypes);
}
boolean noArgumentIsFunctionTyped = commonDomain.equals(EMPTY_TUPLE) && !thereExists(argumentTypes, t -> t.hasFunctor(FunctorConstants.FUNCTION_TYPE));
Expression resultCoDomain;
if (thereExists(argumentTypes, t -> Util.equals(getCoDomainOrItself(t), "Number"))) {
resultCoDomain = makeSymbol("Number");
} else if (thereExists(argumentTypes, t -> Util.equals(getCoDomainOrItself(t), "Real"))) {
resultCoDomain = makeSymbol("Real");
} else if (thereExists(argumentTypes, t -> isRealInterval(getCoDomainOrItself(t)))) {
resultCoDomain = makeSymbol("Real");
} else {
resultCoDomain = makeSymbol("Integer");
}
if (noArgumentIsFunctionTyped) {
result = resultCoDomain;
} else {
result = apply(FUNCTION_TYPE, commonDomain, resultCoDomain);
}
} else if (expression.hasFunctor(FunctorConstants.INTEGER_INTERVAL) || expression.hasFunctor(FunctorConstants.REAL_INTERVAL_CLOSED_CLOSED) || expression.hasFunctor(FunctorConstants.REAL_INTERVAL_OPEN_CLOSED) || expression.hasFunctor(FunctorConstants.REAL_INTERVAL_CLOSED_OPEN) || expression.hasFunctor(FunctorConstants.REAL_INTERVAL_OPEN_OPEN)) {
result = makeSymbol("Set");
} else if (isComparisonFunctionApplication(expression)) {
result = makeSymbol("Boolean");
} else if (expression.hasFunctor(FunctorConstants.FUNCTION_TYPE)) {
// very vague type for now
result = apply(FUNCTION_TYPE, makeSymbol("Set"), makeSymbol("Set"));
} else if (Sets.isIntensionalMultiSet(expression)) {
IntensionalSet set = (IntensionalSet) expression;
// NOTE: Need to extend the registry as the index expressions in the quantifier may
// declare new types (i.e. function types).
Registry headRegistry = registry.extendWith(set.getIndexExpressions());
Expression headType = getTypeExpressionOfExpression(set.getHead(), headRegistry);
result = new DefaultIntensionalMultiSet(list(), headType, TRUE);
} else if (Sets.isExtensionalSet(expression)) {
// very vague type for now
result = apply(FUNCTION_TYPE, makeSymbol("Set"));
} else if (expression.hasFunctor(FunctorConstants.INTERSECTION) || expression.hasFunctor(FunctorConstants.UNION) || expression.hasFunctor(FunctorConstants.INTENSIONAL_UNION)) {
// very vague type for now
result = apply(FUNCTION_TYPE, makeSymbol("Set"));
} else if (expression.getSyntacticFormType().equals(Symbol.SYNTACTIC_FORM_TYPE)) {
if (expression.getValue() instanceof Integer) {
result = makeSymbol("Integer");
} else if (expression.getValue() instanceof Double) {
result = makeSymbol("Real");
} else if (expression.getValue() instanceof Rational) {
Rational rational = (Rational) expression.getValue();
boolean isInteger = rational.isInteger();
result = makeSymbol(isInteger ? "Integer" : "Real");
} else if (expression.getValue() instanceof Number) {
result = makeSymbol("Number");
} else if (expression.getValue() instanceof String && expression.isStringLiteral()) {
result = makeSymbol("String");
} else if (expression.getValue() instanceof Boolean) {
result = makeSymbol("Boolean");
} else if (expression.equals(Expressions.INFINITY) || expression.equals(Expressions.MINUS_INFINITY)) {
result = makeSymbol("Number");
} else {
result = registry.getTypeExpressionOfRegisteredSymbol(expression);
if (result == null) {
Type type = getFirstSatisfyingPredicateOrNull(registry.getTypes(), t -> t.contains(expression));
if (type != null) {
result = parse(type.getName());
}
}
}
} else if (expression.hasFunctor(FunctorConstants.GET) && expression.numberOfArguments() == 2 && Expressions.isNumber(expression.get(1))) {
Expression argType = getTypeExpressionOfExpression(expression.get(0), registry);
if (TupleType.isTupleType(argType)) {
TupleType tupleType = (TupleType) GrinderUtil.fromTypeExpressionToItsIntrinsicMeaning(argType, registry);
result = parse(tupleType.getElementTypes().get(expression.get(1).intValue() - 1).toString());
} else {
throw new Error("get type from tuple for '" + expression + "' currently not supported.");
}
} else if (expression.hasFunctor(FunctorConstants.TUPLE_TYPE)) {
// Is a type expression already.
result = expression;
} else if (expression.getSyntacticFormType().equals(FunctionApplication.SYNTACTIC_FORM_TYPE)) {
Expression functionType = getTypeExpressionOfExpression(expression.getFunctor(), registry);
if (functionType == null) {
throw new Error("Type of '" + expression.getFunctor() + "' required but unknown.");
}
Expression coDomain = FunctionType.getCodomain(functionType);
List<Expression> argumentsTypesList = FunctionType.getArgumentList(functionType);
if (expression.getArguments().size() != argumentsTypesList.size()) {
throw new Error("Function " + expression.getFunctor() + " is of type " + functionType + " but has incorrect number of arguments = " + expression.getArguments());
}
for (int idx = 0; idx < expression.getArguments().size(); idx++) {
Expression arg = expression.get(idx);
Expression argExprType = argumentsTypesList.get(idx);
Type argType = registry.getTypeFromTypeExpression(argExprType);
if (!isSubtypeOf(arg, argType, registry)) {
throw new Error("Function " + expression.getFunctor() + " is of type " + functionType + " but has arguments that are not legal subtypes [#" + idx + "] = " + expression.getArguments());
}
}
result = coDomain;
} else if (Tuple.isTuple(expression)) {
List<Expression> elementTypes = expression.getArguments().stream().map(element -> getTypeExpressionOfExpression(element, registry)).collect(Collectors.toList());
result = TupleType.make(elementTypes);
} else if (expression instanceof QuantifiedExpressionWithABody) {
QuantifiedExpressionWithABody quantifiedExpressionWithABody = (QuantifiedExpressionWithABody) expression;
// NOTE: Need to extend the registry as the index expressions in the quantifier may
// declare new types (i.e. function types).
Registry quantifiedExpressionWithABodyRegistry = registry.extendWith(quantifiedExpressionWithABody.getIndexExpressions());
result = getTypeExpressionOfExpression(quantifiedExpressionWithABody.getBody(), quantifiedExpressionWithABodyRegistry);
} else if (expression instanceof LambdaExpression) {
LambdaExpression lambdaExpression = (LambdaExpression) expression;
Collection<Expression> domain = IndexExpressions.getIndexDomainsOfQuantifiedExpression(lambdaExpression);
IndexExpressionsSet indexExpressions = lambdaExpression.getIndexExpressions();
Registry lambdaExpressionWithABodyRegistry = registry.extendWith(indexExpressions);
Expression coDomain = getTypeExpressionOfExpression(lambdaExpression.getBody(), lambdaExpressionWithABodyRegistry);
result = Expressions.apply(FUNCTION_TYPE, domain, coDomain);
} else if (expression instanceof AbstractExpressionWrapper) {
Expression innerExpression = ((AbstractExpressionWrapper) expression).getInnerExpression();
result = getTypeExpressionOfExpression(innerExpression, registry);
} else {
throw new Error("GrinderUtil.getType does not yet know how to determine the type of this sort of expression: " + expression);
}
return result;
}
use of com.sri.ai.util.math.Rational in project aic-expresso by aic-sri-international.
the class Max method add.
@Override
public Expression add(Expression value1, Expression value2, Context context) {
Expression result;
if (value1.getValue() instanceof Number && value2.getValue() instanceof Number) {
Rational rationalValue1 = value1.rationalValue();
Rational rationalValue2 = value2.rationalValue();
if (rationalValue1.compareTo(rationalValue2) > 0) {
result = value1;
} else {
result = value2;
}
} else if (value1.equals(INFINITY) || value2.equals(INFINITY)) {
result = INFINITY;
} else if (isMinusInfinity(value1)) {
result = value2;
} else if (isMinusInfinity(value2)) {
result = value1;
} else {
result = Expressions.apply(MAX, value1, value2);
}
return result;
}
use of com.sri.ai.util.math.Rational in project aic-expresso by aic-sri-international.
the class DefaultSymbolTest method testDisplayLargeApproximateNumber.
@Test
public void testDisplayLargeApproximateNumber() {
Rational largeRational = new Rational(3).pow(100000);
Assert.assertEquals("1.33E47712", Expressions.makeSymbol(largeRational).toString());
largeRational = new Rational(3).pow(100000).divide(new Rational(7).pow(100));
Assert.assertEquals("4.13E47627", Expressions.makeSymbol(largeRational).toString());
}
use of com.sri.ai.util.math.Rational in project aic-expresso by aic-sri-international.
the class DefaultSymbolTest method testPrecisionOutput.
@Test
public void testPrecisionOutput() {
Assert.assertEquals("12345.68", Expressions.makeSymbol(12345.6789).toString());
//
// Positive
Assert.assertEquals("100000", Expressions.makeSymbol(100000).toString());
Assert.assertEquals("1E6", Expressions.makeSymbol(1000000).toString());
Assert.assertEquals("1E7", Expressions.makeSymbol(10000000).toString());
Assert.assertEquals("0.1", Expressions.makeSymbol(new Rational(1, 10)).toString());
Assert.assertEquals("0.01", Expressions.makeSymbol(new Rational(1, 100)).toString());
Assert.assertEquals("1E-3", Expressions.makeSymbol(new Rational(1, 1000)).toString());
Assert.assertEquals("1E-4", Expressions.makeSymbol(new Rational(1, 10000)).toString());
Assert.assertEquals("1E-5", Expressions.makeSymbol(0.00001).toString());
Assert.assertEquals("1E-6", Expressions.makeSymbol(0.000001).toString());
Assert.assertEquals("0.39", Expressions.makeSymbol(0.3928208).toString());
Assert.assertEquals("0.4", Expressions.makeSymbol(0.3998208).toString());
// 0.0129
Assert.assertEquals("0.01", Expressions.makeSymbol(new Rational(129, 10000)).toString());
Assert.assertEquals("123", Expressions.makeSymbol(123).toString());
// 10.0143
Assert.assertEquals("10.01", Expressions.makeSymbol(new Rational(100143, 10000)).toString());
// 10.926
Assert.assertEquals("10.93", Expressions.makeSymbol(new Rational(10926, 1000)).toString());
Assert.assertEquals("0.5", Expressions.makeSymbol(0.5).toString());
Assert.assertEquals("0.99", Expressions.makeSymbol(0.99).toString());
Assert.assertEquals("1", Expressions.makeSymbol(0.999).toString());
// 10.999
Assert.assertEquals("11", Expressions.makeSymbol(new Rational(10999, 1000)).toString());
// 19.999
Assert.assertEquals("20", Expressions.makeSymbol(new Rational(19999, 1000)).toString());
// 19.00000926
Assert.assertEquals("19", Expressions.makeSymbol(new Rational(1900000926, 100000000)).toString());
Assert.assertEquals("1", Expressions.makeSymbol(0.999973).toString());
// 100000.1
Assert.assertEquals("100000.1", Expressions.makeSymbol(new Rational(1000001, 10)).toString());
// 100000.9
Assert.assertEquals("100000.9", Expressions.makeSymbol(new Rational(1000009, 10)).toString());
// 123456.1
Assert.assertEquals("123456.1", Expressions.makeSymbol(new Rational(1234561, 10)).toString());
// 123456.9
Assert.assertEquals("123456.9", Expressions.makeSymbol(new Rational(1234569, 10)).toString());
// 123456.9
Assert.assertEquals("1.23E6", Expressions.makeSymbol(new Rational(12345679, 10)).toString());
Assert.assertEquals("1.23E9", Expressions.makeSymbol(1234567890).toString());
Assert.assertEquals("1E11", Expressions.makeSymbol(100234567890L).toString());
Assert.assertEquals("0.01", Expressions.makeSymbol(new Rational(1, 100)).toString());
Assert.assertEquals("1E-3", Expressions.makeSymbol(new Rational(1, 1000)).toString());
Assert.assertEquals("1E-4", Expressions.makeSymbol(new Rational(1, 10000)).toString());
Assert.assertEquals("1E-5", Expressions.makeSymbol(new Rational(1, 100000)).toString());
//
// Negative
Assert.assertEquals("-0.39", Expressions.makeSymbol(-0.3928208).toString());
Assert.assertEquals("-0.4", Expressions.makeSymbol(-0.3998208).toString());
// 0.0129
Assert.assertEquals("-0.01", Expressions.makeSymbol(new Rational(-129, 10000)).toString());
Assert.assertEquals("-123", Expressions.makeSymbol(-123).toString());
// 10.143
Assert.assertEquals("-10.01", Expressions.makeSymbol(new Rational(-100143, 10000)).toString());
// 10.926
Assert.assertEquals("-10.93", Expressions.makeSymbol(new Rational(-10926, 1000)).toString());
Assert.assertEquals("-0.5", Expressions.makeSymbol(-0.5).toString());
Assert.assertEquals("-0.99", Expressions.makeSymbol(-0.99).toString());
Assert.assertEquals("-1", Expressions.makeSymbol(-0.999).toString());
// 10.999
Assert.assertEquals("-11", Expressions.makeSymbol(new Rational(-10999, 1000)).toString());
// 19.999
Assert.assertEquals("-20", Expressions.makeSymbol(new Rational(-19999, 1000)).toString());
// 19.00000926
Assert.assertEquals("-19", Expressions.makeSymbol(new Rational(-1900000926, 100000000)).toString());
Assert.assertEquals("-1", Expressions.makeSymbol(-0.999973).toString());
// 100000.1
Assert.assertEquals("-100000.1", Expressions.makeSymbol(new Rational(-1000001, 10)).toString());
// 100000.9
Assert.assertEquals("-100000.9", Expressions.makeSymbol(new Rational(-1000009, 10)).toString());
// 123456.1
Assert.assertEquals("-123456.1", Expressions.makeSymbol(new Rational(-1234561, 10)).toString());
// 123456.9
Assert.assertEquals("-123456.9", Expressions.makeSymbol(new Rational(-1234569, 10)).toString());
// 123456.9
Assert.assertEquals("-1.23E6", Expressions.makeSymbol(new Rational(-12345679, 10)).toString());
Assert.assertEquals("-1.23E9", Expressions.makeSymbol(-1234567890).toString());
}
Aggregations