Example #1
0
def prove(Eq):
    i = Symbol.i(integer=True)
    j = Symbol.j(integer=True)
    n = Symbol.n(domain=Interval(2, oo, integer=True))
    x = Symbol.x(shape=(oo, ), dtype=dtype.integer, finite=True)

    j_domain = Interval(0, n - 1, integer=True) - {i}
    given = ForAll[j:j_domain, i:n](Equality(x[i] & x[j], EmptySet()))
    Eq << apply(given)

    y = Symbol.y(shape=(oo, ),
                 dtype=dtype.integer,
                 definition=LAMBDA[i](Piecewise((x[i], i < n),
                                                (EmptySet(), True))))

    Eq.y_definition = y.equality_defined()

    Eq.yi_definition = Eq.y_definition.forall((i, 0, n - 1))

    Eq << Eq.yi_definition.reversed

    Eq << Eq[0].subs(Eq[-1]).subs(Eq[-1].limits_subs(i, j))

    Eq << Eq.y_definition.forall((i, n, oo))

    Eq << Eq[-1].intersect(y[j]).forall((j, j_domain))

    Eq << (Eq[-1] & Eq[-3])

    Eq << sets.forall_equality.imply.equality.nonoverlapping_utility.apply(
        Eq[-1])

    Eq << Eq[-1].subs(Eq.yi_definition)
Example #2
0
def test_stationary_points():
    x, y = symbols('x y')

    assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)
        ) == {-pi/2, pi/2}
    assert  stationary_points(sin(x), x, Interval.Ropen(0, pi/4)
        ) == EmptySet()
    assert stationary_points(tan(x), x,
        ) == EmptySet()
    assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)
        ) == {pi/4, pi*Rational(3, 4)}
    assert stationary_points(sec(x), x, Interval(0, pi)
        ) == {0, pi}
    assert stationary_points((x+3)*(x-2), x
        ) == FiniteSet(Rational(-1, 2))
    assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)
        ) == EmptySet()
    assert stationary_points((x**2+3)/(x-2), x
        ) == {2 - sqrt(7), 2 + sqrt(7)}
    assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)
        ) == {2 + sqrt(7)}
    assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals
        ) == FiniteSet(-2, 0, Rational(5, 4))
    assert stationary_points(exp(x), x
        ) == EmptySet()
    assert stationary_points(log(x) - x, x, S.Reals
        ) == {1}
    assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
        ) == {0, -pi, pi}
    assert stationary_points(y, x, S.Reals
        ) == S.Reals
    assert stationary_points(y, x, S.EmptySet) == S.EmptySet
Example #3
0
def test_ComplexPlane_intersect():

    # Polar form
    X_axis = ComplexPlane(Interval(0, oo) * FiniteSet(0, S.Pi), polar=True)

    unit_disk = ComplexPlane(Interval(0, 1) * Interval(0, 2 * S.Pi),
                             polar=True)
    upper_half_unit_disk = ComplexPlane(Interval(0, 1) * Interval(0, S.Pi),
                                        polar=True)
    upper_half_disk = ComplexPlane(Interval(0, oo) * Interval(0, S.Pi),
                                   polar=True)
    lower_half_disk = ComplexPlane(Interval(0, oo) * Interval(S.Pi, 2 * S.Pi),
                                   polar=True)
    right_half_disk = ComplexPlane(Interval(0, oo) *
                                   Interval(-S.Pi / 2, S.Pi / 2),
                                   polar=True)
    first_quad_disk = ComplexPlane(Interval(0, oo) * Interval(0, S.Pi / 2),
                                   polar=True)

    assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk
    assert right_half_disk.intersect(first_quad_disk) == first_quad_disk
    assert upper_half_disk.intersect(right_half_disk) == first_quad_disk
    assert upper_half_disk.intersect(lower_half_disk) == X_axis

    c1 = ComplexPlane(Interval(0, 4) * Interval(0, 2 * S.Pi), polar=True)
    assert c1.intersect(Interval(1, 5)) == Interval(1, 4)
    assert c1.intersect(Interval(4, 9)) == FiniteSet(4)
    assert c1.intersect(Interval(5, 12)) == EmptySet()

    # Rectangular form
    X_axis = ComplexPlane(Interval(-oo, oo) * FiniteSet(0))

    unit_square = ComplexPlane(Interval(-1, 1) * Interval(-1, 1))
    upper_half_unit_square = ComplexPlane(Interval(-1, 1) * Interval(0, 1))
    upper_half_plane = ComplexPlane(Interval(-oo, oo) * Interval(0, oo))
    lower_half_plane = ComplexPlane(Interval(-oo, oo) * Interval(-oo, 0))
    right_half_plane = ComplexPlane(Interval(0, oo) * Interval(-oo, oo))
    first_quad_plane = ComplexPlane(Interval(0, oo) * Interval(0, oo))

    assert upper_half_plane.intersect(unit_square) == upper_half_unit_square
    assert right_half_plane.intersect(first_quad_plane) == first_quad_plane
    assert upper_half_plane.intersect(right_half_plane) == first_quad_plane
    assert upper_half_plane.intersect(lower_half_plane) == X_axis

    c1 = ComplexPlane(Interval(-5, 5) * Interval(-10, 10))
    assert c1.intersect(Interval(2, 7)) == Interval(2, 5)
    assert c1.intersect(Interval(5, 7)) == FiniteSet(5)
    assert c1.intersect(Interval(6, 9)) == EmptySet()

    # unevaluated object
    C1 = ComplexPlane(Interval(0, 1) * Interval(0, 2 * S.Pi), polar=True)
    C2 = ComplexPlane(Interval(-1, 1) * Interval(-1, 1))
    assert C1.intersect(C2) == Intersection(C1, C2)
Example #4
0
def test_infinitely_indexed_set_1():
    from sympy.abc import n, m, t
    assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers)

    assert imageset(Lambda(n, 2*n), S.Integers).intersect(imageset(Lambda(m, 2*m + 1), S.Integers)) == \
            EmptySet()

    assert imageset(Lambda(n, 2*n), S.Integers).intersect(imageset(Lambda(n, 2*n + 1), S.Integers)) == \
            EmptySet()

    assert imageset(Lambda(m, 2*m), S.Integers).intersect(imageset(Lambda(n, 3*n), S.Integers)) == \
            ImageSet(Lambda(t, 6*t), S.Integers)
Example #5
0
def apply(given):
    assert isinstance(given, StrictGreaterThan)
    A_abs, zero = given.args
    assert A_abs.is_Abs and zero.is_zero
    A = A_abs.arg

    return Unequality(A, EmptySet(), given=given)
Example #6
0
def apply(given):
    assert given.is_Equality
    assert given.lhs.is_Complement
    A, B = given.lhs.args
    assert given.rhs == A

    return Equality(A & B, EmptySet(), given=given)
Example #7
0
def apply(given):
    assert isinstance(given, GreaterThan)
    A_abs, positive = given.args
    assert A_abs.is_Abs and positive.is_positive
    A = A_abs.arg

    return Unequality(A, EmptySet(), given=given)
Example #8
0
    def _intersect(self, other):
        from sympy import Dummy
        from sympy.solvers.diophantine import diophantine
        from sympy.sets.sets import imageset
        if self.base_set is S.Integers:
            if isinstance(other, ImageSet) and other.base_set is S.Integers:
                f, g = self.lamda.expr, other.lamda.expr
                n, m = self.lamda.variables[0], other.lamda.variables[0]

                # Diophantine sorts the solutions according to the alphabetic
                # order of the variable names, since the result should not depend
                # on the variable name, they are replaced by the dummy variables
                # below
                a, b = Dummy('a'), Dummy('b')
                f, g = f.subs(n, a), g.subs(m, b)
                solns_set = diophantine(f - g)
                if solns_set == set():
                    return EmptySet()
                solns = list(diophantine(f - g))
                if len(solns) == 1:
                    t = list(solns[0][0].free_symbols)[0]
                else:
                    return None

                # since 'a' < 'b'
                return imageset(Lambda(t, f.subs(a, solns[0][0])), S.Integers)
Example #9
0
def prove(Eq):
    A = Symbol.A(dtype=dtype.integer, given=True)
    B = Symbol.B(dtype=dtype.integer, given=True)

    Eq << apply(Equality(B - A, EmptySet()))

    Eq << Eq[0].union(A).reversed

    Eq << Eq[1].subs(Eq[-1])
Example #10
0
def test_bool_as_set():
    x = symbols('x')

    assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2)
    assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo)
    assert Not(x > 2).as_set() == Interval(-oo, 2)
    # issue 10240
    assert Not(And(x > 2, x < 3)).as_set() == \
        Union(Interval(-oo,2),Interval(3,oo))
    assert true.as_set() == S.UniversalSet
    assert false.as_set() == EmptySet()
Example #11
0
def test_minima():
    from sympy import Integers
    x, y, n = symbols('x y n')
    assert minima(sin(x), x) == ImageSet(Lambda(n, 2*pi*n + 3*pi/2), Integers)
    assert minima(sin(x), x, Interval(0, 2*pi)) == {3*pi/2}
    assert minima(sin(x)-x, x) == EmptySet()
    assert minima(x - x**3, x, Interval(-1, 2)) == {-sqrt(3)/3}
    assert minima(sin(x)**2, x, Interval(-pi/2, pi/2)) == {0}
    assert minima(sin(x)*cos(x), x, Interval(0, 2*pi)) == {3*pi/4, 7*pi/4}
    #assert minima((x+3)*(x-2), x) == {-1/2}
    assert minima((x+3)/(x-2), x) == EmptySet()
    assert minima(x**5-3*x**3+2*x**2+6, x) == {0, 1}
    assert minima(exp(x), x) == EmptySet()
    assert minima(log(x) - x, x) == EmptySet()
    assert minima(y, x) == EmptySet()

    raises(ValueError, lambda : maxima(sin(x), x, S.EmptySet))
    raises(ValueError, lambda : maxima(log(cos(x)), x, S.EmptySet))
    raises(ValueError, lambda : maxima(1/(x**2 + y**2 + 1), x, S.EmptySet))
    raises(ValueError, lambda : maxima(sin(x), sin(x)))
    raises(ValueError, lambda : maxima(sin(x), x*y, S.EmptySet))
    raises(ValueError, lambda : maxima(sin(x), S(1)))
Example #12
0
    def as_set(self):
        """
        Rewrite logic operators and relationals in terms of real sets.

        Examples
        ========

        >>> from sympy import false
        >>> false.as_set()
        EmptySet()
        """
        from sympy.sets.sets import EmptySet
        return EmptySet()
Example #13
0
def test_bool_as_set():
    assert ITE(y <= 0, False, y >= 1).as_set() == Interval(1, oo)
    assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2)
    assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo)
    assert Not(x > 2).as_set() == Interval(-oo, 2)
    # issue 10240
    assert Not(And(x > 2, x < 3)).as_set() == \
        Union(Interval(-oo, 2), Interval(3, oo))
    assert true.as_set() == S.UniversalSet
    assert false.as_set() == EmptySet()
    assert x.as_set() == S.UniversalSet
    assert And(Or(x < 1, x > 3), x < 2).as_set() == Interval.open(-oo, 1)
    assert And(x < 1, sin(x) < 3).as_set() == (x < 1).as_set()
    raises(NotImplementedError, lambda: (sin(x) < 1).as_set())
Example #14
0
    def _intersect(self, other):
        from sympy.solvers.diophantine import diophantine
        if self.base_set is S.Integers:
            g = None
            if isinstance(other, ImageSet) and other.base_set is S.Integers:
                g = other.lamda.expr
                m = other.lamda.variables[0]
            elif other is S.Integers:
                m = g = Dummy('x')
            if g is not None:
                f = self.lamda.expr
                n = self.lamda.variables[0]
                # Diophantine sorts the solutions according to the alphabetic
                # order of the variable names, since the result should not depend
                # on the variable name, they are replaced by the dummy variables
                # below
                a, b = Dummy('a'), Dummy('b')
                f, g = f.subs(n, a), g.subs(m, b)
                solns_set = diophantine(f - g)
                if solns_set == set():
                    return EmptySet()
                solns = list(diophantine(f - g))

                if len(solns) != 1:
                    return

                # since 'a' < 'b', select soln for n
                nsol = solns[0][0]
                t = nsol.free_symbols.pop()
                return imageset(Lambda(n, f.subs(a, nsol.subs(t, n))),
                                S.Integers)

        if other == S.Reals:
            from sympy.solvers.solveset import solveset_real
            from sympy.core.function import expand_complex
            if len(self.lamda.variables) > 1:
                return None

            f = self.lamda.expr
            n = self.lamda.variables[0]

            n_ = Dummy(n.name, real=True)
            f_ = f.subs(n, n_)

            re, im = f_.as_real_imag()
            im = expand_complex(im)

            return imageset(Lambda(n_, re),
                            self.base_set.intersect(solveset_real(im, n_)))
Example #15
0
def codomain(func, domain, *syms):
    """ Finds the range of a real-valued function, for a real-domain

    Parameters
    ==========

    func: Expr
          The expression whose range is to be found
    domain: Union of Sets
          The real-domain for the variable involved in function
    syms: Tuple of symbols
          Symbol whose domain is given

    Raises
    ======

    NotImplementedError
          The algorithms to find the range of the given function are
          not yet implemented.
    ValueError
          The input is not valid.
    RuntimeError
          It is a bug, please report it to the github issue tracker
          (https://github.com/sympy/sympy/issues).

    Examples
    ========

    >>> from sympy import Symbol, S, Interval, Union, FiniteSet, codomain
    >>> x = Symbol('x', real=True)
    >>> codomain(x**2, Interval(-1, 1), x)
    [0, 1]
    >>> codomain(x/(x**2 - 4), Union(Interval(-1, 3), FiniteSet(5)), x)
    (-oo, 1/3] U [3/5, oo)
    >>> codomain(x**2/(x**2 - 4), S.Reals, x)
    (-oo, 0] U (1, oo)
    """

    func = sympify(func)
    if not isinstance(domain, Set):
        raise ValueError('A Set must be given, not %s: %s' %
                         (type(domain), domain))

    # TODO: handle piecewise defined functions
    # TODO: handle transcendental functions
    # TODO: handle multivariate functions
    if len(syms) == 0:
        raise ValueError("A Symbol or a tuple of symbols must be given")

    if len(syms) == 1:
        sym = syms[0]
    else:
        raise NotImplementedError("more than one variables %s not handled" %
                                  (syms, ))

    if not func.has(sym):
        return FiniteSet(func)

    # this block of code can be replaced by
    # sing = Intersection(FiniteSet(*sing), domain.closure)
    # after the issue #9706 has been fixed
    def closure_handle(set_im, singul):
        if set_im.has(Interval):
            if not oo in set_im.boundary:
                if not S.NegativeInfinity in set_im.boundary:
                    return Intersection(FiniteSet(*singul), set_im.closure)
                return Intersection(
                    FiniteSet(*singul),
                    Union(set_im, FiniteSet(max(set_im.boundary))))
            else:
                if not S.NegativeInfinity in set_im.boundary:
                    return Intersection(
                        FiniteSet(*singul),
                        Union(set_im, FiniteSet(min(set_im.boundary))))
                return Intersection(FiniteSet(*singul), set_im)
        return Intersection(FiniteSet(*singul), set_im)

    # all the singularities of the function
    sing = solveset(func.as_numer_denom()[1], sym, domain=S.Reals)
    sing_in_domain = closure_handle(domain, sing)
    domain = Complement(domain, sing_in_domain)

    if domain.is_EmptySet:
        return EmptySet()

    def codomain_interval(f, set_val, *sym):
        symb = sym[0]
        df1 = diff(f, symb)
        df2 = diff(df1, symb)
        der_zero = solveset(df1, symb, domain=S.Reals)
        der_zero_in_dom = closure_handle(set_val, der_zero)

        local_maxima = set()
        local_minima = set()
        start_val = limit(f, symb, set_val.start)
        end_val = limit(f, symb, set_val.end, '-')

        if start_val is S.Infinity or end_val is S.Infinity:
            local_maxima = set([(oo, True)])
        elif start_val is S.NegativeInfinity or end_val is S.NegativeInfinity:
            local_minima = set([(-oo, True)])

        if (not start_val.is_real) or (not end_val.is_real):
            raise ValueError('Function does not contain all points of %s '
                             'as its domain' % (domain))

        if local_maxima == set():
            if start_val > end_val:
                local_maxima = set([(start_val, set_val.left_open)])
            elif start_val < end_val:
                local_maxima = set([(end_val, set_val.right_open)])
            else:
                local_maxima = set([(start_val, set_val.left_open
                                     and set_val.right_open)])

        if local_minima == set():
            if start_val < end_val:
                local_minima = set([(start_val, set_val.left_open)])
            elif start_val > end_val:
                local_minima = set([(end_val, set_val.right_open)])
            else:
                local_minima = set([(start_val, set_val.left_open
                                     and set_val.right_open)])

        for i in der_zero_in_dom:
            exist = not i in set_val
            if df2.subs({symb: i}) < 0:
                local_maxima.add((f.subs({symb: i}), exist))
            elif df2.subs({symb: i}) > 0:
                local_minima.add((f.subs({symb: i}), exist))

        maximum = (-oo, True)
        minimum = (oo, True)

        for i in local_maxima:
            if i[0] > maximum[0]:
                maximum = i
            elif i[0] == maximum[0]:
                maximum = (maximum[0], i[1] and maximum[1])

        for i in local_minima:
            if i[0] < minimum[0]:
                minimum = i
            elif i[0] == minimum[0]:
                minimum = (minimum[0], i[1] and minimum[1])

        return Union(Interval(minimum[0], maximum[0], minimum[1], maximum[1]))

    if isinstance(domain, Union):
        return Union(*[
            codomain(func, intrvl_or_finset, sym)
            for intrvl_or_finset in domain.args
        ])

    if isinstance(domain, Interval):
        return codomain_interval(func, domain, sym)

    if isinstance(domain, FiniteSet):
        return FiniteSet(*[
            limit(func, sym, i) if i in
            FiniteSet(-oo, oo) else func.subs({sym: i}) for i in domain
        ])
Example #16
0
def not_empty_in(finset_intersection, *syms):
    """ Finds the domain of the functions in `finite_set` in which the
    `finite_set` is not-empty

    Parameters
    ==========

    finset_intersection: The unevaluated intersection of FiniteSet containing
                        real-valued functions with Union of Sets
    syms: Tuple of symbols
            Symbol for which domain is to be found

    Raises
    ======

    NotImplementedError
        The algorithms to find the non-emptiness of the given FiniteSet are
        not yet implemented.
    ValueError
        The input is not valid.
    RuntimeError
        It is a bug, please report it to the github issue tracker
        (https://github.com/sympy/sympy/issues).

    Examples
    ========

    >>> from sympy import FiniteSet, Interval, not_empty_in, oo
    >>> from sympy.abc import x
    >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x)
    Interval(0, 2)
    >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x)
    Union(Interval(-sqrt(2), -1), Interval(1, 2))
    >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x)
    Union(Interval(-2, -1, True), Interval(2, oo, False, True))
    """

    # TODO: handle piecewise defined functions
    # TODO: handle transcendental functions
    # TODO: handle multivariate functions
    if len(syms) == 0:
        raise ValueError("One or more symbols must be given in syms.")

    if finset_intersection.is_EmptySet:
        return EmptySet()

    if isinstance(finset_intersection, Union):
        elm_in_sets = finset_intersection.args[0]
        return Union(not_empty_in(finset_intersection.args[1], *syms),
                     elm_in_sets)

    if isinstance(finset_intersection, FiniteSet):
        finite_set = finset_intersection
        _sets = S.Reals
    else:
        finite_set = finset_intersection.args[1]
        _sets = finset_intersection.args[0]

    if not isinstance(finite_set, FiniteSet):
        raise ValueError('A FiniteSet must be given, not %s: %s' %
                         (type(finite_set), finite_set))

    if len(syms) == 1:
        symb = syms[0]
    else:
        raise NotImplementedError('more than one variables %s not handled' %
                                  (syms,))

    def elm_domain(expr, intrvl):
        """ Finds the domain of an expression in any given interval """
        from sympy.solvers.solveset import solveset

        _start = intrvl.start
        _end = intrvl.end
        _singularities = solveset(expr.as_numer_denom()[1], symb,
                                  domain=S.Reals)

        if intrvl.right_open:
            if _end is S.Infinity:
                _domain1 = S.Reals
            else:
                _domain1 = solveset(expr < _end, symb, domain=S.Reals)
        else:
            _domain1 = solveset(expr <= _end, symb, domain=S.Reals)

        if intrvl.left_open:
            if _start is S.NegativeInfinity:
                _domain2 = S.Reals
            else:
                _domain2 = solveset(expr > _start, symb, domain=S.Reals)
        else:
            _domain2 = solveset(expr >= _start, symb, domain=S.Reals)

        # domain in the interval
        expr_with_sing = Intersection(_domain1, _domain2)
        expr_domain = Complement(expr_with_sing, _singularities)
        return expr_domain

    if isinstance(_sets, Interval):
        return Union(*[elm_domain(element, _sets) for element in finite_set])

    if isinstance(_sets, Union):
        _domain = S.EmptySet
        for intrvl in _sets.args:
            _domain_element = Union(*[elm_domain(element, intrvl)
                                    for element in finite_set])
            _domain = Union(_domain, _domain_element)
        return _domain
Example #17
0
def prove(Eq):

    n = Symbol.n(domain=[2, oo], integer=True)

    x = Symbol.x(shape=(oo, ), integer=True)

    k = Symbol.k(integer=True)

    j = Symbol.j(domain=[0, n - 1], integer=True, given=True)

    Eq << apply(
        Equality(x[:n].set_comprehension(k), Interval(0, n - 1, integer=True)),
        j)

    Eq << Eq[1].lhs.this.definition

    Eq <<= Eq[-3].subs(Eq[-1]), Eq[-2].subs(Eq[-1])

    Eq << Eq[-1].lhs.indices[0].this.expand()

    Eq << Eq[-1].rhs.function.args[1].this.as_Piecewise()

    Eq << Eq[-2].this.rhs.subs(Eq[-1])

    Eq << Eq[-1].rhs.subs(1, 0).this.bisect({0})

    assert Eq[-1].lhs.limits[0][1].args[-1][-1].step.is_zero == False
    Eq << Eq[-2].subs(Eq[-1].reversed)

    assert Eq[-1].rhs.limits[0][1].args[-1][-1].step.is_zero == False

    sj = Symbol.s_j(definition=Eq[-1].rhs.limits[0][1])

    Eq.sj_definition = sj.equality_defined()
    assert Eq.sj_definition.rhs.limits[0][-1].step.is_zero == False

    Eq.crossproduct = Eq[-1].subs(Eq.sj_definition.reversed)

    Eq.sj_definition_reversed = Eq.sj_definition.this.rhs.limits[0][1].reversed
    assert Eq.sj_definition_reversed.args[-1].args[-1][
        -1].step.is_zero == False
    Eq.sj_definition_reversed = Eq.sj_definition_reversed.reversed

    assert Eq.sj_definition_reversed.lhs.args[-1][-1].step.is_zero == False

    Eq << Eq[0].intersect({j})

    Eq << Piecewise((x[k].set, Equality(x[k], j)),
                    (EmptySet(), True)).this.simplify()

    Eq << Eq[-1].reversed.union_comprehension((k, 0, n - 1))

    Eq.distribute = Eq[-1].subs(Eq[-3]).reversed

    Eq << Eq.distribute.this.lhs.function.subs(
        Eq.distribute.lhs.limits[0][1].args[1][1])

    Eq << Eq[-1].as_Or()

    Eq << Eq[-1].subs(Eq.sj_definition_reversed)

    Eq.sj_greater_than_1 = greater_than.apply(Eq[-1])

    Eq.distribute = Eq.distribute.subs(Eq.sj_definition_reversed)

    Eq << Eq.sj_greater_than_1.lhs.assertion()

    Eq.sj_less_than_1, Eq.inequality_ab = Eq[-1].split()

    (a, *_), (b, *_) = Eq.inequality_ab.limits

    Eq << sets.equality.imply.forall_equality.nonoverlapping.apply(
        Eq[0].abs(), excludes=Eq.inequality_ab.variables_set)

    Eq << Eq[-1].subs(k, a)

    Eq << Eq[-1].subs(Eq[-1].variable, b)

    Eq << (Eq.inequality_ab & Eq[-1])

    Eq.distribute_ab = Eq[-1].this.function.distribute()

    Eq.j_equality, _ = sj.assertion().split()

    Eq.i_domain = ForAll[a:sj](Contains(a, Interval(0, n - 1, integer=True)),
                               plausible=True)
    Eq << Eq.i_domain.simplify()

    Eq.sj_element_contains = ForAll[b:sj](Contains(
        b, Interval(0, n - 1, integer=True)),
                                          plausible=True)
    Eq << Eq.sj_element_contains.simplify()

    Eq << Eq.i_domain.apply(sets.contains.imply.equality.union)

    Eq << Eq.distribute_ab.subs(Eq[-1])

    Eq << (Eq[-1] & Eq.sj_element_contains)

    Eq << Eq.j_equality.limits_subs(k, a).reversed
    Eq << Eq[-2].subs(Eq[-1])

    Eq << Eq.j_equality.limits_subs(k, b).reversed

    Eq << Eq[-1].subs(Eq[-2])

    Eq << Eq.sj_less_than_1.subs(Eq.sj_greater_than_1)

    Eq << sets.equality.imply.contains.apply(Eq[-1], var=k)

    Eq.index_domain = Eq[-1].subs(Eq.crossproduct.reversed)

    Eq << Eq.j_equality.subs(k, Eq.index_domain.lhs).split()

    Eq <<= Eq[-2] & Eq.index_domain

    Eq << Eq[-1].reversed

    Eq << Subset(sj, Eq[1].rhs, plausible=True)

    Eq <<= Eq[-1] & Eq.index_domain
Example #18
0
    def _intersect(self, other):
        from sympy.solvers.diophantine import diophantine
        if self.base_set is S.Integers:
            g = None
            if isinstance(other, ImageSet) and other.base_set is S.Integers:
                g = other.lamda.expr
                m = other.lamda.variables[0]
            elif other is S.Integers:
                m = g = Dummy('x')
            if g is not None:
                f = self.lamda.expr
                n = self.lamda.variables[0]
                # Diophantine sorts the solutions according to the alphabetic
                # order of the variable names, since the result should not depend
                # on the variable name, they are replaced by the dummy variables
                # below
                a, b = Dummy('a'), Dummy('b')
                f, g = f.subs(n, a), g.subs(m, b)
                solns_set = diophantine(f - g)
                if solns_set == set():
                    return EmptySet()
                solns = list(diophantine(f - g))

                if len(solns) != 1:
                    return

                # since 'a' < 'b', select soln for n
                nsol = solns[0][0]
                t = nsol.free_symbols.pop()
                return imageset(Lambda(n, f.subs(a, nsol.subs(t, n))),
                                S.Integers)

        if other == S.Reals:
            from sympy.solvers.solveset import solveset_real
            from sympy.core.function import expand_complex
            if len(self.lamda.variables) > 1:
                return None

            f = self.lamda.expr
            n = self.lamda.variables[0]

            n_ = Dummy(n.name, real=True)
            f_ = f.subs(n, n_)

            re, im = f_.as_real_imag()
            im = expand_complex(im)

            return imageset(Lambda(n_, re),
                            self.base_set.intersect(solveset_real(im, n_)))

        elif isinstance(other, Interval):
            from sympy.solvers.solveset import (invert_real, invert_complex,
                                                solveset)

            f = self.lamda.expr
            n = self.lamda.variables[0]
            base_set = self.base_set
            new_inf, new_sup = None, None
            new_lopen, new_ropen = other.left_open, other.right_open

            if f.is_real:
                inverter = invert_real
            else:
                inverter = invert_complex

            g1, h1 = inverter(f, other.inf, n)
            g2, h2 = inverter(f, other.sup, n)

            if all(isinstance(i, FiniteSet) for i in (h1, h2)):
                if g1 == n:
                    if len(h1) == 1:
                        new_inf = h1.args[0]
                if g2 == n:
                    if len(h2) == 1:
                        new_sup = h2.args[0]
                # TODO: Design a technique to handle multiple-inverse
                # functions

                # Any of the new boundary values cannot be determined
                if any(i is None for i in (new_sup, new_inf)):
                    return

                range_set = S.EmptySet

                if all(i.is_real for i in (new_sup, new_inf)):
                    # this assumes continuity of underlying function
                    # however fixes the case when it is decreasing
                    if new_inf > new_sup:
                        new_inf, new_sup = new_sup, new_inf
                    new_interval = Interval(new_inf, new_sup, new_lopen,
                                            new_ropen)
                    range_set = base_set._intersect(new_interval)
                else:
                    if other.is_subset(S.Reals):
                        solutions = solveset(f, n, S.Reals)
                        if not isinstance(range_set, (ImageSet, ConditionSet)):
                            range_set = solutions._intersect(other)
                        else:
                            return

                if range_set is S.EmptySet:
                    return S.EmptySet
                elif isinstance(range_set,
                                Range) and range_set.size is not S.Infinity:
                    range_set = FiniteSet(*list(range_set))

                if range_set is not None:
                    return imageset(Lambda(n, f), range_set)
                return
            else:
                return
Example #19
0
def empty_set():
    return AtSet(EmptySet(), EmptySet())
Example #20
0
def apply(e, s):
    return Equality(s & e.set, Piecewise((e.set, Contains(e, s)), (EmptySet(), True)))