From 26128fc1c2edadd7d919d9ea9eda48a2657159a7 Mon Sep 17 00:00:00 2001 From: Pearu Peterson Date: Mon, 14 Oct 2024 21:17:24 +0300 Subject: [PATCH 1/2] Add basic assume support. --- functional_algorithms/__init__.py | 1 + functional_algorithms/assume.py | 174 +++++++++++++++++++++ functional_algorithms/context.py | 1 + functional_algorithms/expr.py | 71 ++++++++- functional_algorithms/tests/test_assume.py | 13 ++ 5 files changed, 255 insertions(+), 5 deletions(-) create mode 100644 functional_algorithms/assume.py create mode 100644 functional_algorithms/tests/test_assume.py diff --git a/functional_algorithms/__init__.py b/functional_algorithms/__init__.py index 12ea605..b712ca7 100644 --- a/functional_algorithms/__init__.py +++ b/functional_algorithms/__init__.py @@ -19,3 +19,4 @@ from . import rewrite from .restrict import restrict from .signatures import filter_signatures +from .assume import assume diff --git a/functional_algorithms/assume.py b/functional_algorithms/assume.py new file mode 100644 index 0000000..441d73a --- /dev/null +++ b/functional_algorithms/assume.py @@ -0,0 +1,174 @@ +__all__ = ["assume", "check"] + +from collections import defaultdict +from .rewrite import op_flatten, op_expand +from .utils import number_types + + +class Choice: + """Holds a choice. + + A choice is a logical or-expression of relational operators lt and + eq. Other types of relational expressions are normalized to use lt + and eq operators only. + + For example, x >= y is expressed as a choice instance containing: + is_lt = {y: x} + is_eq = {x: y, y: x} + + For x != y, we'll have + is_lt = {x: y, y: x} + is_eq = {} + + For x > a or x < b, we'll have + is_lt = {a: x, x: b} + is_eq = {} + + For x > a and x <= b, we'll have two choice instances associated + with logical and-operation: + is_lt = {a: x} is_lt = {x: b} + is_eq = {} is_eq = {x: b, b: x} + + For (x > a and x <= b) or (x > c and x <= d), we'll have two + assumptions associated with logical or-operation. Both assumptions + contain two choice instances as explained above. + + """ + + def __init__(self, relational_expr): + self.is_lt = dict() # {lhs.key: rhs) + # is_gt mirrors is_lt + self.is_gt = dict() # {rhs.key: lhs) + self.is_eq = dict() # {lhs.key: rhs, rhs.key: lhs} + # is_ne mirrors is_lt + self.is_ne = dict() # {lhs.key: rhs, rhs.key: lhs} + + x, y = relational_expr.operands + if relational_expr.kind == "lt": + self.is_lt[x.key] = y + self.is_gt[y.key] = x + elif relational_expr.kind == "gt": + self.is_gt[x.key] = y + self.is_lt[y.key] = x + elif relational_expr.kind == "eq": + self.is_eq[x.key] = y + self.is_eq[y.key] = x + elif relational_expr.kind == "le": + self.is_lt[x.key] = y + self.is_gt[y.key] = x + self.is_eq[x.key] = y + self.is_eq[y.key] = x + elif relational_expr.kind == "ge": + self.is_gt[x.key] = y + self.is_lt[y.key] = x + self.is_eq[x.key] = y + self.is_eq[y.key] = x + elif relational_expr.kind == "ne": + self.is_ne[x.key] = y + self.is_ne[y.key] = x + else: + assert 0, relational_expr.kind # unreachable + + def register(self, x): + x.props + + +class Assumption: + """Holds a list of assumptions. + + An assumption is a logical and-expression of choices. + """ + + def __init__(self): + self.choices = [] + + +def assume(logical_expr): + for logical_and_expr in op_expand( + logical_expr, commutative=True, idempotent=True, over_commutative=True, over_idempotent=True, kind="logical_and" + ): + # print("AAA") + assumption = Assumption() + for expr in op_flatten(logical_and_expr, commutative=True, idempotent=True, kind="logical_and"): + assert expr.kind in {"lt", "gt", "le", "ge", "eq", "ne"}, expr.kind + # print(expr.key) + + choice = Choice(expr) + + +def assume_relational(x, rop, y): + n = f"_is_{rop}" + m = f'_is_{dict(lt="gt", le="ge", gt="lt", ge="le", eq="eq", ne="ne")[rop]}' + if n not in x.props: + x.props[n] = [] + if m not in y.props: + y.props[m] = [] + x.props[n].append(y) + y.props[m].append(x) + + +def _assume(logical_expr): + for expr in op_flatten(logical_expr, commutative=True, idempotent=True, kind="logical_and"): + if expr.kind in {"lt", "le", "gt", "ge", "eq", "ne"}: + x, y = expr.operands + assume_relational(x, expr.kind, y) + else: + raise NotImplementedError(expr.kind) + + +def check_relational(x, rop, y): + rel_op = dict( + lt=lambda x, y: x < y, + le=lambda x, y: x <= y, + gt=lambda x, y: x > y, + ge=lambda x, y: x >= y, + eq=lambda x, y: x == y, + ne=lambda x, y: x != y, + )[rop] + + if x.kind == "constant": + xvalue, xlike = x.operands + if y.kind == "constant": + yvalue, ylike = y.operands + if isinstance(xvalue, number_types) and isinstance(yvalue, number_types): + return rel_op(x, y) + + swap_rop = dict(lt="gt", le="ge", gt="lt", ge="le", eq="eq", ne="ne")[rop] + for y_ in x.props.get("_is_{rop}", []): + if y_ is y: + return True + + # print(f"{x=}") + # print(f"{rop, swap_rop=}") + # print(f"{y=}") + + for x_ in y.props.get("_is_{swap_rop}", []): + if x_ is x: + return True + + +def check_logical_and(logical_and_expr): + for expr in op_flatten(logical_and_expr, commutative=True, idempotent=True, kind="logical_and"): + r = check(expr) + if r is None: + return None + if r is False: + return False + return True + + +def check(logical_expr): + result = False + for expr in op_flatten(logical_expr, commutative=True, idempotent=True, kind="logical_or"): + if expr.kind in {"lt", "le", "gt", "ge", "eq", "ne"}: + x, y = expr.operands + r = check_relational(x, expr.kind, y) + elif expr.kind == "logical_and": + r = check_logical_and(expr) + else: + raise NotImplementedError(expr.kind) + if r is None: + result = None + if r is True: + return True + return result diff --git a/functional_algorithms/context.py b/functional_algorithms/context.py index 2d89591..16ddc42 100644 --- a/functional_algorithms/context.py +++ b/functional_algorithms/context.py @@ -7,6 +7,7 @@ from .utils import UNSPECIFIED, boolean_types, float_types, complex_types from .expr import Expr, make_constant, make_symbol, make_apply, known_expression_kinds from .typesystem import Type +from . import rewrite class Context: diff --git a/functional_algorithms/expr.py b/functional_algorithms/expr.py index b4d0ac2..59ff4b2 100644 --- a/functional_algorithms/expr.py +++ b/functional_algorithms/expr.py @@ -4,8 +4,8 @@ import warnings from .utils import UNSPECIFIED, warn_once, value_types, float_types, integer_types, number_types from .typesystem import Type -from .rewrite import RewriteContext - +from .rewrite import RewriteContext, op_flatten +from .assume import check known_expression_kinds = set( """ @@ -223,7 +223,9 @@ def wrap(self): name = mth.__name__ r = self.props.get(name, UNSPECIFIED) if r is UNSPECIFIED: - self.props[name] = r = mth(self) + r = mth(self) + if r is not None: + self.props[name] = r return r return wrap @@ -339,8 +341,10 @@ def __new__(cls, context, kind, operands): # props is a dictionary that contains reference_name and # force_ref. In general, its content could be anything. For - # instance, the results of `_is_foo` method calls are cached - # in props. + # instance, the results of `_is_positive/negative/...` method + # calls are cached in props. Also, `_is_gt/lt/...` lists are + # used to store assumptions: + # for all y in x.props['_is_gt'], x > y is assumed to hold. # When ref is specified in props, it is used as a variable # name referencing the expression. When an expression with @@ -691,6 +695,29 @@ def is_neginf(self): def is_inf(self): return self.context.logical_or(self.is_posinf, self.is_neginf) + def _assume_is_negative(self): + self.props.update( + _is_negative=True, _is_nonnegative=False, _is_positive=False, _is_zero=False, _is_nonzero=True, _is_one=False + ) + + def _assume_is_nonnegative(self): + self.props.update(_is_nonnegative=True, _is_negative=False) + + def _assume_is_positive(self): + self.props.update(_is_positive=True, _is_nonpositive=False, _is_negative=False, _is_zero=False, _is_nonzero=True) + + def _assume_is_nonpositive(self): + self.props.update(_is_nonpositive=True, _is_positive=False) + + def _assume_is_zero(self): + self.props.update(_is_zero=True, _is_nonzero=False, _is_positive=False, _is_negative=False, _is_one=False) + + def _assume_is_nonzero(self): + self.props.update(_is_nonzero=True, _is_zero=False) + + def _assume_is_one(self): + self.props.update(_is_zero=False, _is_nonzero=True, _is_positive=True, _is_negative=False, _is_one=True) + def _is(self, *props): result = True for prop in props: @@ -800,6 +827,7 @@ def _is_finite(self): @property @_is_cache def _is_nonnegative(self): + # self >= 0 assert not self.is_complex if self.kind == "constant": value, like = self.operands @@ -890,6 +918,39 @@ def _is_nonpositive(self): elif self.kind in {"square", "absolute"} and self.operands[0]._is_negative: return False + return check(self <= 0) + + for k, lst in self.props.items(): + if k == "_is_gt": + for x in lst: + # self > x > 0 => self <= 0 is False + # self > x >= 0 => self <= 0 is False + if x._is_positive or x._is_nonnegative: + return False + elif k == "_is_lt": + for x in lst: + # self < x <= 0 => self <= 0 is True + if x._is_nonpositive: + return True + elif k == "_is_ge": + for x in lst: + # self >= x > 0 => self <= 0 is False + if x._is_positive: + return False + elif k == "_is_le": + for x in lst: + # self <= x <= 0 => self <= 0 is True + if x._is_nonpositive: + return True + elif k == "_is_eq": + for x in lst: + # self == x <= 0 => self <= 0 is True + if x._is_nonpositive: + return True + # self == x > 0 => self <= 0 is False + if x._is_positive: + return False + @property @_is_cache def _is_positive(self): diff --git a/functional_algorithms/tests/test_assume.py b/functional_algorithms/tests/test_assume.py new file mode 100644 index 0000000..823bc2a --- /dev/null +++ b/functional_algorithms/tests/test_assume.py @@ -0,0 +1,13 @@ +import functional_algorithms as fa + +assert_equal = fa.expr.assert_equal + + +def test_assume(): + ctx = fa.Context(default_constant_type="float") + + x = ctx.symbol("x") + y = ctx.symbol("y") + z = ctx.symbol("z") + + fa.assume((x > 0) & ((y < z) | (y > 0))) From 6b4a1f039173074b70c4ba2036f19a45b1d6a3f6 Mon Sep 17 00:00:00 2001 From: Pearu Peterson Date: Sat, 19 Oct 2024 21:48:33 +0300 Subject: [PATCH 2/2] Revise the assumptions system. --- functional_algorithms/__init__.py | 16 +- functional_algorithms/assume.py | 174 ------ functional_algorithms/assumptions.py | 681 +++++++++++++++++++++ functional_algorithms/context.py | 8 +- functional_algorithms/expr.py | 45 +- functional_algorithms/rewrite.py | 181 +++++- functional_algorithms/tests/test_assume.py | 481 ++++++++++++++- functional_algorithms/tests/test_expr.py | 16 +- functional_algorithms/typesystem.py | 14 +- functional_algorithms/utils.py | 25 + 10 files changed, 1421 insertions(+), 220 deletions(-) delete mode 100644 functional_algorithms/assume.py create mode 100644 functional_algorithms/assumptions.py diff --git a/functional_algorithms/__init__.py b/functional_algorithms/__init__.py index b712ca7..0f207e3 100644 --- a/functional_algorithms/__init__.py +++ b/functional_algorithms/__init__.py @@ -1,4 +1,16 @@ -__all__ = ["Context", "Expr", "targets", "TextImage", "algorithms", "targets", "rewrite", "filter_signatures", "restrict"] +__all__ = [ + "Context", + "Expr", + "targets", + "TextImage", + "algorithms", + "targets", + "rewrite", + "filter_signatures", + "restrict", + "assume", + "check", +] try: from ._version import __version__ @@ -19,4 +31,4 @@ from . import rewrite from .restrict import restrict from .signatures import filter_signatures -from .assume import assume +from .assumptions import assume, check diff --git a/functional_algorithms/assume.py b/functional_algorithms/assume.py deleted file mode 100644 index 441d73a..0000000 --- a/functional_algorithms/assume.py +++ /dev/null @@ -1,174 +0,0 @@ -__all__ = ["assume", "check"] - -from collections import defaultdict -from .rewrite import op_flatten, op_expand -from .utils import number_types - - -class Choice: - """Holds a choice. - - A choice is a logical or-expression of relational operators lt and - eq. Other types of relational expressions are normalized to use lt - and eq operators only. - - For example, x >= y is expressed as a choice instance containing: - is_lt = {y: x} - is_eq = {x: y, y: x} - - For x != y, we'll have - is_lt = {x: y, y: x} - is_eq = {} - - For x > a or x < b, we'll have - is_lt = {a: x, x: b} - is_eq = {} - - For x > a and x <= b, we'll have two choice instances associated - with logical and-operation: - is_lt = {a: x} is_lt = {x: b} - is_eq = {} is_eq = {x: b, b: x} - - For (x > a and x <= b) or (x > c and x <= d), we'll have two - assumptions associated with logical or-operation. Both assumptions - contain two choice instances as explained above. - - """ - - def __init__(self, relational_expr): - self.is_lt = dict() # {lhs.key: rhs) - # is_gt mirrors is_lt - self.is_gt = dict() # {rhs.key: lhs) - self.is_eq = dict() # {lhs.key: rhs, rhs.key: lhs} - # is_ne mirrors is_lt - self.is_ne = dict() # {lhs.key: rhs, rhs.key: lhs} - - x, y = relational_expr.operands - if relational_expr.kind == "lt": - self.is_lt[x.key] = y - self.is_gt[y.key] = x - elif relational_expr.kind == "gt": - self.is_gt[x.key] = y - self.is_lt[y.key] = x - elif relational_expr.kind == "eq": - self.is_eq[x.key] = y - self.is_eq[y.key] = x - elif relational_expr.kind == "le": - self.is_lt[x.key] = y - self.is_gt[y.key] = x - self.is_eq[x.key] = y - self.is_eq[y.key] = x - elif relational_expr.kind == "ge": - self.is_gt[x.key] = y - self.is_lt[y.key] = x - self.is_eq[x.key] = y - self.is_eq[y.key] = x - elif relational_expr.kind == "ne": - self.is_ne[x.key] = y - self.is_ne[y.key] = x - else: - assert 0, relational_expr.kind # unreachable - - def register(self, x): - x.props - - -class Assumption: - """Holds a list of assumptions. - - An assumption is a logical and-expression of choices. - """ - - def __init__(self): - self.choices = [] - - -def assume(logical_expr): - for logical_and_expr in op_expand( - logical_expr, commutative=True, idempotent=True, over_commutative=True, over_idempotent=True, kind="logical_and" - ): - # print("AAA") - assumption = Assumption() - for expr in op_flatten(logical_and_expr, commutative=True, idempotent=True, kind="logical_and"): - assert expr.kind in {"lt", "gt", "le", "ge", "eq", "ne"}, expr.kind - # print(expr.key) - - choice = Choice(expr) - - -def assume_relational(x, rop, y): - n = f"_is_{rop}" - m = f'_is_{dict(lt="gt", le="ge", gt="lt", ge="le", eq="eq", ne="ne")[rop]}' - if n not in x.props: - x.props[n] = [] - if m not in y.props: - y.props[m] = [] - x.props[n].append(y) - y.props[m].append(x) - - -def _assume(logical_expr): - for expr in op_flatten(logical_expr, commutative=True, idempotent=True, kind="logical_and"): - if expr.kind in {"lt", "le", "gt", "ge", "eq", "ne"}: - x, y = expr.operands - assume_relational(x, expr.kind, y) - else: - raise NotImplementedError(expr.kind) - - -def check_relational(x, rop, y): - rel_op = dict( - lt=lambda x, y: x < y, - le=lambda x, y: x <= y, - gt=lambda x, y: x > y, - ge=lambda x, y: x >= y, - eq=lambda x, y: x == y, - ne=lambda x, y: x != y, - )[rop] - - if x.kind == "constant": - xvalue, xlike = x.operands - if y.kind == "constant": - yvalue, ylike = y.operands - if isinstance(xvalue, number_types) and isinstance(yvalue, number_types): - return rel_op(x, y) - - swap_rop = dict(lt="gt", le="ge", gt="lt", ge="le", eq="eq", ne="ne")[rop] - for y_ in x.props.get("_is_{rop}", []): - if y_ is y: - return True - - # print(f"{x=}") - # print(f"{rop, swap_rop=}") - # print(f"{y=}") - - for x_ in y.props.get("_is_{swap_rop}", []): - if x_ is x: - return True - - -def check_logical_and(logical_and_expr): - for expr in op_flatten(logical_and_expr, commutative=True, idempotent=True, kind="logical_and"): - r = check(expr) - if r is None: - return None - if r is False: - return False - return True - - -def check(logical_expr): - result = False - for expr in op_flatten(logical_expr, commutative=True, idempotent=True, kind="logical_or"): - if expr.kind in {"lt", "le", "gt", "ge", "eq", "ne"}: - x, y = expr.operands - r = check_relational(x, expr.kind, y) - elif expr.kind == "logical_and": - r = check_logical_and(expr) - else: - raise NotImplementedError(expr.kind) - if r is None: - result = None - if r is True: - return True - return result diff --git a/functional_algorithms/assumptions.py b/functional_algorithms/assumptions.py new file mode 100644 index 0000000..c6ec992 --- /dev/null +++ b/functional_algorithms/assumptions.py @@ -0,0 +1,681 @@ +r"""Design of assumption system +--------------------------- + +The assumption system is needed for branching between different +computational paths depending on the conditions postulated on inputs. + +As a simple example, if `x` is non-negative, `abs(x)` can be evaluated +as `x`, and if `x` is negative, then as `-x`. The sign of `x` can be +specifed using `assume` function. Here are three possible +alternatives: + + assume(x > -3) + assume(x > 2) + assume(x < -1) + +When no assumptions are given, or when `x > -3` is assumed, `abs(x)` +cannot be rewritten. In other cases, however, `abs(x)` can be +rewritten as `x` or `-x` when `x > 2` or `x < -1` is assumed, +respectively. + +Consider a system of logical expressions that involve relational +expressions and logical operations such as conjunction, disjunction, +negation, or exclusive disjunction. When collecting all non-boolean +symbols in this system (that is, all the symbols that are present in +relational expressions), the truth value of the system (`logical_expr +== true` for all logical expressions in the system) defines a subset +in a multi-dimensional space that coordinates are the non-boolean +symbols. + +For example, the following logical expression + + 2 * x + y > 0 and x <= 0 + +has two non-boolean symbols x and y and the given system of +inequalities defines a subset in the second quarter of x-y plane that +looks like unbounded triangle: + + ^ y + ........| + \xxxxxxx| + \xxxxxx| + \xxxxx| + \xxxx| + \xxx| + \xx| + \x| + \| + -------------------0-------------------> x + +When calling + + assume(y > -2 * x) + assume(x <= 0) + +then it means that all possible values to symbols x, y are those +point pairs that are in the subset defined by the system of +inequalities defined above. + +We define the following tools for the assumption system: + +- `is_subset_of(logical_expr, other_logical_expr)` that returns true + when a subset A (defined logical_expr) is a subset of B (defined by + other_logical_expr), false when there exists A subset that is not a + subset of B, or result_logical_expr that defines a set R such that + B = intersection(A, R) + + For example, + + is_subset_of((y > -2 * x) & (x <= 0), y >= 0) -> true + is_subset_of((y > -2 * x) & (x <= 0), y <= 0) -> false + is_subset_of((y > -2 * x) & (x <= 0), y == 1) -> y == 1 + +- `assume(logical_expr)` that defines restrictions to non-boolean + subexpressions used in the specified logical expression. The + restrictions are saved in `.props['_assumptions']` + dictionary. + +- `assume(nonlogical_expr)` that generates restrictions to + subexpressions used in the specified non-logical expression. + +- `check(logical_expr)` +""" + +__all__ = ["assume", "check"] + +from collections import defaultdict +from . import rewrite +from .utils import number_types +from .targets import symbolic + + +def _rewrite(mth): + def wrapper(self, *args): + r = mth(self, *args) + if r is not None: + r = r.rewrite(rewrite) + return r + + return wrapper + + +@_rewrite +def is_subset_of(logical_expr, other): + """Check if logical_expr is a subset of other logical expression. + + Definition: + + logical_expr(x) is a subset of other logical_expr(x) + + when + + other logical_expr(x) is true for all x such that logical_expr(x) is true + + where x is a set of all non-boolean symbols present in logical + expressions. + + The logical expression may contain logical `or`, logical `and`, or + relational operations. + + The `is_subset_of` function either returns true, false, or a + result logical expression such that + + is_subset_of(logical_expr & result_logical_expr, other_logical_expr) + + would return true. + """ + + boolean = logical_expr.context.constant + false = boolean(False) + true = boolean(True) + + if other.kind == "logical_and": + operands = [] + for o in rewrite.op_flatten(other, commutative=True, idempotent=True): + r = is_subset_of(logical_expr, o) + if r is false: + return false + if r is true: + continue + operands.append(o if r is None else r) + if operands: + return rewrite.op_unflatten(operands, "logical_and") + return true + + elif other.kind == "logical_or": + operands = [] + for o in rewrite.op_flatten(other, commutative=True, idempotent=True): + r = is_subset_of(logical_expr, o) + if r is true: + return true + if r is false: + continue + operands.append(o if r is None else r) + if operands: + return rewrite.op_unflatten(operands, "logical_or") + return false + + elif logical_expr.kind == "logical_and": + input_operands = list(rewrite.op_flatten(logical_expr, commutative=True, idempotent=True)) + operands = [] + for expr in input_operands: + r = is_subset_of(expr, other) + if r is true: + return true + if r is false: + return false + assert r is not None + if [None for inp in input_operands if normalize(inp).key == normalize(r).key]: + continue + operands.append(r) + if operands: + return rewrite.op_unflatten(operands, "logical_or") + return true + + elif logical_expr.kind == "logical_or": + operands = [] + for expr in rewrite.op_flatten(logical_expr, commutative=True, idempotent=True): + r = is_subset_of(expr, other) + if r is true: + continue + if r is false: + return false + assert r is not None + operands.append(r) + if operands: + return rewrite.op_unflatten(operands, "logical_and") + return false + + elif logical_expr.kind in {"lt", "gt", "le", "ge", "eq", "ne"} and logical_expr.kind in { + "lt", + "gt", + "le", + "ge", + "eq", + "ne", + }: + r = relational_is_subset_of(logical_expr, other) + + return r + + raise NotImplementedError((logical_expr.kind, other.kind)) + + +def normalize(expr): + if expr.kind == "ge": + return expr.context.le(*(expr.operands[::-1])) + elif expr.kind == "gt": + return expr.context.lt(*(expr.operands[::-1])) + elif expr.kind == "eq" and expr.operands[0]._is_constant: + return expr.context.eq(*(expr.operands[::-1])) + elif expr.kind == "ne" and expr.operands[0]._is_constant: + return expr.context.ne(*(expr.operands[::-1])) + return expr + + +def relational_is_subset_of(rel_expr, other): + ctx = rel_expr.context + boolean = ctx.constant + false = boolean(False) + true = boolean(True) + + r1 = normalize(rel_expr) + r2 = normalize(other) + + rop1, (lhs1, rhs1) = r1.kind, r1.operands + rop2, (lhs2, rhs2) = r2.kind, r2.operands + + def ispair(x, y): + if x._is_constant: + return False + return x is y + + def make_largest(x): + return x.context.constant("largest", x) + + def is_eq_posinf(x): + return x == x.context.constant("posinf", x) + + def is_eq_neginf(x): + return x == x.context.constant("neginf", x) + + def is_ne_posinf(x): + return x != x.context.constant("posinf", x) + + def is_ne_neginf(x): + return x != x.context.constant("neginf", x) + + def is_ne_inf(x): + return (x != x.context.constant("neginf", x)) & (x != x.context.constant("posinf", x)) + + def is_lt_largest(x): + return x < x.context.constant("largest", x) + + if rop1 == "lt": + # x < a is a subset of x < b if (a <= b) and b != -inf + # x < a is a subset of b < x if b < x and b < a and b != -inf + # a < x is a subset of x < b if x < b and a < b and b != inf + # a < x is a subset of b < x if (b <= a) and b != inf + + # x < a is a subset of x <= b if a <= b or b == -inf + # x < a is a subset of b <= x if (b <= x and b < a) or (b == -inf) + # a < x is a subset of x <= b if (x <= b and b > a) or (b == inf) + # a < x is a subset of b <= x if b <= a or b == inf + + # x < a is a subset of x == b if (b == x and a > b) and (abs(b) != inf) + # x < a is a subset of b == x if (b == x and a > b) + # a < x is a subset of x == b if (b == x and a < b) and (abs(b) != inf) + # a < x is a subset of b == x if (b == x and a < b) + + # x < a is a subset of x != b if (b >= a) and (b is not x) or (b == -inf and -a < largest) + # x < a is a subset of b != x if (b >= a) and (b is not x) or (b == -inf and -a < largest) + # a < x is a subset of x != b if (b <= a) and (b is not x) or (b == inf and a < largest) + # a < x is a subset of b != x if (b <= a) and (b is not x) or (b == inf and a < largest) + if rop2 == "lt": + if lhs2 is rhs2: + return false + if ispair(lhs1, lhs2): + return (rhs1 <= rhs2) & is_ne_neginf(rhs2) + if ispair(lhs1, rhs2): + return (lhs2 < rhs2) & (lhs2 < rhs1) & is_ne_neginf(lhs2) + if ispair(rhs1, lhs2): + return (lhs2 < rhs2) & (lhs1 < rhs2) & is_ne_posinf(rhs2) + if ispair(rhs1, rhs2): + return (lhs2 <= lhs1) & is_ne_posinf(lhs2) + elif rop2 == "le": + if lhs2 is rhs2: + return true + if ispair(lhs1, lhs2): + return (rhs1 <= rhs2) | is_eq_neginf(rhs2) + if ispair(lhs1, rhs2): + return ((lhs2 <= rhs2) & (lhs2 < rhs1)) | is_eq_neginf(lhs2) + if ispair(rhs1, lhs2): + return ((lhs2 <= rhs2) & (lhs1 < rhs2)) | is_eq_posinf(rhs2) + if ispair(rhs1, rhs2): + return (lhs2 <= lhs1) | is_eq_posinf(lhs2) + elif rop2 == "eq": + if lhs2 is rhs2: + return true + if ispair(lhs1, lhs2): + return ((lhs2 == rhs2) & (rhs1 > rhs2)) & is_ne_inf(rhs2) + if ispair(lhs1, rhs2): + return (lhs2 == rhs2) & (rhs1 > lhs2) + if ispair(rhs1, lhs2): + return ((lhs2 == rhs2) & (lhs1 < rhs2)) & is_ne_inf(rhs2) + if ispair(rhs1, rhs2): + return (lhs2 == rhs2) & (lhs1 < lhs2) + elif rop2 == "ne": + if lhs2 is rhs2: + return false + if ispair(lhs1, lhs2): + return (rhs2 >= rhs1) | (is_eq_neginf(rhs2) & is_lt_largest(-rhs1)) + if ispair(lhs1, rhs2): + return (lhs2 >= rhs1) | (is_eq_neginf(lhs2) & is_lt_largest(-rhs1)) + if ispair(rhs1, lhs2): + return (rhs2 <= lhs1) | (is_eq_posinf(rhs2) & is_lt_largest(lhs1)) + if ispair(rhs1, rhs2): + return (lhs2 <= lhs1) | (is_eq_posinf(lhs2) & is_lt_largest(lhs1)) + else: + assert 0 # unreachable + elif rop1 == "le": + # x <= a is a subset of x < b if a < b + # x <= a is a subset of b < x if b < x and b < a and b != -inf + # a <= x is a subset of x < b if x < b and a < b and b != inf + # a <= x is a subset of b < x if b < a + + # x <= a is a subset of x <= b if a <= b + # x <= a is a subset of b <= x if (x >= b and b < a) or (x == b and a == b) or (b == -inf) + # a <= x is a subset of x <= b if (x <= b and a < b) or (x == b and a == b) or (b == inf) + # a <= x is a subset of b <= x if b <= a + + # x <= a is a subset of x == b if (a == b and a == -inf) or (x == b and b <= a) + # x <= a is a subset of b == x if (a == b and a == -inf) + # a <= x is a subset of x == b if (a == b and a == inf) or (x == b and b >= a) + # a <= x is a subset of b == x if (a == b and a == inf) or (x == b and b >= a) + + # x <= a is a subset of x != b if (b > a) and (b is not x) + # x <= a is a subset of b != x if (b > a) and (b is not x) + # a <= x is a subset of x != b if (b < a) and (b is not x) + # a <= x is a subset of b != x if (b < a) and (b is not x) + if rop2 == "lt": + if lhs2 is rhs2: + return false + if ispair(lhs1, lhs2): + return rhs1 < rhs2 + if ispair(lhs1, rhs2): + return (lhs2 < rhs2) & (lhs2 < rhs1) & is_ne_neginf(lhs2) + if ispair(rhs1, lhs2): + return (lhs2 < rhs2) & (rhs2 > lhs1) & is_ne_posinf(rhs2) + if ispair(rhs1, rhs2): + return lhs2 < lhs1 + elif rop2 == "le": + if lhs2 is rhs2: + return true + if ispair(lhs1, lhs2): + return rhs1 <= rhs2 + if ispair(lhs1, rhs2): + return ((lhs2 <= rhs2) & (lhs2 < rhs1)) | ((lhs2 == rhs2) & (lhs2 == rhs1)) | is_eq_neginf(lhs2) + if ispair(rhs1, lhs2): + return ((lhs2 <= rhs2) & (lhs1 < rhs2)) | ((lhs2 == rhs2) & (lhs1 == rhs2)) | is_eq_posinf(rhs2) + if ispair(rhs1, rhs2): + return lhs2 <= lhs1 + elif rop2 == "eq": + if lhs2 is rhs2: + return true + if ispair(lhs1, lhs2): + return ((rhs1 == rhs2) & is_eq_neginf(rhs1)) | ((lhs2 == rhs2) & (rhs2 <= rhs1)) + if ispair(lhs1, rhs2): + return (rhs1 == lhs2) & is_eq_neginf(rhs1) + if ispair(rhs1, lhs2): + return ((lhs1 == rhs2) & is_eq_posinf(lhs1)) | ((lhs2 == rhs2) & (rhs2 >= lhs1)) + if ispair(rhs1, rhs2): + return ((lhs1 == lhs2) & is_eq_posinf(lhs1)) | ((lhs2 == rhs2) & (lhs2 >= lhs1)) + elif rop2 == "ne": + if lhs2 is rhs2: + return false + if ispair(lhs1, lhs2): + return (rhs2 > rhs1) & boolean(not ispair(rhs2, lhs1)) + if ispair(lhs1, rhs2): + return (lhs2 > rhs1) & boolean(not ispair(lhs2, lhs1)) + if ispair(rhs1, lhs2): + return (rhs2 < lhs1) & boolean(not ispair(rhs2, rhs1)) + if ispair(rhs1, rhs2): + return (lhs2 < lhs1) & boolean(not ispair(lhs2, rhs1)) + else: + assert 0 # unreachable + elif rop1 == "eq": + # x == a is a subset of x < b if a < b + # a == x is a subset of x < b if a < b + # x == a is a subset of b < x if a > b + # a == x is a subset of b < x if a > b + + # x == a is a subset of x <= b if a <= b + # a == x is a subset of x <= b if a <= b + # x == a is a subset of b <= x if a >= b + # a == x is a subset of b <= x if a >= b + + # x == a is a subset of x == b if (a == b) or (x is b) + # a == x is a subset of x == b if (a == b) or (x is b) + # x == a is a subset of b == x if (a == b) or (x is b) + # a == x is a subset of b == x if (a == b) or (x is b) + + # x == a is a subset of x != b if (a != b) and (b is not x) + # a == x is a subset of x != b if (a != b) and (b is not x) + # x == a is a subset of b != x if (a != b) and (b is not x) + # a == x is a subset of b != x if (a != b) and (b is not x) + if rop2 == "lt": + if lhs2 is rhs2: + return false + if ispair(lhs1, lhs2): + return rhs1 < rhs2 + if ispair(rhs1, lhs2): + return lhs1 < rhs2 + if ispair(lhs1, rhs2): + return rhs1 > lhs2 + if ispair(rhs1, rhs2): + return lhs1 > lhs2 + elif rop2 == "le": + if lhs2 is rhs2: + return true + if ispair(lhs1, lhs2): + return rhs1 <= rhs2 + if ispair(rhs1, lhs2): + return lhs1 <= rhs2 + if ispair(lhs1, rhs2): + return rhs1 >= lhs2 + if ispair(rhs1, rhs2): + return lhs1 >= lhs2 + elif rop2 == "eq": + if lhs2 is rhs2: + return true + if ispair(lhs1, lhs2): + return rhs1 == rhs2 + if ispair(rhs1, lhs2): + return lhs1 == rhs2 + if ispair(lhs1, rhs2): + return rhs1 == lhs2 + if ispair(rhs1, rhs2): + return lhs1 == lhs2 + elif rop2 == "ne": + if lhs2 is rhs2: + return false + if ispair(lhs1, lhs2): + return rhs1 != rhs2 + if ispair(rhs1, lhs2): + return lhs1 != rhs2 + if ispair(lhs1, rhs2): + return rhs1 != lhs2 + if ispair(rhs1, rhs2): + return lhs1 != lhs2 + else: + assert 0 # unreachable + elif rop1 == "ne": + # x != a is a subset of x < b if (x < b and (a >= b or x != a) or (b == inf and a == inf)) and (b != -inf) + # a != x is a subset of x < b if (x < b and (a >= b or x != a) or (b == inf and a == inf)) and (b != -inf) + # x != a is a subset of b < x if (b < x and (a <= b or x != a) or (b == -inf and a == -inf)) and b != inf + # a != x is a subset of b < x if (b < x and (a <= b or x != a) or (b == -inf and a == -inf)) and b != inf + + # x != a is a subset of x <= b if (((x < b and a == b) or (x <= b and a != b)) and (b != -inf)) or (b == inf) + # a != x is a subset of x <= b if (((x < b and a == b) or (x <= b and a != b)) and (b != -inf)) or (b == inf) + # x != a is a subset of b <= x if (((b < x and a == b) or (b <= x and a != b)) and (b != inf)) or (b == -inf) + # a != x is a subset of b <= x if (((b < x and a == b) or (b <= x and a != b)) and (b != inf)) or (b == -inf) + + # x != a is a subset of x == b if (b is x) or (x == b and a != b) + # a != x is a subset of x == b if (b is x) or (x == b and a != b) + # x != a is a subset of b == x if (b is x) or (x == b and a != b) + # a != x is a subset of b == x if (b is x) or (x == b and a != b) + + # x != a is a subset of x != b if a == b or (x != b and a != b) + # a != x is a subset of x != b if a == b or (x != b and a != b) + # x != a is a subset of b != x if a == b or (x != b and a != b) + # a != x is a subset of b != x if a == b or (x != b and a != b) + if rop2 == "lt": + if lhs2 is rhs2: + return false + if ispair(lhs1, lhs2): + return ((lhs2 < rhs2) | ((rhs1 == rhs2) & is_eq_posinf(rhs1))) & is_ne_neginf(rhs2) + if ispair(rhs1, lhs2): + return ((lhs2 < rhs2) | ((lhs1 == rhs2) & is_eq_posinf(lhs1))) & is_ne_neginf(rhs2) + if ispair(lhs1, rhs2): + return ((lhs2 < rhs2) | ((rhs1 == lhs2) & is_eq_neginf(rhs1))) & is_ne_posinf(lhs2) + if ispair(rhs1, rhs2): + return ((lhs2 < rhs2) | ((rhs1 == lhs2) & is_eq_neginf(lhs1))) & is_ne_posinf(lhs2) + elif rop2 == "le": + if lhs2 is rhs2: + return true + if ispair(lhs1, lhs2): + return ( + (((lhs2 < rhs2) & (rhs1 == rhs2)) | ((lhs2 <= rhs2) & (rhs1 != rhs2))) & is_ne_neginf(rhs2) + ) | is_eq_posinf(rhs2) + if ispair(rhs1, lhs2): + return ( + (((lhs2 < rhs2) & (lhs1 == rhs2)) | ((lhs2 <= rhs2) & (lhs1 != rhs2))) & is_ne_neginf(rhs2) + ) | is_eq_posinf(rhs2) + if ispair(lhs1, rhs2): + return ( + (((lhs2 < rhs2) & (rhs1 == lhs2)) | ((lhs2 <= rhs2) & (rhs1 != lhs2))) & is_ne_posinf(lhs2) + ) | is_eq_neginf(lhs2) + if ispair(rhs1, rhs2): + return ( + (((lhs2 < rhs2) & (lhs1 == lhs2)) | ((lhs2 <= rhs2) & (lhs1 != lhs2))) & is_ne_posinf(lhs2) + ) | is_eq_neginf(lhs2) + elif rop2 == "eq": + if lhs2 is rhs2: + return true + if ispair(lhs1, lhs2): + return (lhs2 == rhs2) & (rhs1 != rhs2) + if ispair(rhs1, lhs2): + return (lhs2 == rhs2) & (lhs1 != rhs2) + if ispair(lhs1, rhs2): + return (lhs2 == rhs2) & (rhs1 != lhs2) + if ispair(rhs1, rhs2): + return (lhs2 == rhs2) & (lhs1 != lhs2) + elif rop2 == "ne": + if lhs2 is rhs2: + return false + if ispair(lhs1, lhs2): + return (rhs1 == rhs2) | ((lhs2 != rhs2) & (rhs1 != rhs2)) + if ispair(rhs1, lhs2): + return (lhs1 == rhs2) | ((lhs2 != rhs2) & (lhs1 != rhs2)) + if ispair(lhs1, rhs2): + return (rhs1 == lhs2) | ((lhs2 != rhs2) & (rhs1 != lhs2)) + if ispair(rhs1, rhs2): + return (lhs1 == lhs2) | ((lhs2 != rhs2) & (lhs1 != lhs2)) + else: + assert 0 # unreachable + return rel_expr + + +class LogicalAndAssumption: + """Holds a list of assumptions associated with logical and-operation + + A logical and assumption is a logical and-expression of logical + expressions. + """ + + def __init__(self): + self.operands = [] + + +def logical_binary_operation(logical_expr, kind, left=None, right=None): + ctx = logical_expr.context + op = getattr(ctx, kind) + + def f(expr): + return expr.rewrite(rewrite) + + if logical_expr.kind in {"logical_and", "logical_or", "logical_xor", "logical_not"}: + logical_op = getattr(ctx, logical_expr.kind) + return logical_op( + *[logical_binary_operation(operand, kind, left=left, right=right) for operand in logical_expr.operands] + ) + elif (logical_expr.kind in {"eq", "ne"} and kind in {"multiply", "divide"}) or ( + logical_expr.kind in {"eq", "ne", "lt", "le", "gt", "ge"} and kind in {"add", "subtract"} + ): + logical_op = getattr(ctx, logical_expr.kind) + if left is not None: + if right is not None: + return logical_op(*[f(op(op(left, operand), right)) for operand in logical_expr.operands]) + else: + return logical_op(*[f(op(left, operand)) for operand in logical_expr.operands]) + elif right is not None: + return logical_op(*[f(op(operand, right)) for operand in logical_expr.operands]) + else: + return logical_expr + elif logical_expr.kind in {"lt", "le", "gt", "ge"} and kind in {"multiply", "divide"}: + logical_op1 = getattr(ctx, logical_expr.kind) + logical_op2 = getattr(ctx, dict(lt="gt", le="ge", gt="lt", ge="le")[logical_expr.kind]) + if left is not None: + if right is not None: + r1 = logical_op1(*[f(op(op(left, operand), right)) for operand in logical_expr.operands]) & f(left * right > 0) + r2 = logical_op2(*[f(op(op(left, operand), right)) for operand in logical_expr.operands]) & f(left * right < 0) + else: + r1 = logical_op1(*[f(op(left, operand)) for operand in logical_expr.operands]) & f(left > 0) + r2 = logical_op2(*[f(op(left, operand)) for operand in logical_expr.operands]) & f(left < 0) + elif right is not None: + r1 = logical_op1(*[f(op(operand, right)) for operand in logical_expr.operands]) & f(right > 0) + r2 = logical_op2(*[f(op(operand, right)) for operand in logical_expr.operands]) & f(right < 0) + else: + return logical_expr + false = logical_expr.context.constant(False) + true = logical_expr.context.constant(True) + r1 = rewrite.op_rewrite(r1, commutative=True, idempotent=True, identity=true, absorber=false, kind="logical_and") + r2 = rewrite.op_rewrite(r2, commutative=True, idempotent=True, identity=true, absorber=false, kind="logical_and") + r = r1 | r2 + return rewrite.op_rewrite(r, commutative=True, idempotent=True, identity=false, absorber=true, kind="logical_or") + else: + assert 0, (kind, logical_expr.kind) # unreachable + + +class AssumptionsGenerator: + + def __init__(self, data=None): + self.data = dict() if data is None else data + + def __rewrite_modifier__(self, expr): + if expr.kind in {"symbol"}: + pass + elif expr.kind == "constant": + value, like = expr.operands + if isinstance(value, str): + if value in {"smallest_subnormal", "smallest", "eps", "pi", "largest"}: + assume(expr > 0, _data=self.data) + elif expr.kind == "absolute": + (x,) = expr.operands + if x.get_type().is_real: + assume(expr >= 0, _data=self.data) + elif expr.kind in {"multiply", "divide", "add", "subtract"}: + x, y = expr.operands + if x.key in self.data: + assume(logical_binary_operation(self.data[x.key], expr.kind, right=y), _data=self.data) + if y.key in self.data: + assume(logical_binary_operation(self.data[y.key], expr.kind, left=x), _data=self.data) + elif expr.kind in {"logical_and", "logical_or", "logical_xor", "logical_not", "gt", "lt", "ge", "le", "eq", "ne"}: + pass + else: + assert 0, expr.kind # not implemeneted + return expr + + +def assume(expr, _data=None): + """Attach assumptions to symbols and expressions given by a logical + expression that truth-value is assumed to be true. + + Calling assume multiple time for the same symbol or expression + merges the assumptions using logical conjugate. + """ + if expr._is_boolean: + data = {} if _data is None else _data + for and_operand in rewrite.op_flatten( + rewrite.op_collect( + expr, commutative=True, idempotent=True, over_commutative=True, over_idempotent=True, over_kind="logical_or" + ), + commutative=True, + idempotent=True, + kind="logical_and", + ): + collector = rewrite.Collector() + and_operand.rewrite(collector) + for expr_ in collector.data.values(): + props = expr_.props + if "_assumptions" not in props: + props["_assumptions"] = {} + if and_operand.key not in props["_assumptions"]: + props["_assumptions"][and_operand.key] = and_operand + data[expr_.key] = and_operand + return list(data.values()) + else: + modifier = AssumptionsGenerator(_data) + expr.rewrite(modifier) + return list(modifier.data.values()) + + +def check(logical_expr): + """Check if logical_expr defines a non-empty subset. + + Definition: + + logical_expr(x) is a non-empty subset + + when there exists x such that logical_expr(x) is true, x is a set + of all non-boolean symbols present in the logical expression. + """ + true = logical_expr.context.constant(True) + false = logical_expr.context.constant(False) + + logical_expr.rewrite(AssumptionsGenerator()) + + collector = rewrite.Collector() + logical_expr.rewrite(collector) + assumptions = {} + for expr in collector.data.values(): + assumptions.update(expr.props.get("_assumptions", {})) + + if assumptions: + assumption = rewrite.op_unflatten(assumptions.values(), "logical_and") + r = is_subset_of(logical_expr, assumption) + if r is true: + return True + if r is false: + return False + return diff --git a/functional_algorithms/context.py b/functional_algorithms/context.py index 16ddc42..8ca07f5 100644 --- a/functional_algorithms/context.py +++ b/functional_algorithms/context.py @@ -12,7 +12,7 @@ class Context: - def __init__(self, paths=[], enable_alt=None, default_constant_type=None, parameters=None): + def __init__(self, paths=[], enable_alt=None, default_constant_type=None, compare_float_type=None, parameters=None): """Parameters ---------- paths : list @@ -26,9 +26,14 @@ def __init__(self, paths=[], enable_alt=None, default_constant_type=None, parame default_constant_type : {str, Type} Default type for constant expressions. Use together with enable_alt=True. + compare_float_type: {str, Type} + Type of float constants used in comparing constant + expressions when the type of float constant is not + explicitly specified. parameters : dict Parameters dictionary that can be used to parameterize algorithms. + """ self._expressions = {} self._stack_name = "" @@ -38,6 +43,7 @@ def __init__(self, paths=[], enable_alt=None, default_constant_type=None, parame self._alt = None self._enable_alt = enable_alt self._default_constant_type = default_constant_type + self._compare_float_type = compare_float_type self._default_like = None self.parameters = parameters or {} if "using" not in self.parameters: diff --git a/functional_algorithms/expr.py b/functional_algorithms/expr.py index 59ff4b2..6b05f1f 100644 --- a/functional_algorithms/expr.py +++ b/functional_algorithms/expr.py @@ -5,7 +5,8 @@ from .utils import UNSPECIFIED, warn_once, value_types, float_types, integer_types, number_types from .typesystem import Type from .rewrite import RewriteContext, op_flatten -from .assume import check +import functional_algorithms as fa + known_expression_kinds = set( """ @@ -423,6 +424,9 @@ def rewrite(self, modifier, *modifiers, deep_first=None, _rewrite_context=None): result = self if deep_first else modifier(self) + if result is None: + raise RuntimeError(f"{modifier} returned None") + if result is not self: pass elif self.kind == "symbol": @@ -455,6 +459,9 @@ def rewrite(self, modifier, *modifiers, deep_first=None, _rewrite_context=None): if deep_first: result = modifier(result) + if result is None: + raise RuntimeError(f"{modifier} returned None") + return rewrite_context(self, result) def tostring(self, target, tab="", need_ref=None, debug=0): @@ -729,6 +736,26 @@ def _is(self, *props): break return result + @property + @_is_cache + def _is_posinf(self): + if self.kind == "constant": + value, like = self.operands + if isinstance(value, Expr): + return value._is_posinf + elif isinstance(value, str): + return value == "posinf" + + @property + @_is_cache + def _is_neginf(self): + if self.kind == "constant": + value, like = self.operands + if isinstance(value, Expr): + return value._is_neginf + elif isinstance(value, str): + return value == "neginf" + @property @_is_cache def _is_nonzero(self): @@ -814,6 +841,7 @@ def _is_finite(self): if self._is_nonnegative: return True elif self.kind in {"add", "subtract", "positive", "negative", "absolute", "multiply", "square"}: + for x in self.operands: r = x._is_finite if r is None: @@ -918,7 +946,8 @@ def _is_nonpositive(self): elif self.kind in {"square", "absolute"} and self.operands[0]._is_negative: return False - return check(self <= 0) + return + return fa.check(self <= 0) for k, lst in self.props.items(): if k == "_is_gt": @@ -975,6 +1004,18 @@ def _is_boolean(self): return self.operands[1]._is_boolean return False + @property + def _is_constant(self): + if self.kind == "symbol": + return False + elif self.kind == "constant": + return True + else: + for item in self.operands: + if not item._is_constant: + return False + return True + @property def is_complex(self): if self.kind in {"symbol", "constant", "select"}: diff --git a/functional_algorithms/rewrite.py b/functional_algorithms/rewrite.py index e31e866..f6e809c 100644 --- a/functional_algorithms/rewrite.py +++ b/functional_algorithms/rewrite.py @@ -2,7 +2,8 @@ import numpy from collections import defaultdict from . import expr as _expr -from .utils import number_types, value_types, float_types, complex_types, boolean_types +from .utils import number_types, value_types, float_types, complex_types, boolean_types, str2float, warn_once +import functional_algorithms as fa class Printer: @@ -191,9 +192,11 @@ def tostring(self, expr): } -def op_rewrite(expr, commutative=False, idempotent=False, kind=None): +def op_rewrite(expr, commutative=False, idempotent=False, identity=None, absorber=None, kind=None): """Normalizes expression.""" - return op_unflatten(op_flatten(expr, commutative=commutative, idempotent=idempotent, kind=kind), kind) + return op_unflatten( + op_flatten(expr, commutative=commutative, idempotent=idempotent, kind=kind), kind, identity=identity, absorber=absorber + ) def op_collect(expr, commutative=False, idempotent=False, over_commutative=False, over_idempotent=False, over_kind=None): @@ -237,18 +240,25 @@ def op_collect(expr, commutative=False, idempotent=False, over_commutative=False row = new_row matrix.append(row) - left = [] - while len(set([row[0] if row else None for row in matrix])) == 1: - left.append(dct[matrix[0][0]]) - matrix = [row[1:] for row in matrix if len(row) > 1] - right = [] - while len(set([row[-1] if row else None for row in matrix])) == 1: - right.insert(0, dct[matrix[0][-1]]) - matrix = [row[:-1] for row in matrix if len(row) > 1] + if commutative: + left_ = set.intersection(*map(set, matrix)) + matrix = [sorted(row.difference(left_)) for row in map(set, matrix)] + left = [dct[key] for key in sorted(left_)] + else: + left = [] + while len(set([row[0] if row else None for row in matrix])) == 1: + left.append(dct[matrix[0][0]]) + matrix = [row[1:] for row in matrix if len(row) > 1] + + while len(set([row[-1] if row else None for row in matrix])) == 1: + right.insert(0, dct[matrix[0][-1]]) + matrix = [row[:-1] for row in matrix if len(row) > 1] + + matrix = [row for row in matrix if row] if matrix: - middle = op_unflatten([op_unflatten([dct[key] for key in row], kind) for row in matrix], over_kind) + middle = op_unflatten([op_unflatten([dct[key] for key in row], kind) for row in matrix if row], over_kind) return op_unflatten(left + [middle] + right, kind) return op_unflatten(left + right, kind) @@ -362,7 +372,7 @@ def op_flatten(expr, commutative=False, idempotent=False, kind=None, _kind=None) yield expr -def op_unflatten(operands, kind): +def op_unflatten(operands, kind, identity=None, absorber=None): """Return nested operation on operands. Inverse of op_flatten. For example: @@ -371,12 +381,18 @@ def op_unflatten(operands, kind): lhs = None op = None for operand in operands: + if operand is absorber: + return absorber + if operand is identity: + continue if lhs is None: lhs = operand op = getattr(lhs.context, kind) else: lhs = op(lhs, operand) - assert lhs is not None + if lhs is None: + lhs = identity + assert lhs is not None # specifying identity is recommended return lhs @@ -499,7 +515,6 @@ def exp(self, expr): def _binary_op(self, expr, op): x, y = expr.operands - if x.kind == "constant" and y.kind == "constant": xvalue, xlike = x.operands yvalue, ylike = y.operands @@ -532,6 +547,10 @@ def subtract(self, expr): if isinstance(value, number_types) and value == 0: return -y_ if s == -1 else y_ + if x is y: + # TODO: add isfinite check + return x.context.constant(0, x) # assuming finite x!!! + def multiply(self, expr): result = self._binary_op(expr, lambda x, y: x * y) @@ -542,8 +561,12 @@ def multiply(self, expr): for x_, y_ in [(x, y), (y, x)]: if x_.kind == "constant": value, like = x_.operands - if isinstance(value, number_types) and value == 1: - return y_ + if isinstance(value, number_types): + if value == 1: + return y_ + if value == 0: + # TODO: add isfinite check + return x_ # assuming that y_ is finite!!!! def minimum(self, expr): return self._binary_op(expr, lambda x, y: min(x, y)) @@ -552,18 +575,28 @@ def maximum(self, expr): return self._binary_op(expr, lambda x, y: max(x, y)) def divide(self, expr): + result = self._binary_op(expr, lambda x, y: x / y) + + if result is not None: + return result + x, y = expr.operands if y.kind == "constant": value, like = y.operands if isinstance(value, number_types) and value == 1: return x + if x is y: + # TODO: add isfinite check + return x.context.constant(1, x) # assuming finite x!!! + def complex(self, expr): pass def constant(self, expr): value, like = expr.operands typ = like.get_type() + if typ.kind in {"float", "complex"} and typ.bits is not None: dtype = typ.asdtype() if dtype is not None: @@ -573,21 +606,22 @@ def constant(self, expr): elif isinstance(value, str): if value == "posinf": return expr.context.constant(dtype(numpy.inf), like) - if value == "neginf": + elif value == "neginf": return expr.context.constant(-dtype(numpy.inf), like) - if value == "pi": + elif value == "pi": return expr.context.constant(dtype(numpy.pi), like) - if value in {"undefined", "nan"}: + elif value in {"undefined", "nan"}: return expr.context.constant(dtype(numpy.nan), like) fi = numpy.finfo(dtype) if value == "eps": return expr.context.constant(dtype(fi.eps), like) - if value == "largest": + elif value == "largest": return expr.context.constant(dtype(fi.max), like) - if value == "smallest": + elif value == "smallest": return expr.context.constant(dtype(fi.smallest_normal), like) - if value == "smallest_subnormal": + elif value == "smallest_subnormal": return expr.context.constant(dtype(fi.smallest_subnormal), like) + warn_once(f"unknown constant name: {value}") elif typ.kind == "float" and typ.bits is None: if not isinstance(value, float) and isinstance(value, number_types): return expr.context.constant(float(value), like) @@ -631,7 +665,9 @@ def logical_and(self, expr): if isinstance(value, bool): return y_ if value else ctx.constant(False) - operands = tuple(op_flatten(expr, commutative=True, idempotent=True)) + r = op_rewrite(expr, commutative=True, idempotent=True, kind="logical_and") + if r is not expr: + return r def logical_or(self, expr): x, y = expr.operands @@ -641,9 +677,13 @@ def logical_or(self, expr): value, like = x_.operands if isinstance(value, bool): if value: - return ctx.constant(True, ctx.symbol(None, "boolean")) + return ctx.constant(True) return y_ + r = op_rewrite(expr, commutative=True, idempotent=True, kind="logical_or") + if r is not expr: + return r + def logical_not(self, expr): (x,) = expr.operands if x.kind == "constant": @@ -701,23 +741,42 @@ def imag(self, expr): def _compare(self, expr, relop, relop_index, swap_relop_index): x, y = expr.operands + ctx = expr.context + + if x._is_constant and ctx._compare_float_type is not None: + x = x.rewrite(CompleteFloatType(ctx._compare_float_type), fa.rewrite) + assert x.kind == "constant", x + + if y._is_constant and ctx._compare_float_type is not None: + y = y.rewrite(CompleteFloatType(ctx._compare_float_type), fa.rewrite) + assert y.kind == "constant", y + if x.kind == "constant": xvalue, xlike = x.operands + + if isinstance(xvalue, str): + xvalue = str2float(xvalue, xlike.get_type()) + if y.kind == "constant": yvalue, ylike = y.operands + if isinstance(yvalue, str): + yvalue = str2float(yvalue, ylike.get_type()) + if isinstance(xvalue, _expr.Expr) or isinstance(yvalue, _expr.Expr): r = self._compare(relop(xvalue, yvalue), relop, relop_index, swap_relop_index) if isinstance(r, bool): - return expr.context.constant(r) + return ctx.constant(r) else: r = _constant_relop_constant.get((xvalue, yvalue)) if r is not None: - return expr.context.constant(r[relop_index]) + return ctx.constant(r[relop_index]) if isinstance(xvalue, value_types) and isinstance(yvalue, value_types): - r = bool(relop(xvalue, yvalue)) - return expr.context.constant(r) + r = relop(xvalue, yvalue) + + if r is not None: + return ctx.constant(bool(r)) elif isinstance(xvalue, number_types): for prop in ["positive", "negative", "nonpositive", "nonnegative", "finite"]: @@ -726,7 +785,7 @@ def _compare(self, expr, relop, relop_index, swap_relop_index): if r is not None: r = r[relop_index] if r is not None: - return expr.context.constant(r) + return ctx.constant(r) elif y.kind == "constant": yvalue, ylike = y.operands @@ -737,7 +796,7 @@ def _compare(self, expr, relop, relop_index, swap_relop_index): if r is not None: r = r[swap_relop_index] if r is not None: - return expr.context.constant(r) + return ctx.constant(r) else: for xprop, yprop in [ ("positive", "negative"), @@ -758,7 +817,16 @@ def _compare(self, expr, relop, relop_index, swap_relop_index): if r is not None: r = r[relop_index] if r is not None: - return expr.context.constant(r) + return ctx.constant(r) + + if expr.kind in {"eq", "ne"} and x._is_constant and y._is_constant is False: + return relop(*expr.operands[::-1]) + + if expr.kind in {"lt", "gt", "ne"} and x is y: + return ctx.constant(False) + + if expr.kind in {"le", "ge", "eq"} and x is y: + return ctx.constant(True) def ge(self, expr): return self._compare(expr, lambda x, y: x >= y, 0, 2) @@ -834,6 +902,12 @@ def rewrite(expr): while True: result = rewriter(result) if result is not None: + if last_result is not None: + if result is last_result: + # as a fix, revise rewriter that ought to return + # None when no rewrite is done: + warn_once(f"breaking unexpected infinite recursion for `{expr.tostring(fa.targets.symbolic)}`") + break last_result = result else: break @@ -873,7 +947,27 @@ def __call__(self, original, new=None): return self.cache[original.key] +class CompleteFloatType: + """Substitute incomplete float type with a complete float type. + + Incomplete type does not have bits specified. + """ + + def __init__(self, float_type): + self.float_type = float_type + + def __rewrite_modifier__(self, expr): + if expr.kind == "symbol": + name, typ = expr.operands + if typ.is_float and typ.bits is None: + typ = type(typ).fromobject(typ.context, self.float_type) + assert typ.bits is not None, typ + return expr.context.symbol(name, typ) + return expr + + class Substitute: + """Substitute sub-expressions.""" def __init__(self, matches, replacements): self.matches = matches @@ -912,3 +1006,26 @@ def __rewrite_modifier__(self, expr): else: raise NotImplementedError(f"{type(replacement)=}") return expr + + +class Collector: + """Rewrite modifier that collects expressions.""" + + def __init__(self, ignore_constants=True, ignore_logical=True, ignore_relational=True): + self.ignore_constants = ignore_constants + self.ignore_logical = ignore_logical + self.ignore_relational = ignore_relational + self.data = dict() + + def __rewrite_modifier__(self, expr): + + if self.ignore_constants and expr.kind == "constant": + pass + elif self.ignore_logical and expr.kind in {"logical_and", "logical_or", "logical_not"}: + pass + elif self.ignore_relational and expr.kind in {"lt", "gt", "le", "ge", "eq", "ne"}: + pass + else: + self.data[expr.key] = expr + + return expr diff --git a/functional_algorithms/tests/test_assume.py b/functional_algorithms/tests/test_assume.py index 823bc2a..f9ffaf4 100644 --- a/functional_algorithms/tests/test_assume.py +++ b/functional_algorithms/tests/test_assume.py @@ -1,13 +1,488 @@ +import numpy import functional_algorithms as fa assert_equal = fa.expr.assert_equal -def test_assume(): +def rewrite(x): + return x.rewrite(fa.rewrite) + + +def swap(expr): + if expr.kind == "le": + x, y = expr.operands + return expr.context.ge(y, x) + elif expr.kind == "ge": + x, y = expr.operands + return expr.context.le(y, x) + elif expr.kind == "lt": + x, y = expr.operands + return expr.context.gt(y, x) + elif expr.kind == "gt": + x, y = expr.operands + return expr.context.lt(y, x) + elif expr.kind == "eq": + x, y = expr.operands + return expr.context.eq(y, x) + elif expr.kind == "ne": + x, y = expr.operands + return expr.context.ne(y, x) + return expr + + +def test_is_subset_of_numbers(): + is_subset_of = fa.assumptions.is_subset_of + + ctx = fa.Context(default_constant_type="float", compare_float_type=numpy.float64) + true = ctx.constant(True) + false = ctx.constant(False) + x = ctx.symbol("x").reference("x") + y = ctx.symbol("y").reference("y") + zero = x.context.constant(0.0, x).reference("zero") + + a = ctx.symbol("a").reference("a") + b = ctx.symbol("b").reference("b") + + assert_equal(is_subset_of(x > 0, x > 0), true) + assert_equal(is_subset_of(x > 0, x < 0), false) + assert_equal(is_subset_of(x > 0, x > 1), false) + assert_equal(is_subset_of(x > 0, x < 1), x < 1.0) + assert_equal(is_subset_of(x > 0, x > -1), true) + assert_equal(is_subset_of(x > 0, x < -1), false) + + assert_equal(is_subset_of(x > 0, x >= 0), true) + assert_equal(is_subset_of(x > 0, x <= 0), false) + assert_equal(is_subset_of(x > 0, x >= 1), false) + assert_equal(is_subset_of(x > 0, x <= 1), x <= 1.0) + assert_equal(is_subset_of(x > 0, x >= -1), true) + assert_equal(is_subset_of(x > 0, x <= -1), false) + + assert_equal(is_subset_of(x > 0, x == 0), false) + assert_equal(is_subset_of(x > 0, x == 1), x == 1.0) + assert_equal(is_subset_of(x > 0, x == -1), false) + + assert_equal(is_subset_of(x > 0, x != 0), true) + assert_equal(is_subset_of(x > 0, x != 1), false) + assert_equal(is_subset_of(x > 0, x != -1), true) + + assert_equal(is_subset_of(x > 0, x == x), true) + assert_equal(is_subset_of(x > 0, x != x), false) + + assert_equal(is_subset_of(x >= 0, x > 0), false) + assert_equal(is_subset_of(x >= 0, x < 0), false) + assert_equal(is_subset_of(x >= 0, x > 1), false) + assert_equal(is_subset_of(x >= 0, x < 1), x < 1.0) + assert_equal(is_subset_of(x >= 0, x > -1), true) + assert_equal(is_subset_of(x >= 0, x < -1), false) + + assert_equal(is_subset_of(x >= 0, x >= 0), true) + assert_equal(is_subset_of(x >= 0, x <= 0), x == 0.0) + assert_equal(is_subset_of(x >= 0, x >= 1), false) + assert_equal(is_subset_of(x >= 0, x <= 1), x <= 1.0) + assert_equal(is_subset_of(x >= 0, x >= -1), true) + assert_equal(is_subset_of(x >= 0, x <= -1), false) + + assert_equal(is_subset_of(x >= 0, x == 0), x == 0.0) + assert_equal(is_subset_of(x >= 0, x == 1), x == 1.0) + assert_equal(is_subset_of(x >= 0, x == -1), false) + + assert_equal(is_subset_of(x >= 0, x != 0), false) + assert_equal(is_subset_of(x >= 0, x != 1), false) + assert_equal(is_subset_of(x >= 0, x != -1), true) + + assert_equal(is_subset_of(x >= 0, x == x), true) + assert_equal(is_subset_of(x >= 0, x != x), false) + + assert_equal(is_subset_of(x < 0, x > 0), false) + assert_equal(is_subset_of(x < 0, x < 0), true) + assert_equal(is_subset_of(x < 0, x > 1), false) + assert_equal(is_subset_of(x < 0, x < 1), true) + assert_equal(is_subset_of(x < 0, x > -1), swap(x > -1.0)) + assert_equal(is_subset_of(x < 0, x < -1), false) + + assert_equal(is_subset_of(x < 0, x >= 0), false) + assert_equal(is_subset_of(x < 0, x <= 0), true) + assert_equal(is_subset_of(x < 0, x >= 1), false) + assert_equal(is_subset_of(x < 0, x <= 1), true) + assert_equal(is_subset_of(x < 0, x >= -1), swap(x >= -1.0)) + assert_equal(is_subset_of(x < 0, x <= -1), false) + + assert_equal(is_subset_of(x < 0, x == 0), false) + assert_equal(is_subset_of(x < 0, x == 1), false) + assert_equal(is_subset_of(x < 0, x == -1), x == -1.0) + + assert_equal(is_subset_of(x < 0, x != 0), true) + assert_equal(is_subset_of(x < 0, x != 1), true) + assert_equal(is_subset_of(x < 0, x != -1), false) + + assert_equal(is_subset_of(x < 0, x == x), true) + assert_equal(is_subset_of(x < 0, x != x), false) + + assert_equal(is_subset_of(x <= 0, x > 0), false) + assert_equal(is_subset_of(x <= 0, x < 0), false) + assert_equal(is_subset_of(x <= 0, x > 1), false) + assert_equal(is_subset_of(x <= 0, x < 1), true) + assert_equal(is_subset_of(x <= 0, x > -1), swap(x > -1.0)) + assert_equal(is_subset_of(x <= 0, x < -1), false) + + assert_equal(is_subset_of(x <= 0, x >= 0), x == 0.0) + assert_equal(is_subset_of(x <= 0, x <= 0), true) + assert_equal(is_subset_of(x <= 0, x >= 1), false) + assert_equal(is_subset_of(x <= 0, x <= 1), true) + assert_equal(is_subset_of(x <= 0, x >= -1), swap(x >= -1.0)) + assert_equal(is_subset_of(x <= 0, x <= -1), false) + + assert_equal(is_subset_of(x <= 0, x == 0), x == 0.0) + assert_equal(is_subset_of(x <= 0, x == 1), false) + assert_equal(is_subset_of(x <= 0, x == -1), x == -1.0) + + assert_equal(is_subset_of(x <= 0, x != 0), false) + assert_equal(is_subset_of(x <= 0, x != 1), true) + assert_equal(is_subset_of(x <= 0, x != -1), false) + + assert_equal(is_subset_of(x <= 0, x == x), true) + assert_equal(is_subset_of(x <= 0, x != x), false) + + assert_equal(is_subset_of(x == 0, x > 0), false) + assert_equal(is_subset_of(x == 0, x < 0), false) + assert_equal(is_subset_of(x == 0, x > 1), false) + assert_equal(is_subset_of(x == 0, x < 1), true) + assert_equal(is_subset_of(x == 0, x > -1), true) + assert_equal(is_subset_of(x == 0, x < -1), false) + + assert_equal(is_subset_of(x == 0, x >= 0), true) + assert_equal(is_subset_of(x == 0, x <= 0), true) + assert_equal(is_subset_of(x == 0, x >= 1), false) + assert_equal(is_subset_of(x == 0, x <= 1), true) + assert_equal(is_subset_of(x == 0, x >= -1), true) + assert_equal(is_subset_of(x == 0, x <= -1), false) + + assert_equal(is_subset_of(x == 0, x == 0), true) + assert_equal(is_subset_of(x == 0, x == 1), false) + assert_equal(is_subset_of(x == 0, x == -1), false) + + assert_equal(is_subset_of(x == 0, x != 0), false) + assert_equal(is_subset_of(x == 0, x != 1), true) + assert_equal(is_subset_of(x == 0, x != -1), true) + + assert_equal(is_subset_of(x == 0, x == x), true) + assert_equal(is_subset_of(x == 0, x != x), false) + + assert_equal(is_subset_of(x != 0, x > 0), swap(x > 0.0)) + assert_equal(is_subset_of(x != 0, x < 0), x < 0.0) + assert_equal(is_subset_of(x != 0, x > 1), swap(x > 1.0)) + assert_equal(is_subset_of(x != 0, x < 1), x < 1.0) + assert_equal(is_subset_of(x != 0, x > -1), swap(x > -1.0)) + assert_equal(is_subset_of(x != 0, x < -1), x < -1.0) + + assert_equal(is_subset_of(x != 0, x >= 0), swap(x > 0.0)) + assert_equal(is_subset_of(x != 0, x <= 0), x < 0.0) + assert_equal(is_subset_of(x != 0, x >= 1), swap(x >= 1.0)) + assert_equal(is_subset_of(x != 0, x <= 1), x <= 1.0) + assert_equal(is_subset_of(x != 0, x >= -1), swap(x >= -1.0)) + assert_equal(is_subset_of(x != 0, x <= -1), x <= -1.0) + + assert_equal(is_subset_of(x != 0, x == 0), false) + assert_equal(is_subset_of(x != 0, x == 1), x == 1.0) + assert_equal(is_subset_of(x != 0, x == -1), x == -1.0) + + assert_equal(is_subset_of(x != 0, x != 0), true) + assert_equal(is_subset_of(x != 0, x != 1), x != 1.0) + assert_equal(is_subset_of(x != 0, x != -1), x != -1.0) + + assert_equal(is_subset_of(x != 0, x == x), true) + assert_equal(is_subset_of(x != 0, x != x), false) + + assert_equal(is_subset_of(x > a, x > b), (b <= a) & (b != ctx.constant("posinf", b))) + assert_equal(is_subset_of(x > a, x > 0), swap(a >= ctx.constant(0.0, x))) + assert_equal(is_subset_of(x < a, x < b), (a <= b) & (b != ctx.constant("neginf", b))) + + assert_equal(is_subset_of(x <= 0, x < 0), false) + assert_equal(is_subset_of(x >= a, x > b), b < a) + + assert_equal(is_subset_of((a < x) & (a < b), x > 0), swap(a >= zero)) + + assert_equal(is_subset_of((1 < x) & (x < 3), x > 0), true) + assert_equal(is_subset_of((1 < x) & (x < 3), (1 < x) & (x < 5)), true) + assert_equal(is_subset_of((1 <= x) & (x < 3), (1 < x) & (x < 5)), false) + assert_equal(is_subset_of((1 < x) & (x < 3), (0 < x) & (x < 2)), false) + + +def test_is_subset_of_symbolic(): + is_subset_of = fa.assumptions.is_subset_of + + ctx = fa.Context(default_constant_type="float", compare_float_type=numpy.float64) + true = ctx.constant(True) + false = ctx.constant(False) + x = ctx.symbol("x").reference("x") + y = ctx.symbol("y").reference("y") + zero = x.context.constant(0.0, x).reference("zero") + eps = x.context.constant("eps", x).reference("eps") + pi = x.context.constant("pi", x).reference("pi") + smallest = x.context.constant("smallest", x).reference("smallest") + largest = x.context.constant("largest", x).reference("largest") + posinf = x.context.constant("posinf", x).reference("posinf") + neginf = x.context.constant("neginf", x).reference("neginf") + + assert_equal(is_subset_of(x == smallest, x > 0), true) + assert_equal(is_subset_of(x == smallest, x > smallest), false) + assert_equal(is_subset_of(x == smallest, x > eps), false) + assert_equal(is_subset_of(x == largest, x > eps), true) + assert_equal(is_subset_of(x == posinf, x > eps), true) + assert_equal(is_subset_of(x == neginf, x > eps), false) + assert_equal(is_subset_of(x > eps, x >= eps), true) + assert_equal(is_subset_of(x <= eps, x > -1), ctx.constant(-1.0, x) < x) + assert_equal(is_subset_of(x >= eps, x < 1), x < 1.0) + assert_equal(is_subset_of(x >= smallest, x < eps), x < eps) + + for c in [ + largest, + ctx.constant(10, x), + pi, + eps, + smallest, + ctx.constant(0, x), + -smallest, + -eps, + ctx.constant(-10, x), + -largest, + posinf, + neginf, + ]: + for d in [ + largest, + ctx.constant(20, x), + pi, + eps, + smallest, + ctx.constant(0, x), + -smallest, + -eps, + ctx.constant(-10, x), + -largest, + posinf, + neginf, + ]: + # + assert_equal(is_subset_of(x < c, x < d), rewrite(false if d._is_neginf else c <= d)) + assert_equal(is_subset_of(x > -c, x > -d), rewrite(false if d._is_neginf else c <= d)) + assert_equal(is_subset_of(x < c, d < x), false if d._is_neginf else rewrite((d < x) & (c > d))) + assert_equal(is_subset_of(x > -c, -d > x), false if d._is_neginf else rewrite((x < -d) & (c > d))) + assert_equal(is_subset_of(c < x, x < d), false if d._is_posinf else rewrite((x < d) & (c < d))) + assert_equal(is_subset_of(-c > x, x > -d), false if d._is_posinf else rewrite((-d < x) & (c < d))) + assert_equal(is_subset_of(c < x, x > d), false if d._is_posinf else rewrite(c >= d)) + assert_equal(is_subset_of(-c > x, x < -d), false if d._is_posinf else rewrite(c >= d)) + # + assert_equal(is_subset_of(x < c, x < posinf), true) + assert_equal(is_subset_of(x > -c, x > neginf), true) + assert_equal(is_subset_of(x < c, posinf < x), false) + assert_equal(is_subset_of(x > -c, neginf > x), false) + assert_equal(is_subset_of(c < x, x < posinf), false) + assert_equal(is_subset_of(-c > x, x > neginf), false) + assert_equal(is_subset_of(c < x, posinf < x), false) + assert_equal(is_subset_of(-c > x, neginf > x), false) + # + assert_equal(is_subset_of(x < c, x <= posinf), true) + assert_equal(is_subset_of(x > -c, x >= neginf), true) + assert_equal(is_subset_of(x < c, posinf <= x), false) + assert_equal(is_subset_of(x > -c, neginf >= x), false) + assert_equal(is_subset_of(c < x, x <= posinf), true) + assert_equal(is_subset_of(-c > x, x >= neginf), true) + assert_equal(is_subset_of(c < x, posinf <= x), true) + assert_equal(is_subset_of(-c > x, neginf >= x), true) + # + assert_equal(is_subset_of(x < c, x == posinf), false) + assert_equal(is_subset_of(x > -c, x == neginf), false) + assert_equal(is_subset_of(x < c, posinf == x), false) + assert_equal(is_subset_of(x > -c, neginf == x), false) + assert_equal(is_subset_of(c < x, x == posinf), false) + assert_equal(is_subset_of(-c > x, x == neginf), false) + assert_equal(is_subset_of(c < x, posinf == x), false) + assert_equal(is_subset_of(-c > x, neginf == x), false) + # + assert_equal(is_subset_of(x < c, x != posinf), true) + assert_equal(is_subset_of(x > -c, x != neginf), true) + assert_equal(is_subset_of(x < c, posinf != x), true) + assert_equal(is_subset_of(x > -c, neginf != x), true) + assert_equal(is_subset_of(c < x, x != posinf), false if c is largest else true) + assert_equal(is_subset_of(-c > x, x != neginf), false if c is largest else true) + assert_equal(is_subset_of(c < x, posinf != x), false if c is largest else true) + assert_equal(is_subset_of(-c > x, neginf != x), false if c is largest else true) + # + assert_equal(is_subset_of(x <= c, x < posinf), false if c._is_posinf else true) + assert_equal(is_subset_of(x >= -c, x > neginf), false if c._is_posinf else true) + assert_equal(is_subset_of(x <= c, posinf < x), false) + assert_equal(is_subset_of(x >= -c, neginf > x), false) + assert_equal(is_subset_of(c <= x, x < posinf), false) + assert_equal(is_subset_of(-c >= x, x > neginf), false) + assert_equal(is_subset_of(c <= x, posinf < x), false) + assert_equal(is_subset_of(-c >= x, neginf > x), false) + # + assert_equal(is_subset_of(x <= c, x <= posinf), true) + assert_equal(is_subset_of(x >= -c, x >= neginf), true) + assert_equal(is_subset_of(x <= c, posinf <= x), x == posinf if c._is_posinf else false) + assert_equal(is_subset_of(x >= -c, neginf >= x), x == neginf if c._is_posinf else false) + assert_equal(is_subset_of(c <= x, x <= posinf), true) + assert_equal(is_subset_of(-c >= x, x >= neginf), true) + assert_equal(is_subset_of(c <= x, posinf <= x), true if c._is_posinf else false) + assert_equal(is_subset_of(-c >= x, neginf >= x), true if c._is_posinf else false) + # + assert_equal(is_subset_of(x <= c, x == posinf), x == posinf if c._is_posinf else false) + assert_equal(is_subset_of(x >= -c, x == neginf), x == neginf if c._is_posinf else false) + assert_equal(is_subset_of(x <= c, posinf == x), x == posinf if c._is_posinf else false) + assert_equal(is_subset_of(x >= -c, neginf == x), x == neginf if c._is_posinf else false) + assert_equal(is_subset_of(c <= x, x == posinf), true if c._is_posinf else x == posinf) + assert_equal(is_subset_of(-c >= x, x == neginf), true if c._is_posinf else x == neginf) + assert_equal(is_subset_of(c <= x, posinf == x), true if c._is_posinf else x == posinf) + assert_equal(is_subset_of(-c >= x, neginf == x), true if c._is_posinf else x == neginf) + # + assert_equal(is_subset_of(x <= c, x != posinf), false if c._is_posinf else true) + assert_equal(is_subset_of(x >= -c, x != neginf), false if c._is_posinf else true) + assert_equal(is_subset_of(x <= c, posinf != x), false if c._is_posinf else true) + assert_equal(is_subset_of(x >= -c, neginf != x), false if c._is_posinf else true) + assert_equal(is_subset_of(c <= x, x != posinf), false) + assert_equal(is_subset_of(-c >= x, x != neginf), false) + assert_equal(is_subset_of(c <= x, posinf != x), false) + assert_equal(is_subset_of(-c >= x, neginf != x), false) + # + assert_equal(is_subset_of(x == c, x < posinf), false if c._is_posinf else true) + assert_equal(is_subset_of(x == -c, x > neginf), false if c._is_posinf else true) + assert_equal(is_subset_of(x == c, posinf < x), false) + assert_equal(is_subset_of(x == -c, neginf > x), false) + assert_equal(is_subset_of(c == x, x < posinf), false if c._is_posinf else true) + assert_equal(is_subset_of(-c == x, x > neginf), false if c._is_posinf else true) + assert_equal(is_subset_of(c == x, posinf < x), false) + assert_equal(is_subset_of(-c == x, neginf > x), false) + # + assert_equal(is_subset_of(x == c, x <= posinf), true) + assert_equal(is_subset_of(x == -c, x >= neginf), true) + assert_equal(is_subset_of(x == c, posinf <= x), true if c._is_posinf else false) + assert_equal(is_subset_of(x == -c, neginf >= x), true if c._is_posinf else false) + assert_equal(is_subset_of(c == x, x <= posinf), true) + assert_equal(is_subset_of(-c == x, x >= neginf), true) + assert_equal(is_subset_of(c == x, posinf <= x), true if c._is_posinf else false) + assert_equal(is_subset_of(-c == x, neginf >= x), true if c._is_posinf else false) + # + assert_equal(is_subset_of(x == c, x == posinf), true if c._is_posinf else false) + assert_equal(is_subset_of(x == -c, x == neginf), true if c._is_posinf else false) + assert_equal(is_subset_of(x == c, posinf == x), true if c._is_posinf else false) + assert_equal(is_subset_of(x == -c, neginf == x), true if c._is_posinf else false) + assert_equal(is_subset_of(c == x, x == posinf), true if c._is_posinf else false) + assert_equal(is_subset_of(-c == x, x == neginf), true if c._is_posinf else false) + assert_equal(is_subset_of(c == x, posinf == x), true if c._is_posinf else false) + assert_equal(is_subset_of(-c == x, neginf == x), true if c._is_posinf else false) + # + assert_equal(is_subset_of(x == c, x != posinf), false if c._is_posinf else true) + assert_equal(is_subset_of(x == -c, x != neginf), false if c._is_posinf else true) + assert_equal(is_subset_of(x == c, posinf != x), false if c._is_posinf else true) + assert_equal(is_subset_of(x == -c, neginf != x), false if c._is_posinf else true) + assert_equal(is_subset_of(c == x, x != posinf), false if c._is_posinf else true) + assert_equal(is_subset_of(-c == x, x != neginf), false if c._is_posinf else true) + assert_equal(is_subset_of(c == x, posinf != x), false if c._is_posinf else true) + assert_equal(is_subset_of(-c == x, neginf != x), false if c._is_posinf else true) + # + assert_equal(is_subset_of(x != c, x < posinf), true if c._is_posinf else x < posinf) + assert_equal(is_subset_of(x != -c, x > neginf), true if c._is_posinf else neginf < x) + assert_equal(is_subset_of(x != c, posinf < x), false) + assert_equal(is_subset_of(x != -c, neginf > x), false) + assert_equal(is_subset_of(c != x, x < posinf), true if c._is_posinf else x < posinf) + assert_equal(is_subset_of(-c != x, x > neginf), true if c._is_posinf else neginf < x) + assert_equal(is_subset_of(c != x, posinf < x), false) + assert_equal(is_subset_of(-c != x, neginf > x), false) + # + assert_equal(is_subset_of(x != c, x <= posinf), true) + assert_equal(is_subset_of(x != -c, x >= neginf), true) + assert_equal(is_subset_of(x != c, posinf <= x), false) + assert_equal(is_subset_of(x != -c, neginf >= x), false) + assert_equal(is_subset_of(c != x, x <= posinf), true) + assert_equal(is_subset_of(-c != x, x >= neginf), true) + assert_equal(is_subset_of(c != x, posinf <= x), false) + assert_equal(is_subset_of(-c != x, neginf >= x), false) + # + assert_equal(is_subset_of(x != c, x == posinf), false if c._is_posinf else x == posinf) + assert_equal(is_subset_of(x != -c, x == neginf), false if c._is_posinf else x == neginf) + assert_equal(is_subset_of(x != c, posinf == x), false if c._is_posinf else x == posinf) + assert_equal(is_subset_of(x != -c, neginf == x), false if c._is_posinf else x == neginf) + assert_equal(is_subset_of(c != x, x == posinf), false if c._is_posinf else x == posinf) + assert_equal(is_subset_of(-c != x, x == neginf), false if c._is_posinf else x == neginf) + assert_equal(is_subset_of(c != x, posinf == x), false if c._is_posinf else x == posinf) + assert_equal(is_subset_of(-c != x, neginf == x), false if c._is_posinf else x == neginf) + # + assert_equal(is_subset_of(x != c, x != posinf), true if c._is_posinf else x != posinf) + assert_equal(is_subset_of(x != -c, x != neginf), true if c._is_posinf else x != neginf) + assert_equal(is_subset_of(x != c, posinf != x), true if c._is_posinf else x != posinf) + assert_equal(is_subset_of(x != -c, neginf != x), true if c._is_posinf else x != neginf) + assert_equal(is_subset_of(c != x, x != posinf), true if c._is_posinf else x != posinf) + assert_equal(is_subset_of(-c != x, x != neginf), true if c._is_posinf else x != neginf) + assert_equal(is_subset_of(c != x, posinf != x), true if c._is_posinf else x != posinf) + assert_equal(is_subset_of(-c != x, neginf != x), true if c._is_posinf else x != neginf) + + +def test_register_assumptions(): ctx = fa.Context(default_constant_type="float") x = ctx.symbol("x") y = ctx.symbol("y") - z = ctx.symbol("z") - fa.assume((x > 0) & ((y < z) | (y > 0))) + fa.assume(((x > 0) | (x < 1)) & (x * x < 1) & (y > 2)) + + assert (x * x < 1).key in x.props["_assumptions"] + assert ((x > 0) | (x < 1)).key in x.props["_assumptions"] + assert (y > 2).key in y.props["_assumptions"] + assert (y > 2).key not in x.props["_assumptions"] + + fa.assume(x + y < 2) + + assert (x * x < 1).key in x.props["_assumptions"] + assert (x + y < 2).key in x.props["_assumptions"] + assert (x + y < 2).key in y.props["_assumptions"] + + +def test_use_assumptions(): + + ctx = fa.Context(default_constant_type="float") + x = ctx.symbol("x") + + assert fa.check(x > 0) is None + + fa.assume(x > 0) + + assert fa.check(x > -1) is False + assert fa.check(x > 0) is True + assert fa.check(x > 1) is True + assert fa.check(x >= 0) is False + assert fa.check(x < 0) is False + assert fa.check(x < 1) is None + + +def test_abs_check(): + + ctx = fa.Context(default_constant_type="float") + x = ctx.symbol("x") + + assert fa.check(abs(x) >= 0) is True + assert fa.check(abs(x) >= 1) is True + assert fa.check(abs(x) < 1) is True + assert fa.check(abs(x) < 0) is False + assert fa.check(abs(x) < -1) is False + assert fa.check(abs(x) == 0) is True + assert fa.check(abs(x) == -1) is False + assert fa.check(abs(x) == 1) is True + assert fa.check(abs(x) != 1) is True + assert fa.check(abs(x) == -1) is False + + +def test_assume_nonlogical(): + + ctx = fa.Context(default_constant_type="float") + x = ctx.symbol("x") + + # assert fa.assume(abs(x)) == [abs(x) >= 0] + fa.assume(abs(x) < ctx.constant("posinf", x)) + d = fa.assume(abs(x) * abs(x)) + for item in d: + print(111, item.tostring(fa.targets.symbolic)) + return + + assert fa.assume(x) == [] + assert fa.assume(abs(x)) == [abs(x) >= 0] diff --git a/functional_algorithms/tests/test_expr.py b/functional_algorithms/tests/test_expr.py index 77f2214..5064267 100644 --- a/functional_algorithms/tests/test_expr.py +++ b/functional_algorithms/tests/test_expr.py @@ -454,7 +454,7 @@ def rewrite(expr): r2 = fa.Expr( expr.context, dict(lt="gt", le="ge", gt="lt", ge="le", eq="eq", ne="ne")[r2_.kind], r2_.operands[::-1] ) - assert r1 is r2 + assert r1 is r2 or (r2_.kind in {"ne", "eq"}), (r1._serialized, r2._serialized) return r1 ctx = fa.Context() @@ -476,6 +476,14 @@ def rewrite(expr): assert rewrite(x != 1).kind == "ne" assert rewrite(x == 1).kind == "eq" + assert rewrite(x > -1).kind == "gt" + assert rewrite(x >= -1).kind == "ge" + assert rewrite(x <= -1).kind == "le" + assert rewrite(x < -1).kind == "lt" + assert rewrite(x == -1).kind == "eq" + assert rewrite(x != -1).kind == "ne" + assert rewrite(x == -1).kind == "eq" + for r in [ctx.square(x), x * x]: assert rewrite(r > 0).kind == "gt" assert rewrite(r >= 0) is true @@ -737,14 +745,14 @@ def test_logical_op_collect(): kwargs = dict(over_kind="logical_or") assert_equal(fa.rewrite.op_collect((x & z) | (y & z), **kwargs), (x | y) & z) assert_equal(fa.rewrite.op_collect((z & x & z) | (y & z), **kwargs), ((z & x) | y) & z) - assert_equal(fa.rewrite.op_collect((z & x & z) | (y & z), commutative=True, idempotent=True, **kwargs), (x | y) & z) + assert_equal(fa.rewrite.op_collect((z & x & z) | (y & z), commutative=True, idempotent=True, **kwargs), z & (x | y)) assert_equal(fa.rewrite.op_collect((x & z) | (y & z) | z, **kwargs), (x | y) & z) assert_equal(fa.rewrite.op_collect((z & x) | (y & z), **kwargs), (z & x) | (y & z)) - assert_equal(fa.rewrite.op_collect((z & x) | (y & z), commutative=True, **kwargs), (x | y) & z) + assert_equal(fa.rewrite.op_collect((z & x) | (y & z), commutative=True, **kwargs), z & (x | y)) assert_equal(fa.rewrite.op_collect((x & z) | (y & z) | (x & z), **kwargs), (x | y | x) & z) - assert_equal(fa.rewrite.op_collect((x & z) | (y & z) | (x & z), commutative=True, **kwargs), (x | y | x) & z) + assert_equal(fa.rewrite.op_collect((x & z) | (y & z) | (x & z), commutative=True, **kwargs), z & (x | y | x)) assert_equal(fa.rewrite.op_collect((x & z) | (y & z) | (x & z), over_commutative=True, **kwargs), (x | x | y) & z) assert_equal( fa.rewrite.op_collect((x & z) | (y & z) | (x & z), over_commutative=True, over_idempotent=True, **kwargs), (x | y) & z diff --git a/functional_algorithms/typesystem.py b/functional_algorithms/typesystem.py index a03f774..426c983 100644 --- a/functional_algorithms/typesystem.py +++ b/functional_algorithms/typesystem.py @@ -90,6 +90,12 @@ def complex_part(self): bits = self.bits // 2 if self.bits is not None else None return type(self)(self.context, "float", bits) + @property + def as_complex(self): + assert self.kind == "float", self + bits = self.bits * 2 if self.bits is not None else None + return type(self)(self.context, "complex", bits) + @property def is_float(self): return self.kind == "float" @@ -98,6 +104,10 @@ def is_float(self): def is_complex(self): return self.kind == "complex" + @property + def is_real(self): + return self.is_float or self.is_integer + @property def is_integer(self): return self.kind == "integer" @@ -119,5 +129,5 @@ def is_same(self, other): def is_same_kind(self, other): return self.kind == other.kind - def asdtype(self): - return getattr(numpy, str(self), None) + def asdtype(self, default=None): + return getattr(numpy, str(self), default) diff --git a/functional_algorithms/utils.py b/functional_algorithms/utils.py index 0624a97..da2ad16 100644 --- a/functional_algorithms/utils.py +++ b/functional_algorithms/utils.py @@ -101,6 +101,31 @@ def mpf2float(dtype, x, flush_subnormals=False): assert 0 # unreachable +def str2float(value, typ): + assert isinstance(value, str), type(value) + if typ.is_float: + dtype = typ.asdtype() + if dtype is None: + dtype = numpy.float64 + if dtype is not None: + fi = numpy.finfo(dtype) + if value in {"smallest", "smallest_normal"}: + return fi.smallest_normal + elif value == "smallest_subnormal": + return fi.smallest_subnormal + elif value == "eps": + return fi.eps + elif value == "largest": + return fi.max + elif value == "posinf": + return dtype(numpy.inf) + elif value == "neginf": + return dtype(-numpy.inf) + elif value == "pi": + return dtype(numpy.pi) + return value + + class vectorize_with_backend(numpy.vectorize): pyfunc_is_vectorized = False