Ejemplo n.º 1
0
def test_Lambda():
    e = Lambda(x, x**2)
    assert e(4) == 16
    assert e(x) == x**2
    assert e(y) == y**2

    assert Lambda(x, x**2) == Lambda(x, x**2)
    assert Lambda(x, x**2) == Lambda(y, y**2)
    assert Lambda(x, x**2) != Lambda(y, y**2 + 1)
    assert Lambda((x, y), x**y) == Lambda((y, x), y**x)
    assert Lambda((x, y), x**y) != Lambda((x, y), y**x)

    assert Lambda((x, y), x**y)(x, y) == x**y
    assert Lambda((x, y), x**y)(3, 3) == 3**3
    assert Lambda((x, y), x**y)(x, 3) == x**3
    assert Lambda((x, y), x**y)(3, y) == 3**y
    assert Lambda(x, f(x))(x) == f(x)
    assert Lambda(x, x**2)(e(x)) == x**4
    assert e(e(x)) == x**4

    assert Lambda((x, y), x + y).nargs == FiniteSet(2)

    p = x, y, z, t
    assert Lambda(p, t * (x + y + z))(*p) == t * (x + y + z)

    assert Lambda(x, 2 * x) + Lambda(y, 2 * y) == 2 * Lambda(x, 2 * x)
    assert Lambda(x, 2 * x) not in [Lambda(x, x)]
    pytest.raises(TypeError, lambda: Lambda(1, x))
    assert Lambda(x, 1)(1) is Integer(1)

    assert (2 * x).canonical_variables == {}
    assert Lambda(x, 2 * x).canonical_variables == {x: Symbol('0_')}
    x_ = Symbol('x_')
    assert Lambda(x_, 2 * x_).canonical_variables == {x_: Symbol('0__')}
Ejemplo n.º 2
0
def test_imageset_intersect_real():
    assert (imageset(Lambda(n, n + (n - 1)*(n + 1)*I),
                     S.Integers).intersect(S.Reals) ==
            FiniteSet(-1, 1))

    s = ImageSet(Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))), S.Integers)
    assert s.intersect(S.Reals) == imageset(Lambda(n, 2*n*pi - pi/4), S.Integers)
Ejemplo n.º 3
0
def test_Function():
    class myfunc(Function):
        @classmethod
        def eval(cls, x):  # one arg
            return

    assert myfunc.nargs == FiniteSet(1)
    assert myfunc(x).nargs == FiniteSet(1)
    pytest.raises(TypeError, lambda: myfunc(x, y).nargs)

    class myfunc(Function):
        @classmethod
        def eval(cls, *x):  # star args
            return

    assert myfunc.nargs == S.Naturals0
    assert myfunc(x).nargs == S.Naturals0
Ejemplo n.º 4
0
 def set(self):
     if self.fulldomain.__class__ is SingleFiniteDomain:
         return FiniteSet(*[
             elem for elem in self.fulldomain.set
             if frozenset(((self.fulldomain.symbol, elem), )) in self
         ])
     else:
         raise NotImplementedError(
             "Not implemented on multi-dimensional conditional domain")
Ejemplo n.º 5
0
def test_range_interval_intersection():
    # Intersection with intervals
    assert FiniteSet(*Range(0, 10, 1).intersect(Interval(2, 6))) == \
        FiniteSet(2, 3, 4, 5, 6)

    # Open Intervals are removed
    assert (FiniteSet(*Range(0, 10, 1).intersect(Interval(2, 6,
                                                          True, True))) ==
            FiniteSet(3, 4, 5))

    # Try this with large steps
    assert (FiniteSet(*Range(0, 100, 10).intersect(Interval(15, 55))) ==
            FiniteSet(20, 30, 40, 50))

    # Going backwards
    assert (FiniteSet(*Range(10, -9, -3).intersect(Interval(-5, 6))) ==
            FiniteSet(-5, -2, 1, 4))
    assert (FiniteSet(*Range(10, -9, -3).intersect(Interval(-5, 6, True))) ==
            FiniteSet(-2, 1, 4))
Ejemplo n.º 6
0
def test_ImageSet():
    squares = ImageSet(Lambda(x, x**2), S.Naturals)
    assert 4 in squares
    assert 5 not in squares
    assert FiniteSet(*range(10)).intersect(squares) == FiniteSet(1, 4, 9)

    assert 16 not in squares.intersect(Interval(0, 10))

    si = iter(squares)
    a, b, c, d = next(si), next(si), next(si), next(si)
    assert (a, b, c, d) == (1, 4, 9, 16)

    harmonics = ImageSet(Lambda(x, 1/x), S.Naturals)
    assert Rational(1, 5) in harmonics
    assert Rational(.25) in harmonics
    assert 0.25 not in harmonics
    assert Rational(.3) not in harmonics

    assert harmonics.is_iterable
Ejemplo n.º 7
0
    def _intersect(self, other):
        from diofant import Dummy
        from diofant.solvers.diophantine import diophantine
        from diofant.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

                # since 'a' < 'b'
                return imageset(Lambda(t, f.subs(a, solns[0][0])), S.Integers)

        if other == S.Reals:
            from diofant.solvers.diophantine import diophantine
            from diofant.core.function import expand_complex
            if len(self.lamda.variables
                   ) > 1 or self.base_set is not S.Integers:
                return

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

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

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

            sols = list(diophantine(im, n_))
            if not sols:
                return S.EmptySet
            elif all(s[0].has(n_) is False for s in sols):
                s = FiniteSet(*[s[0] for s in sols])
            elif len(sols) == 1 and sols[0][0].has(n_):
                s = imageset(Lambda(n_, sols[0][0]), S.Integers)
            else:
                return

            return imageset(Lambda(n_, re), self.base_set.intersect(s))
Ejemplo n.º 8
0
def test_univariate_relational_as_set():
    assert (x > 0).as_set() == Interval(0, oo, True, True)
    assert (x >= 0).as_set() == Interval(0, oo, False, True)
    assert (x < 0).as_set() == Interval(-oo, 0, True, True)
    assert (x <= 0).as_set() == Interval(-oo, 0, True)
    assert Eq(x, 0).as_set() == FiniteSet(0)
    assert Ne(x, 0).as_set() == Interval(-oo, 0, True, True) + \
        Interval(0, oo, True, True)

    assert (x**2 >= 4).as_set() == (Interval(-oo, -2, True) +
                                    Interval(2, oo, False, True))
Ejemplo n.º 9
0
def test_nargs():
    f = Function('f')
    assert f.nargs == S.Naturals0
    assert f(1).nargs == S.Naturals0
    assert Function('f', nargs=2)(1, 2).nargs == FiniteSet(2)
    assert sin.nargs == FiniteSet(1)
    assert sin(2).nargs == FiniteSet(1)
    assert log.nargs == FiniteSet(1, 2)
    assert log(2).nargs == FiniteSet(1, 2)
    assert Function('f', nargs=2).nargs == FiniteSet(2)
    assert Function('f', nargs=0).nargs == FiniteSet(0)
    assert Function('f', nargs=(0, 1)).nargs == FiniteSet(0, 1)
    assert Function('f', nargs=None).nargs == S.Naturals0
    pytest.raises(ValueError, lambda: Function('f', nargs=()))

    p = Function('g', nargs=(1, 2))(1)
    assert p.args == (1, ) and p.nargs == FiniteSet(1, 2)
Ejemplo n.º 10
0
    def __new__(cls, *spaces):
        rs_space_dict = {}
        for space in spaces:
            for value in space.values:
                rs_space_dict[value] = space

        symbols = FiniteSet(*[val.symbol for val in rs_space_dict.keys()])

        # Overlapping symbols
        if len(symbols) < sum(len(space.symbols) for space in spaces):
            raise ValueError("Overlapping Random Variables")

        if all(space.is_Finite for space in spaces):
            from diofant.stats.frv import ProductFinitePSpace
            cls = ProductFinitePSpace
        if all(space.is_Continuous for space in spaces):
            from diofant.stats.crv import ProductContinuousPSpace
            cls = ProductContinuousPSpace

        obj = Basic.__new__(cls, *FiniteSet(*spaces))

        return obj
Ejemplo n.º 11
0
    def __new__(cls, *partition):
        """
        Generates a new partition object.

        This method also verifies if the arguments passed are
        valid and raises a ValueError if they are not.

        Examples
        ========

        >>> from diofant.combinatorics.partitions import Partition
        >>> a = Partition([1, 2], [3])
        >>> a
        {{3}, {1, 2}}
        >>> a.partition
        [[1, 2], [3]]
        >>> len(a)
        2
        >>> a.members
        (1, 2, 3)

        """
        args = partition
        if not all(isinstance(part, (list, FiniteSet)) for part in args):
            raise ValueError(
                "Each argument to Partition should be a list or a FiniteSet")

        # sort so we have a canonical reference for RGS
        partition = sorted(sum(list(map(list, partition)), []),
                           key=default_sort_key)
        if has_dups(partition):
            raise ValueError("Partition contained duplicated elements.")

        obj = FiniteSet.__new__(cls, *[FiniteSet(*x) for x in args])
        obj.members = tuple(partition)
        obj.size = len(partition)
        return obj
Ejemplo n.º 12
0
def test_sympyissue_11732():
    interval12 = Interval(1, 2)
    finiteset1234 = FiniteSet(1, 2, 3, 4)
    pointComplex = (1, 2)

    assert (interval12 in S.Naturals) is False
    assert (interval12 in S.Naturals0) is False
    assert (interval12 in S.Integers) is False

    assert (finiteset1234 in S.Naturals) is False
    assert (finiteset1234 in S.Naturals0) is False
    assert (finiteset1234 in S.Integers) is False

    assert (pointComplex in S.Naturals) is False
    assert (pointComplex in S.Naturals0) is False
    assert (pointComplex in S.Integers) is False
Ejemplo n.º 13
0
    def __new__(cls, *domains):
        symbols = sumsets([domain.symbols for domain in domains])

        # Flatten any product of products
        domains2 = []
        for domain in domains:
            if not domain.is_ProductDomain:
                domains2.append(domain)
            else:
                domains2.extend(domain.domains)
        domains2 = FiniteSet(*domains2)

        if all(domain.is_Finite for domain in domains2):
            from diofant.stats.frv import ProductFiniteDomain
            cls = ProductFiniteDomain
        if all(domain.is_Continuous for domain in domains2):
            from diofant.stats.crv import ProductContinuousDomain
            cls = ProductContinuousDomain

        return Basic.__new__(cls, *domains2)
Ejemplo n.º 14
0
 def elements(self):
     return FiniteSet(*self)
Ejemplo n.º 15
0
def test_fun():
    assert (FiniteSet(*ImageSet(Lambda(x, sin(pi*x/4)), Range(-10, 11))) ==
            FiniteSet(-1, -sqrt(2)/2, 0, sqrt(2)/2, 1))
Ejemplo n.º 16
0
 def symbols(self):
     return FiniteSet(*[val.symbol for val in self.rs_space_dict.keys()])
Ejemplo n.º 17
0
def solve_univariate_inequality(expr, gen, relational=True):
    """
    Solves a real univariate inequality.

    Examples
    ========

    >>> from diofant.solvers.inequalities import solve_univariate_inequality
    >>> from diofant.core.symbol import Symbol

    >>> x = Symbol('x', real=True)

    >>> solve_univariate_inequality(x**2 >= 4, x)
    Or(2 <= x, x <= -2)
    >>> solve_univariate_inequality(x**2 >= 4, x, relational=False)
    (-oo, -2] U [2, oo)
    """
    from diofant.simplify.simplify import simplify
    from diofant.solvers.solvers import solve, denoms

    e = expr.lhs - expr.rhs
    parts = n, d = e.as_numer_denom()
    if all(i.is_polynomial(gen) for i in parts):
        solns = solve(n, gen, check=False)
        singularities = solve(d, gen, check=False)
    else:
        solns = solve(e, gen, check=False)
        singularities = []
        for d in denoms(e):
            singularities.extend(solve(d, gen))

    include_x = expr.func(0, 0)

    def valid(x):
        v = e.subs(gen, x)
        try:
            r = expr.func(v, 0)
        except TypeError:
            r = S.false
        r = simplify(r)
        if r in (S.true, S.false):
            return r
        if v.is_extended_real is False:
            return S.false
        else:
            if v.is_comparable:
                v = v.n(2)
                if v._prec > 1:
                    return expr.func(v, 0)
            elif v.is_comparable is False:
                return False
            raise NotImplementedError

    start = S.NegativeInfinity
    sol_sets = [S.EmptySet]
    try:
        reals = _nsort(set(solns + singularities), separated=True)[0]
    except NotImplementedError:
        raise NotImplementedError('sorting of these roots is not supported')
    for x in reals:
        end = x

        if end in [S.NegativeInfinity, S.Infinity]:
            if valid(Integer(0)):
                sol_sets.append(Interval(start, S.Infinity, True, True))
                break

        if valid((start + end) / 2 if start != S.NegativeInfinity else end -
                 1):
            sol_sets.append(Interval(start, end, True, True))

        if x in singularities:
            singularities.remove(x)
        elif include_x:
            sol_sets.append(FiniteSet(x))

        start = end

    end = S.Infinity

    if valid(start + 1):
        sol_sets.append(Interval(start, end, True, True))

    rv = Union(*sol_sets)
    return rv if not relational else rv.as_relational(gen)
Ejemplo n.º 18
0
 def elements(self):
     return FiniteSet(
         *[frozenset(((self.symbol, elem), )) for elem in self.set])
Ejemplo n.º 19
0
 def symbols(self):
     return FiniteSet(self.symbol)
Ejemplo n.º 20
0
 def __new__(cls, symbol, set):
     if not isinstance(set, FiniteSet):
         set = FiniteSet(*set)
     return Basic.__new__(cls, symbol, set)
Ejemplo n.º 21
0
 def dict(self):
     return FiniteSet(*[Dict(dict(el)) for el in self.elements])
Ejemplo n.º 22
0
 def symbols(self):
     return FiniteSet(sym for sym, val in self.elements)
Ejemplo n.º 23
0
 def spaces(self):
     return FiniteSet(*self.args)
Ejemplo n.º 24
0
 def symbols(self):
     return FiniteSet(*[sym for domain in self.domains
                        for sym in domain.symbols])
Ejemplo n.º 25
0
 def __new__(cls, symbols, *args):
     symbols = FiniteSet(*symbols)
     return Basic.__new__(cls, symbols, *args)