Beispiel #1
0
def test_is_decreasing():
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.Ropen(-oo,
                                                            S(3) / 2)) is False
    assert is_decreasing(-x**2, Interval(-oo, 0)) is False
    assert is_decreasing(-x**2 * b, Interval(-oo, 0), x) is False
Beispiel #2
0
def test_is_decreasing():
    """Test whether is_decreasing returns correct value."""
    b = Symbol('b', positive=True)

    assert is_decreasing(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert not is_decreasing(1 / (x**2 - 3 * x), Interval.Ropen(-oo, S(3) / 2))
    assert not is_decreasing(-x**2, Interval(-oo, 0))
    assert not is_decreasing(-x**2 * b, Interval(-oo, 0), x)
def test_is_decreasing():
    """Test whether is_decreasing returns correct value."""
    b = Symbol('b', positive=True)

    assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
    assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
    assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
    assert not is_decreasing(-x**2, Interval(-oo, 0))
    assert not is_decreasing(-x**2*b, Interval(-oo, 0), x)
Beispiel #4
0
def test_is_decreasing():
    """Test whether is_decreasing returns correct value."""
    b = Symbol("b", positive=True)

    assert is_decreasing(1 / (x**2 - 3 * x), Interval.open(1.5, 3))
    assert is_decreasing(1 / (x**2 - 3 * x), Interval.Lopen(3, oo))
    assert not is_decreasing(1 / (x**2 - 3 * x),
                             Interval.Ropen(-oo, Rational(3, 2)))
    assert not is_decreasing(-(x**2), Interval(-oo, 0))
    assert not is_decreasing(-(x**2) * b, Interval(-oo, 0), x)
    def value(self, add):
        for term in add.args:
            if term.is_number or term in self.bounds or len(
                    term.free_symbols) != 1:
                continue
            fs, = term.free_symbols
            if fs not in self.bounds:
                continue
            intrvl = Interval(*self.bounds[fs])
            if is_increasing(term, intrvl, fs):
                self.bounds[term] = (term.subs({fs: self.bounds[fs][0]}),
                                     term.subs({fs: self.bounds[fs][1]}))
            elif is_decreasing(term, intrvl, fs):
                self.bounds[term] = (term.subs({fs: self.bounds[fs][1]}),
                                     term.subs({fs: self.bounds[fs][0]}))
            else:
                return add

        if all(term.is_number or term in self.bounds for term in add.args):
            bounds = [(term, term) if term.is_number else self.bounds[term]
                      for term in add.args]
            largest_abs_guarantee = 0
            for lo, hi in bounds:
                if lo <= 0 <= hi:
                    continue
                largest_abs_guarantee = max(largest_abs_guarantee,
                                            min(abs(lo), abs(hi)))
            new_terms = []
            for term, (lo, hi) in zip(add.args, bounds):
                if max(abs(lo),
                       abs(hi)) >= largest_abs_guarantee * self.reltol:
                    new_terms.append(term)
            return add.func(*new_terms)
        else:
            return add
Beispiel #6
0
    def value(self, add):
        for term in add.args:
            if term.is_number or term in self.bounds or len(term.free_symbols) != 1:
                continue
            fs, = term.free_symbols
            if fs not in self.bounds:
                continue
            intrvl = Interval(*self.bounds[fs])
            if is_increasing(term, intrvl, fs):
                self.bounds[term] = (
                    term.subs({fs: self.bounds[fs][0]}),
                    term.subs({fs: self.bounds[fs][1]})
                )
            elif is_decreasing(term, intrvl, fs):
                self.bounds[term] = (
                    term.subs({fs: self.bounds[fs][1]}),
                    term.subs({fs: self.bounds[fs][0]})
                )
            else:
                return add

        if all(term.is_number or term in self.bounds for term in add.args):
            bounds = [(term, term) if term.is_number else self.bounds[term] for term in add.args]
            largest_abs_guarantee = 0
            for lo, hi in bounds:
                if lo <= 0 <= hi:
                    continue
                largest_abs_guarantee = max(largest_abs_guarantee,
                                            min(abs(lo), abs(hi)))
            new_terms = []
            for term, (lo, hi) in zip(add.args, bounds):
                if max(abs(lo), abs(hi)) >= largest_abs_guarantee*self.reltol:
                    new_terms.append(term)
            return add.func(*new_terms)
        else:
            return add
    def is_convergent(self):
        r"""Checks for the convergence of a Sum.

        We divide the study of convergence of infinite sums and products in
        two parts.

        First Part:
        One part is the question whether all the terms are well defined, i.e.,
        they are finite in a sum and also non-zero in a product. Zero
        is the analogy of (minus) infinity in products as
        :math:`e^{-\infty} = 0`.

        Second Part:
        The second part is the question of convergence after infinities,
        and zeros in products, have been omitted assuming that their number
        is finite. This means that we only consider the tail of the sum or
        product, starting from some point after which all terms are well
        defined.

        For example, in a sum of the form:

        .. math::

            \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}

        where a and b are numbers. The routine will return true, even if there
        are infinities in the term sequence (at most two). An analogous
        product would be:

        .. math::

            \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}

        This is how convergence is interpreted. It is concerned with what
        happens at the limit. Finding the bad terms is another independent
        matter.

        Note: It is responsibility of user to see that the sum or product
        is well defined.

        There are various tests employed to check the convergence like
        divergence test, root test, integral test, alternating series test,
        comparison tests, Dirichlet tests. It returns true if Sum is convergent
        and false if divergent and NotImplementedError if it can not be checked.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolutely_convergent()
        Product.is_convergent()
        """
        from sympy import Interval, Integral, log, symbols, simplify
        p, q, r = symbols('p q r', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError("convergence checking for more than one symbol "
                                      "containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity
        # and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        sym_ = Dummy(sym.name, integer=True, positive=True)
        sequence_term = sequence_term.xreplace({sym: sym_})
        sym = sym_

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func, cond in sequence_term.args:
                # see if it represents something going to oo
                if cond == True or cond.as_set().sup is S.Infinity:
                    s = Sum(func, (sym, lower_limit, upper_limit))
                    return s.is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit_seq(sequence_term, sym)
            if lim_val is not None and lim_val.is_zero is False:
                return S.false
        except NotImplementedError:
            pass

        try:
            lim_val_abs = limit_seq(abs(sequence_term), sym)
            if lim_val_abs is not None and lim_val_abs.is_zero is False:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] >= -1:
                return S.false

        p2_series_test = order.expr.match((1/sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] <= 1:
                return S.false

        ### ------------- comparison test ------------- ###
        # 1/(n**p*log(n)**q*log(log(n))**r) comparison
        n_log_test = order.expr.match(1/(sym**p*log(sym)**q*log(log(sym))**r))
        if n_log_test is not None:
            if (n_log_test[p] > 1 or
                (n_log_test[p] == 1 and n_log_test[q] > 1) or
                (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)):
                    return S.true
            return S.false

        ### ------------- Limit comparison test -----------###
        # (1/n) comparison
        try:
            lim_comp = limit_seq(sym*sequence_term, sym)
            if lim_comp is not None and lim_comp.is_number and lim_comp > 0:
                return S.false
        except NotImplementedError:
            pass

        ### ----------- ratio test ---------------- ###
        next_sequence_term = sequence_term.xreplace({sym: sym + 1})
        ratio = combsimp(powsimp(next_sequence_term/sequence_term))
        try:
            lim_ratio = limit_seq(ratio, sym)
            if lim_ratio is not None and lim_ratio.is_number:
                if abs(lim_ratio) > 1:
                    return S.false
                if abs(lim_ratio) < 1:
                    return S.true
        except NotImplementedError:
            pass

        ### ----------- root test ---------------- ###
        # lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
        try:
            lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym)
            if lim_evaluated is not None and lim_evaluated.is_number:
                if lim_evaluated < 1:
                    return S.true
                if lim_evaluated > 1:
                    return S.false
        except NotImplementedError:
            pass

        ### ------------- alternating series test ----------- ###
        dict_val = sequence_term.match((-1)**(sym + p)*q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true


        ### ------------- integral test -------------- ###
        check_interval = None
        maxima = solveset(sequence_term.diff(sym), sym, interval)
        if not maxima:
            check_interval = interval
        elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
            check_interval = Interval(maxima.sup, interval.sup)
        if (check_interval is not None and
            (is_decreasing(sequence_term, check_interval) or
            is_decreasing(-sequence_term, check_interval))):
                integral_val = Integral(
                    sequence_term, (sym, lower_limit, upper_limit))
                try:
                    integral_val_evaluated = integral_val.doit()
                    if integral_val_evaluated.is_number:
                        return S(integral_val_evaluated.is_finite)
                except NotImplementedError:
                    pass

        ### ----- Dirichlet and bounded times convergent tests ----- ###
        # TODO
        #
        # Dirichlet_test
        # https://en.wikipedia.org/wiki/Dirichlet%27s_test
        #
        # Bounded times convergent test
        # It is based on comparison theorems for series.
        # In particular, if the general term of a series can
        # be written as a product of two terms a_n and b_n
        # and if a_n is bounded and if Sum(b_n) is absolutely
        # convergent, then the original series Sum(a_n * b_n)
        # is absolutely convergent and so convergent.
        #
        # The following code can grows like 2**n where n is the
        # number of args in order.expr
        # Possibly combined with the potentially slow checks
        # inside the loop, could make this test extremely slow
        # for larger summation expressions.

        if order.expr.is_Mul:
            args = order.expr.args
            argset = set(args)

            ### -------------- Dirichlet tests -------------- ###
            m = Dummy('m', integer=True)
            def _dirichlet_test(g_n):
                try:
                    ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m)
                    if ing_val is not None and ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            ### -------- bounded times convergent test ---------###
            def _bounded_convergent_test(g1_n, g2_n):
                try:
                    lim_val = limit_seq(g1_n, sym)
                    if lim_val is not None and (lim_val.is_finite or (
                        isinstance(lim_val, AccumulationBounds)
                        and (lim_val.max - lim_val.min).is_finite)):
                            if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent():
                                return S.true
                except NotImplementedError:
                    pass

            for n in range(1, len(argset)):
                for a_tuple in itertools.combinations(args, n):
                    b_set = argset - set(a_tuple)
                    a_n = Mul(*a_tuple)
                    b_n = Mul(*b_set)

                    if is_decreasing(a_n, interval):
                        dirich = _dirichlet_test(b_n)
                        if dirich is not None:
                            return dirich

                    bc_test = _bounded_convergent_test(a_n, b_n)
                    if bc_test is not None:
                        return bc_test

        _sym = self.limits[0][0]
        sequence_term = sequence_term.xreplace({sym: _sym})
        raise NotImplementedError("The algorithm to find the Sum convergence of %s "
                                  "is not yet implemented" % (sequence_term))
Beispiel #8
0
    def is_convergent(self):
        r"""Checks for the convergence of a Sum.

        We divide the study of convergence of infinite sums and products in
        two parts.

        First Part:
        One part is the question whether all the terms are well defined, i.e.,
        they are finite in a sum and also non-zero in a product. Zero
        is the analogy of (minus) infinity in products as
        :math:`e^{-\infty} = 0`.

        Second Part:
        The second part is the question of convergence after infinities,
        and zeros in products, have been omitted assuming that their number
        is finite. This means that we only consider the tail of the sum or
        product, starting from some point after which all terms are well
        defined.

        For example, in a sum of the form:

        .. math::

            \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}

        where a and b are numbers. The routine will return true, even if there
        are infinities in the term sequence (at most two). An analogous
        product would be:

        .. math::

            \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}

        This is how convergence is interpreted. It is concerned with what
        happens at the limit. Finding the bad terms is another independent
        matter.

        Note: It is responsibility of user to see that the sum or product
        is well defined.

        There are various tests employed to check the convergence like
        divergence test, root test, integral test, alternating series test,
        comparison tests, Dirichlet tests. It returns true if Sum is convergent
        and false if divergent and NotImplementedError if it can not be checked.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolutely_convergent()

        Product.is_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError("convergence checking for more than one symbol "
                                      "containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity
        # and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        sym_ = Dummy(sym.name, integer=True, positive=True)
        sequence_term = sequence_term.xreplace({sym: sym_})
        sym = sym_

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func, cond in sequence_term.args:
                # see if it represents something going to oo
                if cond == True or cond.as_set().sup is S.Infinity:
                    s = Sum(func, (sym, lower_limit, upper_limit))
                    return s.is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(sequence_term, sym, upper_limit)
            if lim_val.is_number and lim_val is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        try:
            lim_val_abs = limit(abs(sequence_term), sym, upper_limit)
            if lim_val_abs.is_number and lim_val_abs is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### ----------- ratio test ---------------- ###
        next_sequence_term = sequence_term.xreplace({sym: sym + 1})
        ratio = combsimp(powsimp(next_sequence_term/sequence_term))
        lim_ratio = limit(ratio, sym, upper_limit)
        if lim_ratio.is_number:
            if abs(lim_ratio) > 1:
                return S.false
            if abs(lim_ratio) < 1:
                return S.true

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] >= -1:
                return S.false

        p2_series_test = order.expr.match((1/sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] <= 1:
                return S.false

        ### ------------- Limit comparison test -----------###
        # (1/n) comparison
        try:
            lim_comp = limit(sym*sequence_term, sym, S.Infinity)
            if lim_comp.is_number and lim_comp > 0:
                    return S.false
        except NotImplementedError:
            pass

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        dict_val = sequence_term.match((-1)**(sym + p)*q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1/(log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1/(sym*(log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1/(sym*(log(sym)*log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1/(sym**p*log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        maxima = solveset(sequence_term.diff(sym), sym, interval)
        if not maxima:
            check_interval = interval
        elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
            check_interval = Interval(maxima.sup, interval.sup)
            if (
                    is_decreasing(sequence_term, check_interval) or
                    is_decreasing(-sequence_term, check_interval)):
                integral_val = Integral(
                    sequence_term, (sym, lower_limit, upper_limit))
                try:
                    integral_val_evaluated = integral_val.doit()
                    if integral_val_evaluated.is_number:
                        return S(integral_val_evaluated.is_finite)
                except NotImplementedError:
                    pass

        ### -------------- Dirichlet tests -------------- ###
        if order.expr.is_Mul:
            a_n, b_n = order.expr.args[0], order.expr.args[1]
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            if is_decreasing(a_n, interval):
                dirich1 = _dirichlet_test(b_n)
                if dirich1 is not None:
                    return dirich1

            if is_decreasing(b_n, interval):
                dirich2 = _dirichlet_test(a_n)
                if dirich2 is not None:
                    return dirich2

        _sym = self.limits[0][0]
        sequence_term = sequence_term.xreplace({sym: _sym})
        raise NotImplementedError("The algorithm to find the Sum convergence of %s "
                                  "is not yet implemented" % (sequence_term))
Beispiel #9
0
    def is_convergent(self):
        r"""Checks for the convergence of a Sum.

        We divide the study of convergence of infinite sums and products in
        two parts.

        First Part:
        One part is the question whether all the terms are well defined, i.e.,
        they are finite in a sum and also non-zero in a product. Zero
        is the analogy of (minus) infinity in products as :math:`e^{-\infty} = 0`.

        Second Part:
        The second part is the question of convergence after infinities,
        and zeros in products, have been omitted assuming that their number
        is finite. This means that we only consider the tail of the sum or
        product, starting from some point after which all terms are well
        defined.

        For example, in a sum of the form:

        .. math::

            \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}

        where a and b are numbers. The routine will return true, even if there
        are infinities in the term sequence (at most two). An analogous
        product would be:

        .. math::

            \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}

        This is how convergence is interpreted. It is concerned with what
        happens at the limit. Finding the bad terms is another independent
        matter.

        Note: It is responsibility of user to see that the sum or product
        is well defined.

        There are various tests employed to check the convergence like
        divergence test, root test, integral test, alternating series test,
        comparison tests, Dirichlet tests. It returns true if Sum is convergent
        and false if divergent and NotImplementedError if it can not be checked.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolutely_convergent()

        Product.is_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError(
                "convergence checking for more than one symbol "
                "containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity
        # and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func_cond in sequence_term.args:
                if func_cond[1].func is Ge or func_cond[
                        1].func is Gt or func_cond[1] == True:
                    return Sum(
                        func_cond[0],
                        (sym, lower_limit, upper_limit)).is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(sequence_term, sym, upper_limit)
            if lim_val.is_number and lim_val is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        try:
            lim_val_abs = limit(abs(sequence_term), sym, upper_limit)
            if lim_val_abs.is_number and lim_val_abs is not S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] > -1:
                return S.false

        p2_series_test = order.expr.match((1 / sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] < 1:
                return S.false

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1 / sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        dict_val = sequence_term.match((-1)**(sym + p) * q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1 / (log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1 / (sym * (log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1 / (sym *
                                               (log(sym) * log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1 / (sym**p * log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        if is_decreasing(sequence_term, interval):
            integral_val = Integral(sequence_term,
                                    (sym, lower_limit, upper_limit))
            try:
                integral_val_evaluated = integral_val.doit()
                if integral_val_evaluated.is_number:
                    return S(integral_val_evaluated.is_finite)
            except NotImplementedError:
                pass

        ### -------------- Dirichlet tests -------------- ###
        if order.expr.is_Mul:
            a_n, b_n = order.expr.args[0], order.expr.args[1]
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(
                        Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            if is_decreasing(a_n, interval):
                dirich1 = _dirichlet_test(b_n)
                if dirich1 is not None:
                    return dirich1

            if is_decreasing(b_n, interval):
                dirich2 = _dirichlet_test(a_n)
                if dirich2 is not None:
                    return dirich2

        raise NotImplementedError(
            "The algorithm to find the Sum convergence of %s "
            "is not yet implemented" % (sequence_term))
Beispiel #10
0
def check_constraints(model,
                      constraints,
                      intervals,
                      characteristic_vals=None,
                      verbose=0):
    """WIP function for Tc project.
    UseS Sympy to check for singularities and other limits."""
    intervals = dict(intervals)
    feature_set = list(constraints.keys())
    if characteristic_vals is None:
        characteristic_vals = {
            feature: i / 10
            for i, feature in enumerate(feature_set)
        }
    for feature in feature_set:
        if feature not in intervals.keys():
            intervals[feature] = sympy.Reals
            continue
        interval_min, interval_max = intervals[feature]
        if interval_min == "-oo" or interval_min == -np.inf:
            interval_min = -oo
        elif interval_max == "oo" or interval_max == np.inf:
            interval_max = oo
        interval = Interval(interval_min, interval_max)
        intervals[feature] = interval

    symbol_dict = {
        k: v
        for k, v in zip(
            feature_set,
            sympy.symbols(
                feature_set, positive=True, finite=True, infinite=False))
    }
    expr = parse_expr(model.replace('^', '**'), local_dict=symbol_dict)

    passed = True
    checks = {k: {} for k in constraints.keys()}
    for feature, symbol in symbol_dict.items():
        symbol_set = list(symbol_dict.values())
        variable = symbol_set.pop(symbol_set.index(symbol))
        interval = intervals[feature]

        univariate_expr = expr.subs([(symbol, characteristic_vals[str(symbol)])
                                     for symbol in symbol_set])
        if verbose > 1:
            print(univariate_expr)

        if constraints[feature].get('increasing', None) is not None:
            try:
                increasing = is_increasing(univariate_expr, interval=interval)
            except TypeError:
                increasing = False
            if increasing is None:  # bug?
                increasing = False
            checks[feature]['increasing'] = increasing
            if increasing != constraints[feature]['increasing']:
                passed = False

        if constraints[feature].get('decreasing', None) is not None:
            try:
                decreasing = is_decreasing(univariate_expr, interval=interval)
            except TypeError:
                decreasing = False
            if decreasing is None:  # bug?
                decreasing = False
            checks[feature]['decreasing'] = decreasing
            if decreasing != constraints[feature]['decreasing']:
                passed = False

        if constraints[feature].get('monotonic', None) is not None:
            try:
                monotonic = is_monotonic(univariate_expr, interval=interval)
            except TypeError:
                monotonic = False
            checks[feature]['monotonic'] = monotonic
            if monotonic != constraints[feature]['monotonic']:
                passed = False

        if constraints[feature].get('singularities', None) is not None:
            try:
                singularity_set = singularities(expr,
                                                variable,
                                                domain=interval)
            except TypeError:
                singularity_set = sympy.EmptySet
            checks[feature]['singularities'] = singularity_set
            # has_singularities = singularity_set is not sympy.EmptySet
            if singularity_set != constraints[feature]['singularities']:
                passed = False

        if constraints[feature].get('zero limit', None) is not None:
            try:
                zero_limit = sympy.limit(expr, variable, 0)
            except TypeError:
                zero_limit = None
            checks[feature]['zero limit'] = zero_limit
            if zero_limit != constraints[feature]['zero limit']:
                passed = False
    if verbose == 0:
        return passed
    else:
        return checks, passed
Beispiel #11
0
def test_is_strictly_decreasing():
    assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
    assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
    assert is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) is False
    assert is_decreasing(-x**2, Interval(-oo, 0)) is False
Beispiel #12
0
    def is_convergent(self):
        """
        Convergence tests are used for checking the convergence of
        a series. There are various tests employed to check the convergence,
        returns true if convergent and false if divergent and NotImplementedError
        if can not be checked. Like divergence test, root test, integral test,
        alternating series test, comparison tests, Dirichlet tests.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import Interval, factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolute_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError(
                "convergence checking for more that one symbol \
                                        containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func_cond in sequence_term.args:
                if func_cond[1].func is Ge or func_cond[
                        1].func is Gt or func_cond[1] == True:
                    return Sum(
                        func_cond[0],
                        (sym, lower_limit, upper_limit)).is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(abs(sequence_term), sym, upper_limit)
            if lim_val.is_number and lim_val != S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] > -1:
                return S.false

        p2_series_test = order.expr.match((1 / sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] < 1:
                return S.false

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1 / sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        d = symbols('d', cls=Dummy)
        dict_val = sequence_term.match((-1)**(sym + p) * q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1 / (log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1 / (sym * (log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1 / (sym *
                                               (log(sym) * log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1 / (sym**p * log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        if is_decreasing(sequence_term, interval):
            integral_val = Integral(sequence_term,
                                    (sym, lower_limit, upper_limit))
            try:
                integral_val_evaluated = integral_val.doit()
                if integral_val_evaluated.is_number:
                    return S(integral_val_evaluated.is_finite)
            except NotImplementedError:
                pass

        ### -------------- Dirichlet tests -------------- ###
        if order.expr.is_Mul:
            a_n, b_n = order.expr.args[0], order.expr.args[1]
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(
                        Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            if is_decreasing(a_n, interval):
                dirich1 = _dirichlet_test(b_n)
                if dirich1 is not None:
                    return dirich1

            if is_decreasing(b_n, interval):
                dirich2 = _dirichlet_test(a_n)
                if dirich2 is not None:
                    return dirich2

        raise NotImplementedError(
            "The algorithm to find the convergence of %s "
            "is not yet implemented" % (sequence_term))
Beispiel #13
0
    def is_convergent(self):
        """
        Convergence tests are used for checking the convergence of
        a series. There are various tests employed to check the convergence,
        returns true if convergent and false if divergent and NotImplementedError
        if can not be checked. Like divergence test, root test, integral test,
        alternating series test, comparison tests, Dirichlet tests.

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Convergence_tests

        Examples
        ========

        >>> from sympy import Interval, factorial, S, Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
        True
        >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
        False
        >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
        False
        >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
        True

        See Also
        ========

        Sum.is_absolute_convergent()
        """
        from sympy import Interval, Integral, Limit, log, symbols, Ge, Gt, simplify
        p, q = symbols('p q', cls=Wild)

        sym = self.limits[0][0]
        lower_limit = self.limits[0][1]
        upper_limit = self.limits[0][2]
        sequence_term = self.function

        if len(sequence_term.free_symbols) > 1:
            raise NotImplementedError("convergence checking for more that one symbol \
                                        containing series is not handled")

        if lower_limit.is_finite and upper_limit.is_finite:
            return S.true

        # transform sym -> -sym and swap the upper_limit = S.Infinity and lower_limit = - upper_limit
        if lower_limit is S.NegativeInfinity:
            if upper_limit is S.Infinity:
                return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
                        Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
            sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
            lower_limit = -upper_limit
            upper_limit = S.Infinity

        interval = Interval(lower_limit, upper_limit)

        # Piecewise function handle
        if sequence_term.is_Piecewise:
            for func_cond in sequence_term.args:
                if func_cond[1].func is Ge or func_cond[1].func is Gt or func_cond[1] == True:
                    return Sum(func_cond[0], (sym, lower_limit, upper_limit)).is_convergent()
            return S.true

        ###  -------- Divergence test ----------- ###
        try:
            lim_val = limit(abs(sequence_term), sym, upper_limit)
            if lim_val.is_number and lim_val != S.Zero:
                return S.false
        except NotImplementedError:
            pass

        order = O(sequence_term, (sym, S.Infinity))

        ### --------- p-series test (1/n**p) ---------- ###
        p1_series_test = order.expr.match(sym**p)
        if p1_series_test is not None:
            if p1_series_test[p] < -1:
                return S.true
            if p1_series_test[p] > -1:
                return S.false

        p2_series_test = order.expr.match((1/sym)**p)
        if p2_series_test is not None:
            if p2_series_test[p] > 1:
                return S.true
            if p2_series_test[p] < 1:
                return S.false

        ### ----------- root test ---------------- ###
        lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
        lim_evaluated = lim.doit()
        if lim_evaluated.is_number:
            if lim_evaluated < 1:
                return S.true
            if lim_evaluated > 1:
                return S.false

        ### ------------- alternating series test ----------- ###
        d = symbols('d', cls=Dummy)
        dict_val = sequence_term.match((-1)**(sym + p)*q)
        if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
            return S.true

        ### ------------- comparison test ------------- ###
        # (1/log(n)**p) comparison
        log_test = order.expr.match(1/(log(sym)**p))
        if log_test is not None:
            return S.false

        # (1/(n*log(n)**p)) comparison
        log_n_test = order.expr.match(1/(sym*(log(sym))**p))
        if log_n_test is not None:
            if log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n*log(n)*log(log(n))*p)) comparison
        log_log_n_test = order.expr.match(1/(sym*(log(sym)*log(log(sym))**p)))
        if log_log_n_test is not None:
            if log_log_n_test[p] > 1:
                return S.true
            return S.false

        # (1/(n**p*log(n))) comparison
        n_log_test = order.expr.match(1/(sym**p*log(sym)))
        if n_log_test is not None:
            if n_log_test[p] > 1:
                return S.true
            return S.false

        ### ------------- integral test -------------- ###
        if is_decreasing(sequence_term, interval):
            integral_val = Integral(sequence_term, (sym, lower_limit, upper_limit))
            try:
                integral_val_evaluated = integral_val.doit()
                if integral_val_evaluated.is_number:
                    return S(integral_val_evaluated.is_finite)
            except NotImplementedError:
                pass

        ### -------------- Dirichlet tests -------------- ###
        if order.expr.is_Mul:
            a_n, b_n = order.expr.args[0], order.expr.args[1]
            m = Dummy('m', integer=True)

            def _dirichlet_test(g_n):
                try:
                    ing_val = limit(Sum(g_n, (sym, interval.inf, m)).doit(), m, S.Infinity)
                    if ing_val.is_finite:
                        return S.true
                except NotImplementedError:
                    pass

            if is_decreasing(a_n, interval):
                dirich1 = _dirichlet_test(b_n)
                if dirich1 is not None:
                    return dirich1

            if is_decreasing(b_n, interval):
                dirich2 = _dirichlet_test(a_n)
                if dirich2 is not None:
                    return dirich2

        raise NotImplementedError("The algorithm to find the convergence of %s "
                                    "is not yet implemented" % (sequence_term))