a
    RG5d                     @   sJ  d dl mZ d dlmZ d dlmZ ddlmZ ddl	m
Z
 ddlmZ d dlmZ d d	lmZ d dlmZ d d
lmZmZ d dlmZ d dlmZmZ d dlmZ d dlmZ d dlmZ d dl m!Z!m"Z"m#Z#m$Z$ d dl%m&Z& d dl'm(Z(m)Z) d dl*m+Z+m,Z, d dl-m.Z. d dl/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z?m@Z@ d dlAmBZBmCZCmDZD d dlEmFZF d dlGmHZH d d lImJZJ d d!lKmLZL d d"lMmNZNmOZO d d#lPmQZQ d d$lRZRG d%d& d&e
eZSd'd( ZTd)d* ZUd+d, ZVd-d. ZWd/d0 ZXd1d2 ZYd3d4 ZZd5d6 Z[d7d8 Z\d9d: Z]d;d< Z^d$S )=    )Tuple)is_decreasing)AccumulationBounds   )ExprWithIntLimits)AddWithLimits)
gosper_sum)Expr)Add)
Derivativeexpand)Mul)Float_illegal)Eq)S)ordered)DummyWildSymbolsymbols)	factorial)	bernoulliharmonic)explog)	Piecewise)cotcsc)hyper)KroneckerDelta)zeta)Integral)And)apart)PolynomialErrorPolificationFailed)parallel_poly_from_exprPolyfactor)together)	limit_seq)Oresidue)	FiniteSetInterval)siftNc                   @   s   e Zd ZU dZdZeeeeef  ed< dd Z	dd Z
dd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd'd d!Zd"d# Zd$d% Zd&S )(SumaN  
    Represents unevaluated summation.

    Explanation
    ===========

    ``Sum`` represents a finite or infinite series, with the first argument
    being the general form of terms in the series, and the second argument
    being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking
    all integer values from ``start`` through ``end``. In accordance with
    long-standing mathematical convention, the end term is included in the
    summation.

    Finite sums
    ===========

    For finite sums (and sums with symbolic limits assumed to be finite) we
    follow the summation convention described by Karr [1], especially
    definition 3 of section 1.4. The sum:

    .. math::

        \sum_{m \leq i < n} f(i)

    has *the obvious meaning* for `m < n`, namely:

    .. math::

        \sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1)

    with the upper limit value `f(n)` excluded. The sum over an empty set is
    zero if and only if `m = n`:

    .. math::

        \sum_{m \leq i < n} f(i) = 0  \quad \mathrm{for} \quad  m = n

    Finally, for all other sums over empty sets we assume the following
    definition:

    .. math::

        \sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i)  \quad \mathrm{for} \quad  m > n

    It is important to note that Karr defines all sums with the upper
    limit being exclusive. This is in contrast to the usual mathematical notation,
    but does not affect the summation convention. Indeed we have:

    .. math::

        \sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i)

    where the difference in notation is intentional to emphasize the meaning,
    with limits typeset on the top being inclusive.

    Examples
    ========

    >>> from sympy.abc import i, k, m, n, x
    >>> from sympy import Sum, factorial, oo, IndexedBase, Function
    >>> Sum(k, (k, 1, m))
    Sum(k, (k, 1, m))
    >>> Sum(k, (k, 1, m)).doit()
    m**2/2 + m/2
    >>> Sum(k**2, (k, 1, m))
    Sum(k**2, (k, 1, m))
    >>> Sum(k**2, (k, 1, m)).doit()
    m**3/3 + m**2/2 + m/6
    >>> Sum(x**k, (k, 0, oo))
    Sum(x**k, (k, 0, oo))
    >>> Sum(x**k, (k, 0, oo)).doit()
    Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True))
    >>> Sum(x**k/factorial(k), (k, 0, oo)).doit()
    exp(x)

    Here are examples to do summation with symbolic indices.  You
    can use either Function of IndexedBase classes:

    >>> f = Function('f')
    >>> Sum(f(n), (n, 0, 3)).doit()
    f(0) + f(1) + f(2) + f(3)
    >>> Sum(f(n), (n, 0, oo)).doit()
    Sum(f(n), (n, 0, oo))
    >>> f = IndexedBase('f')
    >>> Sum(f[n]**2, (n, 0, 3)).doit()
    f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2

    An example showing that the symbolic result of a summation is still
    valid for seemingly nonsensical values of the limits. Then the Karr
    convention allows us to give a perfectly valid interpretation to
    those sums by interchanging the limits according to the above rules:

    >>> S = Sum(i, (i, 1, n)).doit()
    >>> S
    n**2/2 + n/2
    >>> S.subs(n, -4)
    6
    >>> Sum(i, (i, 1, -4)).doit()
    6
    >>> Sum(-i, (i, -3, 0)).doit()
    6

    An explicit example of the Karr summation convention:

    >>> S1 = Sum(i**2, (i, m, m+n-1)).doit()
    >>> S1
    m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6
    >>> S2 = Sum(i**2, (i, m+n, m-1)).doit()
    >>> S2
    -m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6
    >>> S1 + S2
    0
    >>> S3 = Sum(i, (i, m, m-1)).doit()
    >>> S3
    0

    See Also
    ========

    summation
    Product, sympy.concrete.products.product

    References
    ==========

    .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
           Volume 28 Issue 2, April 1981, Pages 305-350
           http://dl.acm.org/citation.cfm?doid=322248.322255
    .. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation
    .. [3] https://en.wikipedia.org/wiki/Empty_sum
     limitsc                 O   sH   t j| |g|R i |}t|ds(|S tdd |jD rDtd|S )Nr4   c                 s   s"   | ]}t |d kpd|v V  qdS )   N)len).0lr3   r3   U/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/concrete/summations.py	<genexpr>       zSum.__new__.<locals>.<genexpr>z/Sum requires values for lower and upper bounds.)r   __new__hasattranyr4   
ValueError)clsfunctionr   assumptionsobjr3   r3   r9   r<      s    
zSum.__new__c                 C   s   | j js| jrdS d S NT)rA   is_zerohas_empty_sequenceselfr3   r3   r9   _eval_is_zero   s    zSum._eval_is_zeroc                 C   s   | j r
dS | jjS rD   )rF   rA   is_extended_realrG   r3   r3   r9   _eval_is_extended_real   s    zSum._eval_is_extended_realc                 C   s   | j r| jdu r| jjS d S NF)has_finite_limitshas_reversed_limitsrA   is_positiverG   r3   r3   r9   _eval_is_positive   s    zSum._eval_is_positivec                 C   s   | j r| jdu r| jjS d S rL   )rM   rN   rA   is_negativerG   r3   r3   r9   _eval_is_negative   s    zSum._eval_is_negativec                 C   s   | j r| jjrdS d S rD   )rM   rA   	is_finiterG   r3   r3   r9   _eval_is_finite   s    zSum._eval_is_finitec                    s  | ddr | jjf i |}n| j}i }| jD ]}t|}|r0|||d < q0|rdd | D  | |jf i |}t|trt fdd|D }n|d ur| }n| }|S | jj	r| 
 }| |kr| S t| S t| jD ]\}}	|	\}
}}|| }|dkrtj  S |jr@|jr@|d	 |d	  }}| }t||
||f}|d u r|| jkr| ||
||f}|d ur|  S |   S | j|g| j|d  R    S |}q| ddrt|ts|jf i |S |S )
NdeepTr   c                 S   s   i | ]\}}||qS r3   r3   )r7   kvr3   r3   r9   
<dictcomp>   r;   zSum.doit.<locals>.<dictcomp>c                    s   g | ]}|  qS r3   xreplacer7   iundor3   r9   
<listcomp>   r;   zSum.doit.<locals>.<listcomp>r   )getrA   doitr4   )_dummy_with_inherited_properties_concreteitemsrZ   
isinstancetuple	is_Matrixr   _eval_matrix_sum	enumerater   Zero
is_integerrQ   eval_sumeval_zeta_functionfuncr   )rH   hintsfrepsxabddidexpandednlimitr\   abdifnewfZzeta_functionr3   r]   r9   rb      sV    






 zSum.doitc                 C   s   |\}}}t d|gdt d|gdt d|gd  }}}||| | |  }	|	dur|tju rd|	| |	|   }
|	| }|	| |	|  | }t|
t|| t|dk|dkf| dfS dS )	z
        Check whether the function matches with the zeta function.
        If it matches, then return a `Piecewise` expression because
        zeta function does not converge unless `s > 1` and `q > 0`
        wexcludeyzNr   r   T)r   matchr   Infinityr   r!   r#   )rH   rp   r4   r\   rx   ry   r|   r   r   resultcoeffsqr3   r3   r9   rm     s    
.zSum.eval_zeta_functionc           
      C   s   t |tr|| jvrtjS | jt| j }}|d}|rL| j	|g|R  }|\}}}||jv sj||jv rndS t
||dd}| 	||}	|	S )a  
        Differentiate wrt x as long as x is not in the free symbols of any of
        the upper or lower limits.

        Explanation
        ===========

        Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a`
        since the value of the sum is discontinuous in `a`. In a case
        involving a limit variable, the unevaluated derivative is returned.
        r`   NT)evaluate)re   r   free_symbolsr   rj   rA   listr4   poprn   r   )
rH   xrp   r4   rw   _rx   ry   dfrvr3   r3   r9   _eval_derivative  s    

zSum._eval_derivativec                 C   sf   | j d \}}}|||| }t| j dkr:| j d }n| j| j d d  }t|||d |f S )Nr`      r   r   )argssubsr6   rn   r2   rb   )rH   rv   steprV   r   upperZ	new_upperrp   r3   r3   r9   _eval_difference_deltaB  s    zSum._eval_difference_deltac                 K   s   t t| j}g }g }|D ]h}|trztt|}g }|D ](}t|tr^||	  q@|| q@|t|  q|| qddl
m}	m}
 t |
|g|R  }|	|| jdS )Nr   )
factor_sumsum_combine)r4   )r
   	make_argsr   rA   hasr2   r   re   append_eval_simplifysympy.simplify.simplifyr   r   r4   )rH   kwargstermsZs_tZo_ttermZsubtermsZ	out_termsZsubtermr   r   r   r3   r3   r9   r   M  s     

zSum._eval_simplifyc           )         s  t dtd\}}}| jd d | jd d | jd d | j }t|jdkr\tdjrnjrnt	j
S t	ju rڈt	ju rt|dt	jf ot|t	jdf S ddlm} || i} t	jtjddd	}||i}|t |jr^|jD ]B\}}|dks8| jt	ju rt|f}	|	   S qt	j
S z,t|}
|
d
ur|
jdu rt	jW S W n ty   Y n0 z0tt|}|d
ur|jdu rt	jW S W n ty   Y n0 t|t	jf}|j| }|d
ur8|| dk r$t	j
S || dkr8t	jS |jd| td |  ttd  |   p|jd| td  |  ttd  |   }|d
ur"|| dks|| dkr|| dks|| ||   krdkrn n|| dkrt	j
S t	jS z6t| }|d
urV|j rV|dkrVt	jW S W n tyl   Y n0 |d i}ddl!m"} ddl#m$} |||| }zLt|}|d
ur|j rt|dkrt	jW S t|dk rt	j
W S W n ty   d
}Y n0 |dkr||%d  d  }|& }zDt|}
|
d
ur~|
j r~|
dkrlt	j
W S |
dk r~t	jW S W n ty   Y n0 zPtt|d  }|d
ur|j r|dk rt	j
W S |dkrt	jW S W n ty   Y n0 |t	j'|  | }|| (s:t)||  r:t	j
S d
}ddl*m+} ||, }|sh }n$t-|t.r|jj rt|j j}|d
urt)||st)| |rt/|f}z |0 }|j rt	|jW S W n ty   Y n0 |jj1r|jj}t2|}tddd fdd}fdd} t3dt|D ]}!t45||!D ]l}"|t2|" }#t6|" }$t6|# }%t)|$ r||%}&|&d
ur|&    S | |$|%}'|'d
urZ|'    S qZqJ| jd d }(||(i}td| d
S )ah	  
        Checks for the convergence of a Sum.

        Explanation
        ===========

        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 cannot 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()
        sympy.concrete.products.Product.is_convergent()
        zp q r)r@   r   r   r   zNconvergence checking for more than one symbol containing series is not handledsimplifyTintegerpositiveNFr`   combsimp)powsimp)solvesetm)r   c                    sN   z6t t|  jf }|d ur4|jr4tjW S W n tyH   Y n0 d S N)r+   r2   infrb   rS   r   trueNotImplementedError)Zg_nZing_val)intervalr   symr3   r9   _dirichlet_testk  s    z*Sum.is_convergent.<locals>._dirichlet_testc                    sh   zPt | }|d urN|js2t|trN|j|j jrNt| f rNtj	W S W n t
yb   Y n0 d S r   )r+   rS   re   r   maxminr2   is_absolutely_convergentr   r   r   )Zg1_nZg2_nlim_val)lower_limitr   upper_limitr3   r9   _bounded_convergent_testt  s    
z3Sum.is_convergent.<locals>._bounded_convergent_testzFThe algorithm to find the Sum convergence of %s is not yet implemented)7r   r   r4   rA   r   r6   r   r   rS   r   r   NegativeInfinityr   r2   is_convergentr   rZ   r   namer0   is_Piecewiser   as_setsupr+   rE   falseabsr,   exprr   r   	is_numbersympy.simplify.combsimpr   sympy.simplify.powsimpr   r   	gammasimpNegativeOner   r   sympy.solvers.solvesetr   diffre   r/   r"   rb   is_Mulsetrange	itertoolscombinationsr   ))rH   pr   rsequence_termr   Zsym_rn   condr   r   Zlim_val_absorderZp_series_testZ
n_log_testZlim_compZnext_sequence_termr   r   ratioZ	lim_ratioZtest_valZlim_evaluatedZdict_valZcheck_intervalr   maximaZintegral_valZintegral_val_evaluatedr   argsetr   r   rv   Za_tupleZb_seta_nb_nZdirichZbc_test_symr3   )r   r   r   r   r   r9   r   o  s6   J





<:












 



	


zSum.is_convergentc                 C   s   t t| j| j S )az  
        Checks for the absolute convergence of an infinite series.

        Same as checking convergence of absolute value of sequence_term of
        an infinite series.

        References
        ==========

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

        Examples
        ========

        >>> from sympy import Sum, Symbol, oo
        >>> n = Symbol('n', integer=True)
        >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent()
        False
        >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent()
        True

        See Also
        ========

        Sum.is_convergent()
        )r2   r   rA   r4   r   rG   r3   r3   r9   r     s    zSum.is_absolutely_convergentr   Tc                    s  t |}t |}| jt| jdkr,td| jd \  kdkrx  dkr`tjtjfS d  d    tj}|rjr jrt|  d }|r	rt
 fddt|D  }n }|rt|d|k }|dkr
|t|fS |dks|tjfS |}td|D ]L} | }t|d|k rn|dkrn|t|f  S ||7 }q,  d |kr|tjfS  |7  td	}	t|	|	 f}
|r|
 }
||
7 } fd
d}|\}}|| d }}td|d D ]}||\}}td| td|  ||  }||krT q|r|r|d}|tju rtjtjf  S t||k r q||7 }|jddd}q|| t|fS )a  
        Return an Euler-Maclaurin approximation of self, where m is the
        number of leading terms to sum directly and n is the number of
        terms in the tail.

        With m = n = 0, this is simply the corresponding integral
        plus a first-order endpoint correction.

        Returns (s, e) where s is the Euler-Maclaurin approximation
        and e is the estimated error (taken to be the magnitude of
        the first omitted term in the tail):

            >>> from sympy.abc import k, a, b
            >>> from sympy import Sum
            >>> Sum(1/k, (k, 2, 5)).doit().evalf()
            1.28333333333333
            >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin()
            >>> s
            -log(2) + 7/20 + log(5)
            >>> from sympy import sstr
            >>> print(sstr((s.evalf(), e.evalf()), full_prec=True))
            (1.26629073187415, 0.0175000000000000)

        The endpoints may be symbolic:

            >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin()
            >>> s
            -log(a) + log(b) + 1/(2*b) + 1/(2*a)
            >>> e
            Abs(1/(12*b**2) - 1/(12*a**2))

        If the function is a polynomial of degree at most 2n+1, the
        Euler-Maclaurin formula becomes exact (and e = 0 is returned):

            >>> Sum(k, (k, 2, b)).euler_maclaurin()
            (b**2/2 + b/2 - 1, 0)
            >>> Sum(k, (k, 2, b)).doit()
            b**2/2 + b/2 - 1

        With a nonzero eps specified, the summation is ended
        as soon as the remainder term is less than the epsilon.
        r   zMore than 1 limitr   Tc                    s   g | ]}  | qS r3   r   )r7   rV   )rx   rp   r\   r3   r9   r_     r;   z'Sum.euler_maclaurin.<locals>.<listcomp>r5   Fr   c                    s2   t ju r|  dfS |  | fS )Nr   )r   r   r   )r   )rx   ry   r\   r3   r9   fpoint  s    
z#Sum.euler_maclaurin.<locals>.fpointr   r   )intrA   r6   r4   r?   r   rj   
is_Integerr   is_polynomialr
   r   r   r   evalfr   r"   rb   r   r   r   NaN)rH   r   rv   epseval_integralr   r   testrV   r   Ir   fafbZitermggagbZ
term_evalfr3   )rx   ry   rp   r\   r9   euler_maclaurin  sp    + 




 

zSum.euler_maclaurinc           	      G   s   t |}t|D ] \}}t|ts| |||< qd}g }t| jD ]B\}}|}||v r|| }|d |d d |d d f}|| qDt|| j g|R  S )ab  
        Reverse the order of a limit in a Sum.

        Explanation
        ===========

        ``reverse_order(self, *indices)`` reverses some limits in the expression
        ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in
        the argument ``indices`` specify some indices whose limits get reversed.
        These selectors are either variable names or numerical indices counted
        starting from the inner-most limit tuple.

        Examples
        ========

        >>> from sympy import Sum
        >>> from sympy.abc import x, y, a, b, c, d

        >>> Sum(x, (x, 0, 3)).reverse_order(x)
        Sum(-x, (x, 4, -1))
        >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y)
        Sum(x*y, (x, 6, 0), (y, 7, -1))
        >>> Sum(x, (x, a, b)).reverse_order(x)
        Sum(-x, (x, b + 1, a - 1))
        >>> Sum(x, (x, a, b)).reverse_order(0)
        Sum(-x, (x, b + 1, a - 1))

        While one should prefer variable names when specifying which limits
        to reverse, the index counting notation comes in handy in case there
        are several symbols with the same name.

        >>> S = Sum(x**2, (x, a, b), (x, c, d))
        >>> S
        Sum(x**2, (x, a, b), (x, c, d))
        >>> S0 = S.reverse_order(0)
        >>> S0
        Sum(-x**2, (x, b + 1, a - 1), (x, c, d))
        >>> S1 = S0.reverse_order(1)
        >>> S1
        Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1))

        Of course we can mix both notations:

        >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
        Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
        >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
        Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))

        See Also
        ========

        sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit,
        sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder

        References
        ==========

        .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
               Volume 28 Issue 2, April 1981, Pages 305-350
               http://dl.acm.org/citation.cfm?doid=322248.322255
        r   r   r   )	r   ri   re   r   indexr4   r   r2   rA   )	rH   indices	l_indicesr\   indxer4   rw   r8   r3   r3   r9   reverse_order  s    >
zSum.reverse_orderc                 O   s4   ddl m} | jjr0t|t| jg| jR  S d S )Nr   )Product)sympy.concrete.productsr   rA   rJ   r   r   r4   )rH   r   r   r   r3   r3   r9   _eval_rewrite_as_Productj  s    zSum._eval_rewrite_as_ProductN)r   r   r   T)__name__
__module____qualname____doc__	__slots__tTupler   r	   __annotations__r<   rI   rK   rP   rR   rT   rb   rm   r   r   r   r   r   r   r   r   r3   r3   r3   r9   r2   (   s,   
 	=#"  &
kOr2   c                 O   s   t | g|R i |jddS )a  
    Compute the summation of f with respect to symbols.

    Explanation
    ===========

    The notation for symbols is similar to the notation used in Integral.
    summation(f, (i, a, b)) computes the sum of f with respect to i from a to b,
    i.e.,

    ::

                                    b
                                  ____
                                  \   `
        summation(f, (i, a, b)) =  )    f
                                  /___,
                                  i = a

    If it cannot compute the sum, it returns an unevaluated Sum object.
    Repeated sums can be computed by introducing additional symbols tuples::

    Examples
    ========

    >>> from sympy import summation, oo, symbols, log
    >>> i, n, m = symbols('i n m', integer=True)

    >>> summation(2*i - 1, (i, 1, n))
    n**2
    >>> summation(1/2**i, (i, 0, oo))
    2
    >>> summation(1/log(n)**n, (n, 2, oo))
    Sum(log(n)**(-n), (n, 2, oo))
    >>> summation(i, (i, 0, n), (n, 0, m))
    m**3/6 + m**2/2 + m/3

    >>> from sympy.abc import x
    >>> from sympy import factorial
    >>> summation(x**n/factorial(n), (n, 0, oo))
    exp(x)

    See Also
    ========

    Sum
    Product, sympy.concrete.products.product

    F)rU   )r2   rb   )rp   r   r   r3   r3   r9   	summationp  s    2r   c                    s,   |\t  fddt|D  S )a  
    Returns the direct summation of the terms of a telescopic sum

    Explanation
    ===========

    L is the term with lower index
    R is the term with higher index
    n difference between the indexes of L and R

    Examples
    ========

    >>> from sympy.concrete.summations import telescopic_direct
    >>> from sympy.abc import k, a, b
    >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b))
    -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a

    c                    s,   g | ]$}  |  |  qS r3   r   )r7   r   LRrx   ry   r\   r3   r9   r_     r;   z%telescopic_direct.<locals>.<listcomp>)r
   r   )r   r   rv   r4   r3   r   r9   telescopic_direct  s    
r   c           
         s:  |\}} j sj rdS td}  | }d}|rt||v rt|| }|jrp |  dkstd}|du rtd}z.ddlm}	 |	 |  |pg }W n ty   Y dS 0  fdd|D }t	|dkrdS |d }|dk rt
 t|||fS |dkr6t
 |||fS dS )	zi
    Tries to perform the summation using the telescopic property.

    Return None if not possible.
    NrV   r   r   solvec                    s0   g | ](}|j r |   jr|qS r3   )r   r   r   rE   )r7   sir   r   r\   r3   r9   r_     s   ztelescopic.<locals>.<listcomp>r   )is_Addr   r   r   r   r   sympy.solvers.solversr   r   r6   r   r   )
r   r   r4   rx   ry   rV   solr   r   r   r3   r  r9   
telescopic  s2    
"

r  c                    sj  |\ }}| j rtjS  | jvr0| || d  S ||krD|  |S t| trt fdd| jD sg }| jD ].}t	|j
|}|d u r d S |||jf qp| j| S | trddlm}m} | dd dd } || |d r|| |S || }	|	j}
|
r|	d	k rt|  ||fS t| tr.d S t|   ||f}|d urP|S |
rft|  ||fS d S )
Nr   c                 3   s   | ]} |j d  jv V  qdS )r   N)r   r   )r7   argr\   r3   r9   r:     r;   zeval_sum.<locals>.<genexpr>)deltasummation_has_simple_deltac                 S   s
   t | tS r   )re   r2   r   r3   r3   r9   <lambda>  r;   zeval_sum.<locals>.<lambda>c                 S   s   |   S r   )r)   r
  r3   r3   r9   r    r;   r   d   )rE   r   rj   r   r   re   r   r>   r   rl   r   r   r   rn   r   r    deltar  r	  replacer   eval_sum_directeval_sum_symbolicr   )rp   r4   rx   ry   newargsr  newexprr  r	  rz   definitevaluer3   r  r9   rl     sF    







rl   c                    s  |\ }|  }j r\}}|dkrZt| |f}|r|| }|tjur|S nX \}}	|st|	 |f}
|
r||
 S |	st| |f}|r||	 S ztW n ty   Y n0 j	r~\}}|dkr,t| |f}|r~||d  | }|tjur~|S nR \}}	t| |f}t|	 |f}d||fvr~|| }|tjur~|S t
 fddt|d D  S )z
    Evaluate expression directly, but perform some simple checks first
    to possibly result in a smaller expression and faster execution.
    r   r   Nc                    s   g | ]}  | qS r3   r   )r7   jrx   r   r\   r3   r9   r_   W  r;   z#eval_sum_direct.<locals>.<listcomp>)r   as_independentr  r   r   as_two_termsr   r$   r%   r  r
   r   )r   r4   ry   rz   	without_iwith_ir   r   r   r   sRsLlsumrsumr3   r  r9   r    sN    




r  c           &   	   C   s$  | }|\}}}|  |s(| || d  S | jr| |\}}|dkrpt||||f}|r|| }	|	tjur|	S nX|  \}
}|
 |st||||f}|r|
| S | |st|
|||f}|r|| S zt| |} W n ty   Y n0 | j	r|  \}
}t
|
||||f}|r|S | |\}}|dkrnt||||f}|r||| d  | }	|	tjur|	S nFt|
|||f}t||||f}d ||fvr|| }	|	tjur|	S td}| || }|d ur|| }|jr|dkrP|tju r|tjus|tju r$|tjur$tjS t|d |d t|d | |d   S |jr|dkr|dkrt|t|d  S t|t|t|d t| S | tjtjs| tjtjstd|gd}td|gd}td|gd}td	}|  || }|d ur|| || | }|d ur|| || |}|| |}||| ||d    d|  }	||| d  }t|t|tjf|	d
fS t| |||f}	t|	ttfrddlm } ddl!m"} |	j#t$|dd   j# }|t%|	}||j#@ } g }!t&| D ]|}"zZ|||"}|r>t|"|d ntj'}#|#dkrn|!(t)|j|#j* |+ |#f W  qW n t,y   Y qY n0 q|!(|	d
f t|! S |	d tjfvr|	S t-||||f}$|$d ur|$S t.||||f}	|	d ur|	S |/ }%|%|kr t|%|||fS d S )Nr   r   rv   r`   c1r}   c2c3wexpT)denomr   F)0r   r   r  r  r   r   r  r$   r%   r  r  r   r   r   r   r   r   r   r   r   r   r   updater   r   r   Oner   re   r   r
   sympy.simplify.radsimpr#  r  r   r   r   r*   r   r   r   r2   r   rb   r   eval_sum_hypereval_sum_residuer)   )&rp   r4   Zf_origr\   rx   ry   r  r  r   r   r   r   r  r  Zlrsumr  r  rv   r   r  r   r!  r"  r   Ze_expr   r   r8   r#  r   Z	non_limitdenZden_symr   rW   r   hfactoredr3   r3   r9   r  Z  s    







,
 


 


 


r  c              	   C   s  |dkr t | ||| |dS | |ddkr|ddlm} || |tdddddkrdtjdfS t | ||d |dS ddlm} || |}|du rdS t|t	rdd	lm
} ||}dd
lm} ddlm} ddlm}	 |	t|\}
}|
|\}}||\}}||g}||g}g g g}tdD ]}|| D ]}d}|jrd|j}|j}|jsd  dS t||}| dkr  dS | \}}||  || 9  < ||  || g| 7  < q8q,|d dg }|d }|d |d  }t|||}|| } | |d|| |jfS )z) Returns (res, cond). Sums from a to oo. r   r   r\   Tr   r   )	hypersimpN)	nsimplifyr   )hyperexpand)fractionr   )_eval_sum_hyperr   r   r   r   r   rj   r,  re   r   r-  r   r   sympy.simplify.hyperexpandr.  r&  r/  r)   as_coeff_mulr   is_Powr   baser   r(   degree
all_coeffsr   convergence_statement)rp   r\   rx   r   r,  hsr-  r   r.  r/  numerr#  topZtoplbotZbotlabfactorsparamsrV   facmulr   r   rv   apbqr   r*  r3   r3   r9   r0    sV    



"r0  c                 C   s4  |\}}}|  |du rd S || jr*d S t| |||f}|tjkr|tju rt| || || }|d ur~t||dfS ndd }|| }t| ||}	|	d u s||	|krd S t| ||d }
|
d u s||
|krd S |	|
 \}	}\}
}t	||}|dkrd S t|	|
 |f|dfS |tju rt| || |d}	t| |d}
|	d u s^|
d u rbd S |	\}	}|
\}
}t	||}|dks|
 tjkrd S t|	|
 |f|dfS t| ||}|d ur0|\}}|dkr"|jr| |tdddd| } | js
| jrtjS | jrtjS d S t||dfS d S )	NFTc                    s   t  fddtD S )Nc                 3   s   | ]}  |V  qd S r   )count)r7   r   r
  r3   r9   r:   3  r;   z3eval_sum_hyper.<locals>.<lambda>.<locals>.<genexpr>)sumr   r
  r3   r
  r9   r  3  r;   z eval_sum_hyper.<locals>.<lambda>r   r   r\   r   )is_hypergeometricr   r2   r   r   r   r0  r   r   r#   r   EmptySetr   r   rO   rE   rQ   )rp   i_a_br\   rx   ry   Zold_sumresZ	n_illegalZhadres1res2Zcond1cond2r   r   cr3   r3   r9   r'  !  s^    







r'  c                    s  |\}}dd }dd }dd }fdd}t d	fd
d} jtg rXdS |jsr|tjtjfv srdS |js|tjtjfv sdS |tjkr|tjkrdS | }	|	rd}
|	\}}n*| tj  }	|	rd}
|	\}}ndS || dk rdS ||ftjtjfkrv||}|du r4dS |\}}|rFdS ||||
fdd|D }tj	 t
| S |jr|tju sdS |||s4||}|jsdS |dkrdS ||}||}|||sdS |
rtj tj| |  |    n| |   t || || fS ||}|du rJdS |\}}|rdd |D }t|}t|}t||| d ksdS |t|krdS ||||
fdd|| D }tj	 t
| }|sF| di d } fddtt|dD } fddtdt|D }|t
| t
| }|S |d } fddtt|d t|D }|t
| }|S )a  Compute the infinite summation with residues

    Notes
    =====

    If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$,
    some infinite summations can be computed by the following residue
    evaluations.

    .. math::
        \sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} =
        -\pi \sum_{\alpha|g(\alpha)=0}
        \text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha)

    .. math::
        \sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} =
        -\pi \sum_{\alpha|g(\alpha)=0}
        \text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha)

    Examples
    ========

    >>> from sympy import Sum, oo, Symbol
    >>> x = Symbol('x')

    Doubly infinite series of rational functions.

    >>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit()
    pi/tanh(pi)

    Doubly infinite alternating series of rational functions.

    >>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit()
    pi/sinh(pi)

    Infinite series of even rational functions.

    >>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit()
    1/2 + pi/(2*tanh(pi))

    Infinite series of alternating even rational functions.

    >>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit()
    pi/(2*sinh(pi)) + 1/2

    This also have heuristics to transform arbitrarily shifted summand or
    arbitrarily shifted summation range to the canonical problem the
    formula can handle.

    >>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit()
    1/2 + pi/(2*tanh(pi))
    >>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit()
    1/2 + pi/(2*tanh(pi))
    >>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit()
    -1/2 + pi/(2*tanh(pi))
    >>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit()
    -1 + pi/(2*tanh(pi))

    References
    ==========

    .. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf

    .. [#] Asmar N.H., Grafakos L. (2018) Residue Theory.
           In: Complex Analysis with Applications.
           Undergraduate Texts in Mathematics. Springer, Cham.
           https://doi.org/10.1007/978-3-319-94063-2_5
    c                 S   sh   t dd |  D }t dd | D }t dd |  D }t dd | D }|r`|pf|of|S )z1Test if the rational function is an even functionc                 s   s   | ]\}|d  dkV  qdS r   r   Nr3   r[   r3   r3   r9   r:     r;   z=eval_sum_residue.<locals>.is_even_function.<locals>.<genexpr>c                 s   s   | ]\}|d  dkV  qdS rM  r3   r[   r3   r3   r9   r:     r;   c                 s   s   | ]\}|d  dkV  qdS r   r   Nr3   r[   r3   r3   r9   r:     r;   c                 s   s   | ]\}|d  dkV  qdS rN  r3   r[   r3   r3   r9   r:     r;   )allmonoms)r9  r#  Z
numer_evenZ
denom_evenZ	numer_oddZ	denom_oddr3   r3   r9   is_even_function  s
    z*eval_sum_residue.<locals>.is_even_functionc              	   S   sH   |   \}}zt||f|\\}}}W n ttfy>   Y d S 0 ||fS r   )as_numer_denomr'   r&   r%   )rp   r\   r9  r#  optr3   r3   r9   match_rational  s    z(eval_sum_residue.<locals>.match_rationalc                 S   s@   |    }t|dd }d |v r&d S |d |d  }}||fS )Nc                 S   s   | j S r   )rk   r
  r3   r3   r9   r    r;   z5eval_sum_residue.<locals>.get_poles.<locals>.<lambda>TF)sqf_part	all_rootsr1   )r#  roots	int_rootsnonint_rootsr3   r3   r9   	get_poles  s    z#eval_sum_residue.<locals>.get_polesc                    s<   |   }|  | }|  |d  }| | | }|S )Nr   )r5  coeff_monomial)r#  rv   rx   ry   shiftr  r3   r9   	get_shift  s
    
z#eval_sum_residue.<locals>.get_shiftr   c                    sF   |   |    }|s0|ttj 9 }n|ttj 9 }|S r   )as_exprr   r   r   Pir   )r9  r#  alternatingresidue_factor)r\   r   r3   r9   get_residue_factor  s
    z,eval_sum_residue.<locals>.get_residue_factorNFTr   c                    s   g | ]}t  |qS r3   r-   r7   rootra  r   r3   r9   r_     r;   z$eval_sum_residue.<locals>.<listcomp>r   c                 S   s   g | ]}t |qS r3   )r   rc  r3   r3   r9   r_     r;   r   c                    s   g | ]}t  |qS r3   r-   rc  re  r3   r9   r_   $  r;   c                    s   g | ]}  |iqS r3   rY   r7   i0rp   r\   r3   r9   r_   -  r;   c                    s   g | ]}  |iqS r3   rY   rf  rh  r3   r9   r_   .  r;   c                    s   g | ]}  |iqS r3   rY   rf  rh  r3   r9   r_   7  r;   )r   r   r   r   r   r   r   r   r5  r_  rD  rS   r\  r^  r(  r   r   r6   rZ   r   r   )rp   rG  rx   ry   rQ  rT  rZ  r]  rb  r   r`  r9  r#  ZpolesrX  rY  residuesr\  Zint_roots_maxZint_roots_minZfull_sumZhalf_sumZextraneous_negZextraneous_posr   Z
extraneousr3   )rp   r\   ra  r   r9   r(  ]  s    E
	






&
&r(  c           	      C   s~   | j }t| jD ]h\}}|\}}}|| }|jr|dk dkrT|d |d  }}| }t||||f}|d ur|   S qd S )Nr   Tr   )rA   ri   r4   r   r  rb   )	
expressionrp   rv   rw   r\   rx   ry   rz   r{   r3   r3   r9   rh   =  s    
rh   c           	         s   | \}}}||g}g d}i }i }|D ]> |j  d}|rFd| < q&t fdd|D r&d| < q&|r|| tdi |S dS )z
    Return a Dummy symbol that inherits as many assumptions as possible
    from the provided symbol and limits.

    If the symbol already has all True assumption shared by the limits
    then return None.
    )extended_nonnegativenonnegativeextended_nonpositivenonpositiveextended_positiver   extended_negativenegativer   rationalfinitezerorealextended_realNTc                 3   s   | ]}t |d   V  qdS )is_N)getattrr[   Zassumr3   r9   r:   d  r;   z<_dummy_with_inherited_properties_concrete.<locals>.<genexpr>rs   )rs   )_assumptionsra   rO  r$  r   )	r4   r   rx   ry   r8   Zassumptions_to_considerZassumptions_to_keepZassumptions_to_addZ
assum_truer3   ry  r9   rc   L  s    



rc   )_typingr   r   Zsympy.calculus.singularitiesr   !sympy.calculus.accumulationboundsr   expr_with_intlimitsr   expr_with_limitsr   Zgosperr   sympy.core.exprr	   Zsympy.core.addr
   sympy.core.containerssympy.core.functionr   r   sympy.core.mulr   sympy.core.numbersr   r   sympy.core.relationalr   sympy.core.singletonr   sympy.core.sortingr   sympy.core.symbolr   r   r   r   (sympy.functions.combinatorial.factorialsr   %sympy.functions.combinatorial.numbersr   r   &sympy.functions.elementary.exponentialr   r   $sympy.functions.elementary.piecewiser   (sympy.functions.elementary.trigonometricr   r   sympy.functions.special.hyperr   (sympy.functions.special.tensor_functionsr    &sympy.functions.special.zeta_functionsr!   sympy.integrals.integralsr"   sympy.logic.boolalgr#   sympy.polys.partfracr$   sympy.polys.polyerrorsr%   r&   sympy.polys.polytoolsr'   r(   r)   sympy.polys.rationaltoolsr*   sympy.series.limitseqr+   sympy.series.orderr,   Zsympy.series.residuesr.   sympy.sets.setsr/   r0   sympy.utilities.iterablesr1   r   r2   r   r   r  rl   r  r  r0  r'  r(  rh   rc   r3   r3   r3   r9   <module>   sn         N5./@ 6< a