o
    jg`                     @   st  d Z ddlmZ ddlmZmZmZmZmZ ddl	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mZmZmZ dd
lmZ ddlmZ ddlmZ  ddl!m"Z" e"dZ#dd Z$G dd de%Z&e dd Z'dd Z(dd Z)e e
e#dd Ze e#e
dd Z*dd Z+dd  Z,e e#d,d"d#Z-e e#e
d$d% Z.d&d' Z/e e#d(d) Z0d-d+dZ1d!S ).aS  
Limits
======

Implemented according to the PhD thesis
https://www.cybertester.com/data/gruntz.pdf, which contains very thorough
descriptions of the algorithm including many examples.  We summarize here
the gist of it.

All functions are sorted according to how rapidly varying they are at
infinity using the following rules. Any two functions f and g can be
compared using the properties of L:

L=lim  log|f(x)| / log|g(x)|           (for x -> oo)

We define >, < ~ according to::

    1. f > g .... L=+-oo

        we say that:
        - f is greater than any power of g
        - f is more rapidly varying than g
        - f goes to infinity/zero faster than g

    2. f < g .... L=0

        we say that:
        - f is lower than any power of g

    3. f ~ g .... L!=0, +-oo

        we say that:
        - both f and g are bounded from above and below by suitable integral
          powers of the other

Examples
========
::
    2 < x < exp(x) < exp(x**2) < exp(exp(x))
    2 ~ 3 ~ -5
    x ~ x**2 ~ x**3 ~ 1/x ~ x**m ~ -x
    exp(x) ~ exp(-x) ~ exp(2x) ~ exp(x)**2 ~ exp(x+exp(-x))
    f ~ 1/f

So we can divide all the functions into comparability classes (x and x^2
belong to one class, exp(x) and exp(-x) belong to some other class). In
principle, we could compare any two functions, but in our algorithm, we
do not compare anything below the class 2~3~-5 (for example log(x) is
below this), so we set 2~3~-5 as the lowest comparability class.

Given the function f, we find the list of most rapidly varying (mrv set)
subexpressions of it. This list belongs to the same comparability class.
Let's say it is {exp(x), exp(2x)}. Using the rule f ~ 1/f we find an
element "w" (either from the list or a new one) from the same
comparability class which goes to zero at infinity. In our example we
set w=exp(-x) (but we could also set w=exp(-2x) or w=exp(-3x) ...). We
rewrite the mrv set using w, in our case {1/w, 1/w^2}, and substitute it
into f. Then we expand f into a series in w::

    f = c0*w^e0 + c1*w^e1 + ... + O(w^en),       where e0<e1<...<en, c0!=0

but for x->oo, lim f = lim c0*w^e0, because all the other terms go to zero,
because w goes to zero faster than the ci and ei. So::

    for e0>0, lim f = 0
    for e0<0, lim f = +-oo   (the sign depends on the sign of c0)
    for e0=0, lim f = lim c0

We need to recursively compute limits at several places of the algorithm, but
as is shown in the PhD thesis, it always finishes.

Important functions from the implementation:

compare(a, b, x) compares "a" and "b" by computing the limit L.
mrv(e, x) returns list of most rapidly varying (mrv) subexpressions of "e"
rewrite(e, Omega, x, wsym) rewrites "e" in terms of w
leadterm(f, x) returns the lowest power term in the series of f
mrv_leadterm(e, x) returns the lead term (c0, e0) for e
limitinf(e, x) computes lim e  (for x->oo)
limit(e, z, z0) computes any limit by converting it to the case x->oo

All the functions are really simple and straightforward except
rewrite(), which is the most difficult/complex part of the algorithm.
When the algorithm fails, the bugs are usually in the series expansion
(i.e. in SymPy) or in rewrite.

This code is almost exact rewrite of the Maple code inside the Gruntz
thesis.

Debugging
---------

Because the gruntz algorithm is highly recursive, it's difficult to
figure out what went wrong inside a debugger. Instead, turn on nice
debug prints by defining the environment variable SYMPY_DEBUG. For
example:

[user@localhost]: SYMPY_DEBUG=True ./bin/isympy

In [1]: limit(sin(x)/x, x, 0)
limitinf(_x*sin(1/_x), _x) = 1
+-mrv_leadterm(_x*sin(1/_x), _x) = (1, 0)
| +-mrv(_x*sin(1/_x), _x) = set([_x])
| | +-mrv(_x, _x) = set([_x])
| | +-mrv(sin(1/_x), _x) = set([_x])
| |   +-mrv(1/_x, _x) = set([_x])
| |     +-mrv(_x, _x) = set([_x])
| +-mrv_leadterm(exp(_x)*sin(exp(-_x)), _x, set([exp(_x)])) = (1, 0)
|   +-rewrite(exp(_x)*sin(exp(-_x)), set([exp(_x)]), _x, _w) = (1/_w*sin(_w), -_x)
|     +-sign(_x, _x) = 1
|     +-mrv_leadterm(1, _x) = (1, 0)
+-sign(0, _x) = 0
+-limitinf(1, _x) = 1

And check manually which line is wrong. Then go to the source code and
debug this function to figure out the exact problem.

    )reduce)BasicSMul	PoleError
expand_mul)cacheit)ilcm)Ioo)DummyWild)	bottom_up)logexpsign)Order)SymPyDeprecationWarning)debug_decorator)timethisgruntzc                 C   s   t | t |}}t| trt| ts| jr| jtjkr| j}t|tr5t|ts2|jr5|jtjkr5|j}t|| |}|dkrBdS |j	rGdS dS )z/Returns "<" if a<b, "=" for a == b, ">" for a>br   <>=)
r   
isinstancer   r   is_Powbaser   Exp1limitinfis_infinite)abxlalbc r&   K/var/www/html/zoom/venv/lib/python3.10/site-packages/sympy/series/gruntz.pycompare   s   &&r(   c                       sR   e Zd ZdZdd Z fddZdd Zdd	 Zd
d ZdddZ	dd Z
  ZS )SubsSeta~  
    Stores (expr, dummy) pairs, and how to rewrite expr-s.

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

    The gruntz algorithm needs to rewrite certain expressions in term of a new
    variable w. We cannot use subs, because it is just too smart for us. For
    example::

        > Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))]
        > O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w]
        > e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p))
        > e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1])
        -1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p))

    is really not what we want!

    So we do it the hard way and keep track of all the things we potentially
    want to substitute by dummy variables. Consider the expression::

        exp(x - exp(-x)) + exp(x) + x.

    The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}.
    We introduce corresponding dummy variables d1, d2, d3 and rewrite::

        d3 + d1 + x.

    This class first of all keeps track of the mapping expr->variable, i.e.
    will at this stage be a dictionary::

        {exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}.

    [It turns out to be more convenient this way round.]
    But sometimes expressions in the mrv set have other expressions from the
    mrv set as subexpressions, and we need to keep track of that as well. In
    this case, d3 is really exp(x - d2), so rewrites at this stage is::

        {d3: exp(x-d2)}.

    The function rewrite uses all this information to correctly rewrite our
    expression in terms of w. In this case w can be chosen to be exp(-x),
    i.e. d2. The correct rewriting then is::

        exp(-w)/w + 1/w + x.
    c                 C   s
   i | _ d S N)rewritesselfr&   r&   r'   __init__   s   
zSubsSet.__init__c                    s   t   d | j  S )Nz, )super__repr__r+   r,   	__class__r&   r'   r0      s   zSubsSet.__repr__c                 C   s   || vr	t  | |< t| |S r*   )r   dict__getitem__)r-   keyr&   r&   r'   r4      s   
zSubsSet.__getitem__c                 C   s$   |   D ]\}}|||i}q|S )z)Substitute the variables with expressions)itemsxreplace)r-   eexprvarr&   r&   r'   do_subs   s   zSubsSet.do_subsc                 C   s    t |  t| t  kS )z;Tell whether or not self and s2 have non-empty intersection)setkeysintersectionlist)r-   s2r&   r&   r'   meets   s    zSubsSet.meetsNc                 C   s~   |   }i }| D ]\}}|| v r$|r|||| i}|| ||< q
|||< q
|j D ]\}}|||j|< q.||fS )z0Compute the union of self and s2, adjusting exps)copyr6   r7   r+   )r-   r@   expsrestrr9   r:   rewrr&   r&   r'   union   s   
zSubsSet.unionc                 C   s0   t  }| j |_|  D ]\}}|||< q|S )z Create a shallow copy of SubsSet)r)   r+   rB   r6   )r-   rr9   r:   r&   r&   r'   rB      s
   
zSubsSet.copyr*   )__name__
__module____qualname____doc__r.   r0   r4   r;   rA   rG   rB   __classcell__r&   r&   r1   r'   r)      s    .
r)   c                    s"  ddl m} || ddd} t| tstd| s t | fS | kr-t }|| fS | js3| jro| 	\}}|j
| j
krOt|\}}|| 
||fS | \}}t|\}	}
t|\}}t|	|| 
||
|S | jr| jtjkrtj}
| jr| j}|
| j9 }
|} | js~|dkrt |fS |
rt|tju rt|
jdu rtt|
|d  S tt|
t| S t|\}}|||
 fS t| trt| jd \}}|t|fS t| ts| jrK| jtjkrKt| jtrt| jjd S t| j}td	d
 t|D r=t }	|	|  }
t| j\}}|	|d }t||j|
< t|	|
|t|||
S t| j\}}|t|fS | jrfdd| jD }dd |D }t|dkrkt d|d t }  fdd|D }|| j
| fS | j!rt dt d|  )zoReturns a SubsSet of most rapidly varying (mrv) subexpressions of 'e',
       and e rewritten in terms of theser   powsimpTr   deepcombine e should be an instance of Basic   Fc                 s   s    | ]}|j V  qd S r*   )r   ).0_r&   r&   r'   	<genexpr>)  s    zmrv.<locals>.<genexpr>c                    s   g | ]}t | qS r&   )mrv)rU   r    r"   r&   r'   
<listcomp>4      zmrv.<locals>.<listcomp>c                 S   s   g | ]\}}|t  kr|qS r&   )r)   )rU   srV   r&   r&   r'   rZ   5      zGMRV set computation for functions in several variables not implemented.c                    s   g | ]	}  |d  qS )rT   )r;   rU   r"   )ssr&   r'   rZ   ;  s    z8MRV set computation for derivatives not implemented yet.z+Don't know how to calculate the mrv of '%s')"sympy.simplify.powsimprO   r   r   	TypeErrorhasr)   is_Mulis_Addas_independentfuncrX   as_two_termsmrv_max1r   r   r   r   Oner   r   r   r   argsanyr   	make_argsrG   r+   mrv_max3is_FunctionlenNotImplementedErroris_Derivative)r8   r"   rO   r\   idr9   r    r!   s1e1r@   e2b1lisull2rj   r&   )r_   r"   r'   rX      s~   






 rX   c                 C   s   t | ts	tdt |tstd| t kr||fS |t kr$| |fS | |r-||fS tt|  d t| d |}|dkrG| |fS |dkrO||fS |dkrWtd||fS )a)  
    Computes the maximum of two sets of expressions f and g, which
    are in the same comparability class, i.e. max() compares (two elements of)
    f and g and returns either (f, expsf) [if f is larger], (g, expsg)
    [if g is larger] or (union, expsboth) [if f, g are of the same class].
    z"f should be an instance of SubsSetz"g should be an instance of SubsSetr   r   r   r   zc should be =)r   r)   ra   rA   r(   r?   r=   
ValueError)fexpsfgexpsgrG   expsbothr"   r%   r&   r&   r'   rm   D  s$   




$rm   c                 C   s0   |  ||\}}t| |||| ||||S )ag  Computes the maximum of two sets of expressions f and g, which
    are in the same comparability class, i.e. mrv_max1() compares (two elements of)
    f and g and returns the set, which is in the higher comparability class
    of the union of both, if they have the same order of variation.
    Also returns exps, with the appropriate substitutions made.
    )rG   rm   r;   )r}   r   rC   r"   ur!   r&   r&   r'   rh   a  s   rh   c           	      C   s  t | ts	td| jrdS | jrdS | jrdS | |s+ddlm} || } t	| S | |kr1dS | j
rJ|  \}}t||}|sCdS |t|| S t | trQdS | jrr| jtjkr\dS t| j|}|dkrhdS | jjrq|| j S nt | trt| jd d |S t| |\}}t||S )a  
    Returns a sign of an expression e(x) for x->oo.

    ::

        e >  0 for x sufficiently large ...  1
        e == 0 for x sufficiently large ...  0
        e <  0 for x sufficiently large ... -1

    The result of this function is currently undefined if e changes sign
    arbitrarily often for arbitrarily large x (e.g. sin(x)).

    Note that this returns zero only if e is *constantly* zero
    for x sufficiently large. [If e is constant, of course, this is just
    the same thing as the sign of e.]
    rS   rT   r   )
logcombine)r   r   ra   is_positiveis_negativeis_zerorb   sympy.simplifyr   _signrc   rg   r   r   r   r   r   r   
is_Integerr   rj   mrv_leadterm)	r8   r"   r   r    r!   sar\   c0e0r&   r&   r'   r   m  sF   






r   c           
      C   sX  | }|  |s	| S ddlm} ddlm} |  tr |   } |jr&|j	r4t
ddd}| ||} |}| jdd|d} || } t| |r\t| j|t| j|krStt| j|\}}nt| |\}}t||}|d	krotjS |d
kr|ttdtgd r|t S t||}	|	dkrtd|	t S |dkr||kr| }t||S td|)zLimit e(x) for x-> oo.r   	powdenestAccumBoundspTpositive	tractable)rQ   limitvarrT   r   r    )excludezLeading term should not be 0z{} could not be evaluated)rb   r`   r   sympy.calculus.utilr   r   expandremoveOr   
is_integerr   subsrewriter   r   minmaxrp   r   r   Zeromatchr
   r   r   r|   cancelr   format)
r8   r"   oldr   r   r   r   r   sigr\   r&   r&   r'   r     sB   





r   c                 C   sd   t  }|  D ]\}}||||t|i< q| j D ]\}}| j| |t|i|j|< q|S r*   )r)   r6   r7   r   r+   )r\   r"   rH   r9   r:   r&   r&   r'   moveup2  s    r   c                    s    fdd| D S )Nc                    s   g | ]}|  t iqS r&   )r7   r   )rU   r8   rY   r&   r'   rZ     r]   zmoveup.<locals>.<listcomp>r&   )rz   r"   r&   rY   r'   moveup  s   r   Nc                 C   sv   t ddddd  ddlm} | j||dD ]!}t|d	d
 }| }|tr2|t	r2||}|j
s8 |S q|S )z Calculates at least one term of the series of ``e`` in ``x``.

    This is a place that fails most often, so it is in its own function.
    calculate_seriesz,series() with suitable n, or as_leading_termiNU  z1.12)feature
useinsteadissuedeprecated_since_versionr   r   logxc                       t  d fdd S )Nnormalc                          S r*   r&   r&   wr&   r'   <lambda>      z4calculate_series.<locals>.<lambda>.<locals>.<lambda>getattrr   r&   r   r'   r     s   z"calculate_series.<locals>.<lambda>)r   warnr`   r   lseriesr   factorrb   r   r   r   )r8   r"   r   r   tr&   r&   r'   r     s$   
r   c                 C   s  t  }| |s| tjfS |t  krt| |\}}|s |tjfS ||v r5t||}t|g|d }|}|}tddd}t||||\}}z	|j	||d}	W nl t
ttfy   d}
td}tj}|jrt|j||
| |d}|d9 }|jsc|  }z	|j	||d}	W n3 t
ttfy   ||}	|	d |r| d |}| d }|d | |d | f}	Y nw Y nw |	d t|||	d fS )	zReturns (c0, e0) for e.r   r   Tr   r   rT   )nr      )r)   rb   r   r   rX   r   r   r   r   leadtermrp   r   r|   r   ri   is_Order_eval_nseriesr   r   as_coeff_exponentas_base_expr   r   )r8   r"   OmegarC   Omega_upexps_upr   r}   logwltn0_seriesincrseriesr   exr&   r&   r'   r     sL   





r   c           
      C   s   G dd d}i }| D ]\}}| }||_ ||_|||< q| D ]$\}}||v rC|| }|| }| D ]\}}	||	rB|j||	  q1q|S )a   Helper function for rewrite.

    We need to sort Omega (mrv set) so that we replace an expression before
    we replace any expression in terms of which it has to be rewritten::

        e1 ---> e2 ---> e3
                 \
                  -> e4

    Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
    To do this we assemble the nodes into a tree, and sort them by height.

    This function builds the tree, rewrites then sorts the nodes.
    c                   @   s   e Zd Zdd Zdd ZdS )z#build_expression_tree.<locals>.Nodec                 S   s   g | _ d | _d | _d S r*   )beforer9   r:   r,   r&   r&   r'   r.   Q  s   
z,build_expression_tree.<locals>.Node.__init__c                 S   s   t dd dd | jD dS )Nc                 S   s   | | S r*   r&   )r"   yr&   r&   r'   r   V  s    z8build_expression_tree.<locals>.Node.ht.<locals>.<lambda>c                 S   s   g | ]}|  qS r&   htr^   r&   r&   r'   rZ   W  s    z:build_expression_tree.<locals>.Node.ht.<locals>.<listcomp>rT   )r   r   r,   r&   r&   r'   r   U  s   z&build_expression_tree.<locals>.Node.htN)rI   rJ   rK   r.   r   r&   r&   r&   r'   NodeP  s    r   )r:   r9   rb   r   append)
r   r+   r   nodesr9   vr   rV   rH   v2r&   r&   r'   build_expression_treeA  s    

r   c                    s  ddl m} t|tstdt|dkrtd| D ]}t|ts(tdq|j	}t
| }t|| |j fdddd	 |D ]\}}t|j|}	|	d
kra|	dkra|	|satd|	 qD|	d
krjd
| }g }
g }|D ]C\}}t|j|j |}|jr||j |j}||v rt|| tstd|| jd }|
|t|||j   ||  f qpddlm} || ddd}|
D ]\}}|||i}q|D ]\}}||rJ q|j}|	d
kr| }tt|d
}|||| i}|| }t|dd }t|}||fS )ze(x) ... the function
    Omega ... the mrv set
    wsym ... the symbol which is going to be used for w

    Returns the rewritten e in terms of w and log(w). See test_rewrite1()
    for examples and correct results.
    r   r   z&Omega should be an instance of SubsSetzLength cannot be 0zValue should be expc                    s    | d    S )NrT   r   rY   r   r&   r'   r     s    zrewrite.<locals>.<lambda>T)r5   reverserT   r   z Result depends on the sign of %srN   r   rP   c                    r   )Nr   c                      r   r*   r&   r&   r   r&   r'   r     r   z+rewrite.<locals>.<lambda>.<locals>.<lambda>r   r   r&   r   r'   r     r[   )sympyr   r   r)   ra   ro   r|   r=   r   r+   r?   r6   r   sortr   rb   rp   r   is_Rationalr   qrj   r   r`   rO   r7   r   r	   r   r   r   )r8   r   r"   wsymr   r   r+   r   rV   r   O2denominatorsr}   r:   r%   argrO   r    r!   r   exponentr&   r   r'   r   i  s^   


*r   +c                 C   s   |j stdd}|ttt fv r| }n8|t t t fv r&| || }n&t|dkr7| ||d|  }nt|dkrH| ||d|  }ntdt||}|jddd	S )
ac  
    Compute the limit of e(z) at the point z0 using the Gruntz algorithm.

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

    ``z0`` can be any expression, including oo and -oo.

    For ``dir="+"`` (default) it calculates the limit from the right
    (z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
    (oo or -oo), the dir argument does not matter.

    This algorithm is fully described in the module docstring in the gruntz.py
    file. It relies heavily on the series expansion. Most frequently, gruntz()
    is only used if the faster limit() function (which uses heuristics) fails.
    z Second argument must be a SymbolN-rT   r   zdir must be '+' or '-'intractableT)rQ   )	is_symbolrp   r   r
   r   strr   r   )r8   zz0dirrH   r   r&   r&   r'   r     s   
r*   )r   )2rL   	functoolsr   
sympy.corer   r   r   r   r   sympy.core.cacher   sympy.core.intfuncr	   sympy.core.numbersr
   r   sympy.core.symbolr   r   sympy.core.traversalr   sympy.functionsr   r   r   r   sympy.series.orderr   sympy.utilities.exceptionsr   sympy.utilities.miscr   debugsympy.utilities.timeutilsr   timeitr(   r3   r)   rX   rm   rh   r   r   r   r   r   r   r   r   r&   r&   r&   r'   <module>   sT    v\
L9-	'/(P