
    gg*                      d dl mZ d dlmZ d dlmZ d dlmZ d dl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mZ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$m%Z% d dl&m'Z'm(Z( d dl)m*Z*m+Z+ d dl,m-Z- erddl.m/Z/ d dl0m1Z1 d Z2e G d dee             Z3 G d dee3      Z4d Z5 G d de3      Z6d Z7 G d  d!      Z8dd"l9m:Z: dd#l;m<Z< dd$l=m>Z> dd%l?m@Z@mAZA dd&lBmCZC dd'lDmEZE dd(l.mFZFmGZGmHZHmIZImJZJ y))    )annotations)TYPE_CHECKING)Iterable)reduceN   )sympify_sympify)BasicAtom)S)
EvalfMixinpure_complexDEFAULT_MAXPREC)call_highest_prioritysympify_method_argssympify_return)cacheit)mod_inverse)default_sort_key)
NumberKindsympy_deprecation_warning)as_int	func_name
filldedent)has_varietysift)mpf_logprec_to_dps)giant_steps)Number)defaultdictc                    g }g }t        j                  |       D ]8  }|j                  |      }|s|j                  |       (|j                  |       : t        | t        | fS N)Add	make_argscoeffappend)eqccononicis         D/var/www/openai/venv/lib/python3.12/site-packages/sympy/core/expr.py_coremr0      sZ    	B
C]]2WWQZJJqMIIbM  8S#Y    c                  f    e Zd ZU dZdZded<   dZed        Ze	dd       Z
d	 Zd
Zed        Zed        Zd Zd ZddZ edge       ed      d               Z edge       ed      d               Z edge       ed      d               Z edge       ed      d               Z edge       ed      d               Z edge       ed      d               Z edge       ed      d               ZdddZ edge       ed       d!               Z edge       ed"      d#               Z edge       ed$      d%               Z edge       ed&      d'               Z  edge       ed(      d)               Z! edge       ed*      d+               Z" edge       ed,      d-               Z# edge       ed.      d/               Z$ edge       ed0      d1               Z%d2 Z&d3 Z'd4 Z( edge      d5        Z) edge      d6        Z* edge      d7        Z+ edge      d8        Z,d9 Z-d fd:Z.e/d;        Z0ed<        Z1dd=Z2d> Z3dd?Z4d@ Z5dA Z6dB Z7dC Z8dD Z9dE Z:dF Z;dG Z<dH Z=dI Z>dJ Z?dK Z@eAdL        ZBddMZCdN ZDddOZEdP ZFdQ ZGdR ZHdS ZIddTZJddUZKddVZLdW ZMdX ZNddYZOddZZPd[ ZQd\ ZRdd]ZSdd^ZTdd_ZUd` ZVddaZWdb ZXdc ZYdd ZZde Z[edf        Z\dg Z]ddhZ^di Z_dj Z`dk Zadl Zbdm Zcdn Zddo Zedp ZfddrZgddsZhdt ZidduZjddvZkddwZldx ZmddyZnddzZoe	ddqd{d|       Zpdd}Zqdd~ZrddZsdddZtdddZu	 	 ddZvddZwd Zxd Zye/dd       Zze		 	 dd       Z{d Z|ddZ}ddZ~ddZd ZddZd Zd Zd Zd Zd Zd Zd Zd Zd ZddZeZd Z xZS )Expra  
    Base class for algebraic expressions.

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

    Everything that requires arithmetic operations to be defined
    should subclass this class, instead of Basic (which should be
    used only for argument storage and expression manipulation, i.e.
    pattern matching, substitutions, etc).

    If you want to override the comparisons of expressions:
    Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch.
    _eval_is_ge return true if x >= y, false if x < y, and None if the two types
    are not comparable or the comparison is indeterminate

    See Also
    ========

    sympy.core.basic.Basic
     ztuple[str, ...]	__slots__Tc                     y)a~  Return True if one can differentiate with respect to this
        object, else False.

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

        Subclasses such as Symbol, Function and Derivative return True
        to enable derivatives wrt them. The implementation in Derivative
        separates the Symbol and non-Symbol (_diff_wrt=True) variables and
        temporarily converts the non-Symbols into Symbols when performing
        the differentiation. By default, any object deriving from Expr
        will behave like a scalar with self.diff(self) == 1. If this is
        not desired then the object must also set `is_scalar = False` or
        else define an _eval_derivative routine.

        Note, see the docstring of Derivative for how this should work
        mathematically. In particular, note that expr.subs(yourclass, Symbol)
        should be well-defined on a structural level, or this will lead to
        inconsistent results.

        Examples
        ========

        >>> from sympy import Expr
        >>> e = Expr()
        >>> e._diff_wrt
        False
        >>> class MyScalar(Expr):
        ...     _diff_wrt = True
        ...
        >>> MyScalar().diff(MyScalar())
        1
        >>> class MySymbol(Expr):
        ...     _diff_wrt = True
        ...     is_scalar = False
        ...
        >>> MySymbol().diff(MySymbol())
        Derivative(MySymbol(), MySymbol())
        Fr4   selfs    r/   	_diff_wrtzExpr._diff_wrtG   s    R r1   Nc           	        | j                         \  }}|j                  rX|j                  t        j                  u r, t        d      |j                        t        j                  }}n |j                  \  }}nt        j                  }|j                  r|j                         f}n|j                  rt        |      f}nn|j                  r|j                  |      }n+|j                  r|j!                  |      }n|j                  }t#        |D cg c]  }t%        ||       c}      }t'        |      t#        |      f}|j                  |      }|j)                         |||fS c c}w )Nexporder)as_coeff_Mulis_Powbaser   Exp1Functionr;   Oneargsis_Dummysort_keyis_Atomstris_Addas_ordered_termsis_Mulas_ordered_factorstupler   len	class_key)r8   r=   r'   exprr;   rD   args          r/   rF   zExpr.sort_keyr   s*    '')t;;yyAFF" ,HUODHH5quuc II	c%%C==MMO%D\\I<D{{,,5,9..U.;yy@DF"3e4FHD D	5;'lll'~~sE11 Gs   E)c                    | j                   S )a  Return a tuple of information about self that can be used to
        compute the hash. If a class defines additional attributes,
        like ``name`` in Symbol, then this method should be updated
        accordingly to return such relevant attributes.
        Defining more than _hashable_content is necessary if __eq__ has
        been defined by a class. See note about this in Basic.__eq__.)_argsr7   s    r/   _hashable_contentzExpr._hashable_content   s     zzr1   g      $@c                    t         S r$   r%   r7   s    r/   _add_handlerzExpr._add_handler       
r1   c                    t         S r$   Mulr7   s    r/   _mul_handlerzExpr._mul_handler   rX   r1   c                    | S r$   r4   r7   s    r/   __pos__zExpr.__pos__       r1   c                f    | j                   }t        j                  t        j                  | f|      S r$   )is_commutativer[   
_from_argsr   NegativeOner8   r*   s     r/   __neg__zExpr.__neg__   s)     ~~q}}d3Q77r1   c                    ddl m}  ||       S )Nr   )Abs)$sympy.functions.elementary.complexesrg   )r8   rg   s     r/   __abs__zExpr.__abs__   s    <4yr1   )otherr3   __radd__c                    t        | |      S r$   rV   r8   rj   s     r/   __add__zExpr.__add__        4r1   rn   c                    t        ||       S r$   rV   rm   s     r/   rk   zExpr.__radd__        5$r1   __rsub__c                    t        | |       S r$   rV   rm   s     r/   __sub__zExpr.__sub__   s     4%  r1   rt   c                    t        ||        S r$   rV   rm   s     r/   rr   zExpr.__rsub__   s     54%  r1   __rmul__c                    t        | |      S r$   rZ   rm   s     r/   __mul__zExpr.__mul__   ro   r1   rx   c                    t        ||       S r$   rZ   rm   s     r/   rv   zExpr.__rmul__   rq   r1   __rpow__c                    t        | |      S r$   Powrm   s     r/   _powz	Expr._pow   ro   r1   c           	     ^   || j                  |      S 	 t        |       t        |      t        |      }}}|dk\  rt        t        |||            S t        t	        t        || |      |            S # t
        $ r1 | j                  |      }	 ||z  cY S # t        $ r t        cY cY S w xY ww xY wNr   )r~   r   r	   powr   
ValueError	TypeErrorNotImplemented)r8   rj   mod_selfpowers        r/   __pow__zExpr.__pow__   s    ;99U##	& &tfUmVC[#5EzE5# 677Cvs,CS IJJ 	&IIe$E&Sy  &%%&		&s5   ;A2  A2 2B,BB,B(#B,'B((B,r   c                    t        ||       S r$   r|   rm   s     r/   rz   zExpr.__rpow__   rq   r1   __rtruediv__c                v    t        |t        j                        }| t        j                  u r|S t	        | |      S r$   r}   r   rc   rC   r[   r8   rj   denoms      r/   __truediv__zExpr.__truediv__   s1     E1==)155=LtU##r1   r   c                v    t        | t        j                        }|t        j                  u r|S t	        ||      S r$   r   r   s      r/   r   zExpr.__rtruediv__  s1     D!--(AEE>Lue$$r1   __rmod__c                    t        | |      S r$   Modrm   s     r/   __mod__zExpr.__mod__  ro   r1   r   c                    t        ||       S r$   r   rm   s     r/   r   zExpr.__rmod__  rq   r1   __rfloordiv__c                $    ddl m}  || |z        S Nr   )floor#sympy.functions.elementary.integersr   r8   rj   r   s      r/   __floordiv__zExpr.__floordiv__  s     	>TE\""r1   r   c                $    ddl m}  ||| z        S r   r   r   s      r/   r   zExpr.__rfloordiv__  s     	>UT\""r1   __rdivmod__c                <    ddl m}  || |z        t        | |      fS r   r   r   r   r   s      r/   
__divmod__zExpr.__divmod__%  s"     	>TE\"Ce$444r1   r   c                <    ddl m}  ||| z        t        ||       fS r   r   r   s      r/   r   zExpr.__rdivmod__+  s"     	>UT\"Ct$444r1   c                   | j                   st        d      | j                  d      }|j                  st        d      |t        j
                  t        j                  t        j                  fv rt        d|z        t        |      }|s|S t        |      ra| |kD  t        j                  u r|S | |k  t        j                  u r|dz
  S | j                  |      }|t        d      |r|S ||dkD  rdz
  S dz
  S |S )	NzCannot convert symbols to int   zCannot convert complex to intzCannot convert %s to intr   z#cannot compute int value accuratelyr   )	is_numberr   round	is_Numberr   NaNInfinityNegativeInfinityint
int_valuedtrueequals)r8   rr-   oks       r/   __int__zExpr.__int__1  s    ~~;<<JJqM{{;<<

A$6$6776:;;FHa=qQVV#qQVV#1uQBz EFFQU++++r1   c                    | j                         }|j                  rt        |      S |j                  r|j	                         d   rt        d      t        d      )Nr   zCannot convert complex to floatz"Cannot convert expression to float)evalfr   floatr   as_real_imagr   )r8   results     r/   	__float__zExpr.__float__K  sS     =  3 3 5a 8=>><==r1   c                    | j                         }|j                         \  }}t        t        |      t        |            S r$   )r   r   complexr   )r8   r   reims       r/   __complex__zExpr.__complex__V  s4    $$&BuRy%),,r1   c                     ddl m}  || |      S )Nr   )GreaterThan)
relationalr   )r8   rj   r   s      r/   __ge__zExpr.__ge__[  s    +4''r1   c                     ddl m}  || |      S )Nr   )LessThan)r   r   )r8   rj   r   s      r/   __le__zExpr.__le__`  s    (e$$r1   c                     ddl m}  || |      S )Nr   )StrictGreaterThan)r   r   )r8   rj   r   s      r/   __gt__zExpr.__gt__e  s    1 u--r1   c                     ddl m}  || |      S )Nr   )StrictLessThan)r   r   )r8   rj   r   s      r/   __lt__zExpr.__lt__j  s    .dE**r1   c                F    | j                   st        d      t        |       S )Nz'Cannot truncate symbols and expressions)r   r   Integerr7   s    r/   	__trunc__zExpr.__trunc__o  s    ~~EFF4= r1   c                2   | j                   r|t        j                  d|      }|rdt        |j	                  d            }| j                  |      }|j                  rt        t        |      |      S |j                  rt        ||      S t        | )  |      S )Nz\+?\d*\.(\d+)fr   )r   r   matchr   groupr   
is_Integerformatis_Floatsuper
__format__)r8   format_specmtprecrounded	__class__s        r/   r   zExpr.__format__u  s~    >>+[9B288A;'**T*%%!#g,<<##!';77w!+..r1   c                *   t        | d      r t        j                  | j                  |      S t        | d      rQ| j                  \  }}t        j                  ||      }t        j                  ||      t
        j                  z  }||z   S t        d      )N_mpf__mpc_z#expected mpmath number (mpf or mpc))hasattrFloat_newr   r   r   ImaginaryUnitr   )xr   r   r   s       r/   _from_mpmathzExpr._from_mpmath  sv    1g::aggt,,Q WWFBB%BB%aoo5B7NABBr1   c                :    t        d | j                  D              S )a@  Returns True if ``self`` has no free symbols and no
        undefined functions (AppliedUndef, to be precise). It will be
        faster than ``if not self.free_symbols``, however, since
        ``is_number`` will fail as soon as it hits a free symbol
        or undefined function.

        Examples
        ========

        >>> from sympy import Function, Integral, cos, sin, pi
        >>> from sympy.abc import x
        >>> f = Function('f')

        >>> x.is_number
        False
        >>> f(1).is_number
        False
        >>> (2*x).is_number
        False
        >>> (2 + Integral(2, x)).is_number
        False
        >>> (2 + Integral(2, (x, 1, 2))).is_number
        True

        Not all numbers are Numbers in the SymPy sense:

        >>> pi.is_number, pi.is_Number
        (True, False)

        If something is a number it should evaluate to a number with
        real and imaginary parts that are Numbers; the result may not
        be comparable, however, since the real and/or imaginary part
        of the result may not have precision.

        >>> cos(1).is_number and cos(1).is_comparable
        True

        >>> z = cos(1)**2 + sin(1)**2 - 1
        >>> z.is_number
        True
        >>> z.is_comparable
        False

        See Also
        ========

        sympy.core.basic.Basic.is_comparable
        c              3  4   K   | ]  }|j                     y wr$   )r   ).0objs     r/   	<genexpr>z!Expr.is_number.<locals>.<genexpr>  s     6IS3==I   )allrD   r7   s    r/   r   zExpr.is_number  s    d 6DII666r1   c                x   | j                   }d}|rfddlm} ||||f\  }	}
}}t        t	        t        ||D cg c]  } ||	||
|d       c}                  }	 t        | j                  d|            }ni }t        | j                  d            }t        |d	      sy|j                  dk(  rBt        dt              D ]/  }t        | j                  ||            }|j                  dk7  s/ n |j                  dk7  r!|t        |d
      }| j                  ||      S yc c}w # t        t        f$ r Y yw xY w)a  Return self evaluated, if possible, replacing free symbols with
        random complex values, if necessary.

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

        The random complex value for each free symbol is generated
        by the random_complex_number routine giving real and imaginary
        parts in the range given by the re_min, re_max, im_min, and im_max
        values. The returned value is evaluated to a precision of n
        (if given) else the maximum of 15 and the precision needed
        to get more than 1 digit of precision. If the expression
        could not be evaluated to a number, or could not be evaluated
        to more than 1 digit of precision, then None is returned.

        Examples
        ========

        >>> from sympy import sqrt
        >>> from sympy.abc import x, y
        >>> x._random()                         # doctest: +SKIP
        0.0392918155679172 + 0.916050214307199*I
        >>> x._random(2)                        # doctest: +SKIP
        -0.77 - 0.87*I
        >>> (x + y/2)._random(2)                # doctest: +SKIP
        -0.57 + 0.16*I
        >>> sqrt(2)._random(2)
        1.4

        See Also
        ========

        sympy.core.random.random_complex_number
        r   r   )random_complex_numberTrationalr   subsN_prec   )free_symbolssympy.core.randomr   dictlistzipabsr   r   r   r   r   r    r   max)r8   nre_minim_minre_maxim_maxfreer   r   ar*   bdzirepsnmags                   r/   _randomzExpr._random  sO   H   ?7JAq!QS%)(+%)r )>aAqSW(X%)(+ , - .D4::ad:34 Dtzz!}%DtW%::?
 $A74::d:67::? 8
 ::?ybM::ad:++ G(+ 	*  s   D"D' 'D98D9c                :   d }|j                  dd      }| j                  ry| j                  }|syt        |      }|r||z  sy|xs |}| }|r|j	                         }|j
                  ry|D ch c]  }|j                  t        u s| }}d}	||k(  ry	 |j                  t        t        |dgt        |      z              d      }
|
t        j                  u r|j                  ddddd      }
|
|
t        j                  ur	 |j                  t        t        |dgt        |      z              d      }|t        j                  u r|j                  ddddd      }|&|t        j                  ur|j!                  |
      du ry|j                  dd	ddd      }|&|t        j                  ur|j!                  |
      du ry|j                         }|6|t        j                  ur$|j!                  |
      du ry|
j                  r|
n|}	|D ]O  }|j#                  |      }|r|j	                         }|dk7  s,t%        |d
      s|j                  dd      r|	c S  y  ||       }|du ry|yyc c}w # t        $ r d}
Y w xY w# t        $ r d}Y 7w xY w)a  Return True if self is constant, False if not, or None if
        the constancy could not be determined conclusively.

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

        If an expression has no free symbols then it is a constant. If
        there are free symbols it is possible that the expression is a
        constant, perhaps (but not necessarily) zero. To test such
        expressions, a few strategies are tried:

        1) numerical evaluation at two random points. If two such evaluations
        give two different values and the values have a precision greater than
        1 then self is not constant. If the evaluations agree or could not be
        obtained with any precision, no decision is made. The numerical testing
        is done only if ``wrt`` is different than the free symbols.

        2) differentiation with respect to variables in 'wrt' (or all free
        symbols if omitted) to see if the expression is constant or not. This
        will not always lead to an expression that is zero even though an
        expression is constant (see added test in test_expr.py). If
        all derivatives are zero then self is constant with respect to the
        given symbols.

        3) finding out zeros of denominator expression with free_symbols.
        It will not be constant if there are zeros. It gives more negative
        answers for expression that are not constant.

        If neither evaluation nor differentiation can prove the expression is
        constant, None is returned unless two numerical values happened to be
        the same and the flag ``failing_number`` is True -- in that case the
        numerical value will be returned.

        If flag simplify=False is passed, self will not be simplified;
        the default is True since self should be simplified before testing.

        Examples
        ========

        >>> from sympy import cos, sin, Sum, S, pi
        >>> from sympy.abc import a, n, x, y
        >>> x.is_constant()
        False
        >>> S(2).is_constant()
        True
        >>> Sum(x, (x, 1, 10)).is_constant()
        True
        >>> Sum(x, (x, 1, n)).is_constant()
        False
        >>> Sum(x, (x, 1, n)).is_constant(y)
        True
        >>> Sum(x, (x, 1, n)).is_constant(n)
        False
        >>> Sum(x, (x, 1, n)).is_constant(x)
        True
        >>> eq = a*cos(x)**2 + a*sin(x)**2 - a
        >>> eq.is_constant()
        True
        >>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
        True

        >>> (0**x).is_constant()
        False
        >>> x.is_constant()
        False
        >>> (x**x).is_constant()
        False
        >>> one = cos(x)**2 + sin(x)**2
        >>> one.is_constant()
        True
        >>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
        True
        c                b    ddl m} d} ||       D ]  }|j                  }|du r y|d} |ry y)Nr   )denomsFT)sympy.solvers.solversr  is_zero)
expressionr  retNonedenzs        r/   check_denominator_zerosz1Expr.is_constant.<locals>.check_denominator_zerosZ  sA    4Gj)KK99"G * r1   simplifyTNr   )simultaneousr   Fr   or_realfailing_number)getr   r   setr  r  kindr   r   r   r   rN   r   r   r  ZeroDivisionErrorr   diffr   )r8   wrtflagsr  r  r  rP   sym
wrt_numberr  r  r  wderivcds                  r/   is_constantzExpr.is_constant  s   V	 99Z.>>   #hsTzkT ==?D
 << &)CScCHH
,BcS
C IId3taST]#;<!%  ':T1aA6A }!%%		$s4!SY'?"@%) " +AAEEz LLq!Q: =Qaee^u8L LLr1a3=Qaee^u8L LLN=Qaee^xx{e+$*+++Q1N AIIaLE(z$UD9yy!159--  %T*:Zm D %  ) As2   0I4I4AI9 AJ 9JJJJc                |   ddl mm ddlm} ddlm} ddlm} t        |      }| |k(  ryt         | |z
        d      }|sy|j                  t        t              sy|j                         d	   }t        |      d	kD  r-|D cg c]  }|j!                  d       }	}d
|	vrt#        |	      S |j%                  dd      }
|
du ry|j&                  s|
y
|
du r|j)                         }|r|j*                  ry|j&                  r|j-                  t.              D cg c]  }|j0                  d   j2                  s|  c}j5                  d        D ]  	  ||d      }|r|v r yt7        d |D              r yt7        d |D              r yt#        fd|D              r yt#        fd|D              r yj8                  rt#        fd|D              r y 	 	  ||      }|j<                  ryy|
dvr|
dk7  ry|r|S y
c c}w c c}w # t:        $ r Y w xY w# |t:        f$ r Y 5w xY w)a  Return True if self == other, False if it does not, or None. If
        failing_expression is True then the expression which did not simplify
        to a 0 will be returned instead of None.

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

        If ``self`` is a Number (or complex number) that is not zero, then
        the result is False.

        If ``self`` is a number and has not evaluated to zero, evalf will be
        used to test whether the expression evaluates to zero. If it does so
        and the result has significance (i.e. the precision is either -1, for
        a Rational result, or is greater than 1) then the evalf value will be
        used to return True or False.

        r   )	nsimplifyr  )solveNotAlgebraicminimal_polynomialT)radicalFr   N)r  r  c                "    | j                   d    S r   )rD   )r   s    r/   <lambda>zExpr.equals.<locals>.<lambda>  s    affQiZr1   key)r  c              3  4   K   | ]  }|j                     y wr$   )r   )r   sis     r/   r   zExpr.equals.<locals>.<genexpr>  s     ;sr}}sr   c              3  8   K   | ]  }|j                   d u   yw)FN)is_algebraic)r   r-   s     r/   r   zExpr.equals.<locals>.<genexpr>"  s     D1q~~6s   c              3  &   K   | ]  }|v  
 y wr$   r4   )r   r2  surdss     r/   r   zExpr.equals.<locals>.<genexpr>%  s     9SrrU{Ss   c              3  Z   K   | ]"  } |z
        d k(  xr  |z
        d k(   $ yw)r   Nr4   r   r2  r&  sr  s     r/   r   zExpr.equals.<locals>.<genexpr>)  sC      E@C"  )R0A5  6 (R 0A 5 6@Cs   (+c              3  R   K   | ]  } |g      k(  xr  |      k(     y wr$   r4   r8  s     r/   r   zExpr.equals.<locals>.<genexpr>-  s8      #3.1 $-R!#5#:#Px|q?P#P.1s   $')TN)sympy.simplify.simplifyr&  r  r  r'  sympy.polys.polyerrorsr)  sympy.polys.numberfieldsr+  r   factor_termshasr%   r   as_coeff_mulrN   r   anyr$  r   r  is_comparableatomsr}   rD   r   sortr   is_realNotImplementedError	is_Symbol)r8   rj   failing_expressionr'  r)  r+  r  factorsfacfac_zeroconstantndiffr9  solmpr&  r  r6  s               `  @@@r/   r   zExpr.equals  sT   $ 	@/7?5= HTE\2DAxxS! ##%a(w<!189#

1H98#8}$##U4#Hu~~ tLLNE ,," >> $

3H1166!93G3GQHEJJ/J0  a%8C8#';s;; $)DDD#(9S99 $) E@CE E#'99" #3.1#3  3'+; F +D1B||#  <'HMKA :R IB +  %&9: sT   	HH>HH1HHH/H"H/H- 	H*)H*-H;:H;c                   ddl m} ddlm} | j                  r/	 | j                  d      }|y t        |dd      dk(  ry |t        j                  u ry | j                  d      }|j                  r|t        j                  f}nt        |      }|y|\  }}|j                  r|j                  sy|j                  dk7  r-|j                  dk7  rt!        | xr |r	|dkD        S |dk        S |j                  dk(  rN|r|j                  dk(  r<| j#                         r+| j%                  t&              s	  ||       j(                  ryy y y y y y # t        $ r Y y w xY w# |t*        f$ r Y y w xY w)Nr   r*  r(  r   r   r   F)r=  r+  r<  r)  r   _eval_evalfr   getattrr   r   r   r   Zeror   r   r   bool_eval_is_algebraicr?  rB   rG  rF  )	r8   positiver+  r)  n2fr   r   r-   s	            r/   #_eval_is_extended_positive_negativez(Expr._eval_is_extended_positive_negativeH  s_   ?7>>%%a( zr7A&!+QUU{

1Azz166	$Q}DAqKKAKKww!|1EH(AIIQIIAqAGGqL++-dhhx6H)$/99$ : 7I- -99   4 %&9: s#   E
 1E 
	EEE'&E'c                &    | j                  d      S )NTrV  rY  r7   s    r/   _eval_is_extended_positivezExpr._eval_is_extended_positiveo  s    777FFr1   c                &    | j                  d      S )NFr[  r\  r7   s    r/   _eval_is_extended_negativezExpr._eval_is_extended_negativer  s    777GGr1   c           	     n    ddl m ddlm} ddlmm ddlm} ddl	m
} t        d       fd}k(  rt        j                  S  |d	
      }|t        j                  u r|S  |d
      }	xr |	|z
  S |	|z
  }
j                  rj                  rk  r
 |      }n	 |      } | j!                         j#                         d   |      } j%                  |      D ]  }| ||j&                  d   |      z  } 	 |D ]  }|
t        j                  u r |
S |j                  s%|k  |k  cxk(  rd	k(  rn n|
  |d         |d      z   z  }
U|k  |k  cxk(  rd	k(  sgn j|
  |d        |d      z
  z  }
 	 |
S |
S # t(        $ r Y |
S w xY w)a^  
        Returns evaluation over an interval.  For most functions this is:

        self.subs(x, b) - self.subs(x, a),

        possibly using limit() if NaN is returned from subs, or if
        singularities are found between a and b.

        If b or a is None, it only evaluates -self.subs(x, a) or self.subs(b, x),
        respectively.

        r   AccumBoundslog)limitLimit)Interval)solvesetz"Both interval ends cannot be None.c                r   | rn}|t         j                  S j                  	|      }|j                  t         j                  t         j
                  t         j                  t         j                        r>k  dk7  r 	|| rdnd      }n 	|| rdnd      }t        |      rt        d      |S )NF+-zCould not compute limit)
r   rS  r   r?  r   r   r   ComplexInfinity
isinstancerF  )
leftr*   Crb  rf  r  r  re  r8   r   s
      r/   _eval_endpointz+Expr._eval_interval.<locals>._eval_endpoint  s    qAyvvIIaO55

A,>,>**K9A%'!$1TcsC!$1TcsC!!U+12KLLHr1   T)rn  Fr   )domainrj  rk  )!sympy.calculus.accumulationboundsrb  &sympy.functions.elementary.exponentialrd  sympy.series.limitsre  rf  sympy.sets.setsrg  sympy.solvers.solvesetrh  r   r   rS  r   rB  cancelas_numer_denomrC  rD   r   )r8   r   r  r  rd  rg  rh  rp  ABvaluerq  singularitieslogtermr9  rb  rf  re  s   ````           @@@r/   _eval_intervalzExpr._eval_intervalu  s    	B>4,3I!)ABB	 	" 666M%:H&G!q5LA??q1u!!Q!!Q %T[[]%A%A%CA%FM::c? -a!!1# !# +&A~  ?? A1q51T1%aC"8!85q!S;Q!QQa%QU3t3tQ3!7%aC:P!PP ' u  s   F' 4AF' F' '	F43F4c                     y r$   r4   rm   s     r/   _eval_powerzExpr._eval_power  s     r1   c                >    | j                   r| S | j                  r|  S y r$   )is_extended_realis_imaginaryr7   s    r/   _eval_conjugatezExpr._eval_conjugate  s%      K5L r1   c                    ddl m}  ||       S )z(Returns the complex conjugate of 'self'.r   	conjugate)rh   r  rd   s     r/   r  zExpr.conjugate  s    Gwr1   c                4   | j                   rt        j                  S ddlm} t        j                  }| }|r|t        j
                  z  }|j                  |      }|j                  |d      }|t        j                  u r|j                  |d      }|t        j                  u r7	 |j                  |      \  }}|j                   ||            r
t               	 |t        j                  k7  rn|r||z  z  S # t        $ r |j                  |d      }Y <w xY w)Nr   rc  )r  r   rS  rs  rd  rC   r  r   r   re  rl  leadtermr?  r   )r8   r   cdirrd  minexprQ   r'   _s           r/   dirzExpr.dir  s    <<66M>aeeOF((1+CHHQNE~		!Q))),"||AHE1yyQ((l* )   T6\!!	 " ,IIaOE,s   $5C9 9DDc                    ddl m} | j                  s| j                  r| S | j                  r ||       S | j
                  r	 ||        S y )Nr   r  )rh   r  
is_complexis_infiniteis_hermitianis_antihermitian)r8   r  s     r/   _eval_transposezExpr._eval_transpose  sG    BOOt//KT?"""dO## #r1   c                    ddl m}  ||       S )Nr   )	transpose)rh   r  )r8   r  s     r/   r  zExpr.transpose  s    Br1   c                    ddl m}m} | j                  r| S | j                  r|  S | j                         }| ||      S | j                         }| ||      S y )Nr   )r  r  )rh   r  r  r  r  r  r  )r8   r  r  r   s       r/   _eval_adjointzExpr._eval_adjoint  sb    MK""5L""$?S>!""$?S>! r1   c                    ddl m}  ||       S )Nr   )adjoint)rh   r  )r8   r  s     r/   r  zExpr.adjoint  s    @t}r1   c                    ddl m} t        dd      }|d}n |d      }|rdd  |      fdfd	}||fS )
z+Parse and configure the ordering of terms. r   )monomial_key
startswithNFzrev-   c           	     r    t        | D cg c]  }t        |t               r |      n|  c}      S c c}w r$   )rM   rm  )monommnegs     r/   r  zExpr._parse_order.<locals>.neg  s4    %P%QJq%$8#a&qb@%PQQPs   "4c                    | \  }\  \  }}}} 	 |            }t        |D cg c]  }|j                  
       c}      }t        |      |f||ff}|||fS c c}w )Nr<   )rM   rF   rT  )termr  r   r   r  ncparter'   	monom_keyr  r=   s           r/   r0  zExpr._parse_order.<locals>.key  st    +/(A(R%	%()EVDVAJJUJ3VDEF2h^b"X.E&%'' Es   A)sympy.polys.orderingsr  rR  )clsr=   r  r  reverser0  r  r  s    `    @@r/   _parse_orderzExpr._parse_order  sZ     	7UL$7
G (Gab	 '		R	( G|r1   c                    | gS )z4Return list of ordered factors (if Mul) else [self].r4   )r8   r=   s     r/   rL   zExpr.as_ordered_factors(  s	    vr1   c                p    ddl m}m} ddlm} 	  || g|i |}|j
                  sy|S # ||f$ r Y yw xY w)a  Converts ``self`` to a polynomial or returns ``None``.

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

        >>> from sympy import sin
        >>> from sympy.abc import x, y

        >>> print((x**2 + x*y).as_poly())
        Poly(x**2 + x*y, x, y, domain='ZZ')

        >>> print((x**2 + x*y).as_poly(x, y))
        Poly(x**2 + x*y, x, y, domain='ZZ')

        >>> print((x**2 + sin(y)).as_poly(x, y))
        None

        r   )PolynomialErrorGeneratorsNeeded)PolyN)r<  r  r  sympy.polys.polytoolsr  is_Poly)r8   gensrD   r  r  r  polys          r/   as_polyzExpr.as_poly,  sM    & 	M.
	,t,t,D<<!12 	 	s   + + 55c                0   ddl mm || j                  rfd}t	        t        j                  |       |      }t        |      dk(  rt        |d   f      rst        |d   t              r`t	        t        j                  |d         |      }t        |      dk(  r/t        |d         r |d   j                  r|d   j                  r|S | j                  |      \  }}| j                         \  }}t        d |D              st	        |||      }	n^g g }}
|D ]8  \  }}|j                  s|
j!                  ||f       &|j!                  ||f       : t	        |
|d	      t	        ||d	      z   }	|r|	|fS |	D cg c]  \  }}|	 c}}S c c}}w )
a"  
        Transform an expression to an ordered list of terms.

        Examples
        ========

        >>> from sympy import sin, cos
        >>> from sympy.abc import x

        >>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
        [sin(x)**2*cos(x), sin(x)**2, 1]

        r   )r!   NumberSymbolc                "    t        | f       S r$   )rm  )r   r!   r  s    r/   r.  z'Expr.as_ordered_terms.<locals>.<lambda>b  s    z!fl-CDDr1   r/  r   r   c              3  :   K   | ]  \  }}|j                     y wr$   )is_Order)r   r  r  s      r/   r   z(Expr.as_ordered_terms.<locals>.<genexpr>q  s     6WT14==s   )r0  r  T)numbersr!   r  rI   sortedr%   r&   rN   rm  r[   is_positiveis_negativer  as_termsrA  r  r(   )r8   r=   datar0  add_argsmul_argsr  termsr  ordered_terms_orderr  reprr  r!   r  s                  @@r/   rJ   zExpr.as_ordered_termsN  sx    	2=T[[ ECcmmD1s;HH"x{V\,BCx{C0!#--"<#FMQ&"8A;7 // //#O((/Wmmot666UW=GFF#
d}}MM4,/MM4,/	 $ Vd;S$78G D= (/0WT1D000s   Fc                h   ddl m} t               g }}t        j                  |       D ]  }|j                         \  }}t        |      }i g }}|t        j                  urut        j                  |      D ]]  }	|	j                  r	 |t        |	      z  }|	j                  r" ||	      \  }
}|||
<   |j                  |
       M|j                  |	       _ |j                   |j"                  f}t%        |      }|j                  ||||ff        t'        |t(              }t+        |      i }}t-        |      D ]
  \  }}|||<    g }|D ]N  \  }\  }}}dg|z  }|j/                         D ]  \  }
}||||
   <    |j                  ||t%        |      |ff       P ||fS # t        t        f$ r Y w xY w)z,Transform an expression to a list of terms. r   )decompose_powerr/  r   )	exprtoolsr  r  r%   r&   r>   r   r   rC   r[   r   r   r   ra   addr(   realimagrM   r  r   rN   	enumerateitems)r8   r  r  r  r  r'   _termcpartr  factorr@   r;   kindicesr-   gr   r  s                     r/   r  zExpr.as_terms  s   .eReMM$'D,,.LE5ENE6EAEE!!mmE2F''%!WV_4E %,,$3F$;	c&)df- 3" JJ

*E6]FLL$v 6787 (: d 01Y7dODAqGAJ $ ,1(D(5%CEE"[[]	c'*gdm$ + MM4%uv!>?@ -2 t|G !*:6 ! !s   FF10F1c                    | S )z1Removes the additive O(..) symbol if there is oner4   r7   s    r/   removeOzExpr.removeO  s    r1   c                     y)z=Returns the additive O(..) symbol if there is one, else None.Nr4   r7   s    r/   getOz	Expr.getO  s    r1   c                   | j                         }|y|j                  rC|j                  }|t        j                  u rt        j
                  S |j                  rt        j                  S |j                  r|j                  d   S |j                  r|j                  D ]  }|j                  rt        j                  c S |j                  s.ddl
m}m} |j                  |      }t        |      dk(  sV|j                         }|j!                  | |dd            }|j"                  j                  s|j$                  j&                  st)        |j$                        c S  t+        d|z        )a  
        Returns the order of the expression.

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

        The order is determined either from the O(...) term. If there
        is no O(...) term, it returns None.

        Examples
        ========

        >>> from sympy import O
        >>> from sympy.abc import x
        >>> (1 + x + O(x**2)).getn()
        2
        >>> (1 + x).getn()

        Nr   DummySymbolr   Tr[  znot sure of order of %s)r  r  rP   r   rC   rS  rG  r?   rD   rK   symbolr  r  rC  rN   popr   r@   r;   is_Rationalr   rF  )r8   ooir  r  symsr   s          r/   getnz	Expr.getn  s   ( IIK9ZZAAEEzvv{{uuxxvvay xx&&B|| uuyy9!xx/t9> $
A!#E#,E!FB!ww00RVV5G5G'*266{ 2 ! "";a"?@@r1   c                     ddl m}  || |      S )Nr   )	count_ops)functionr  )r8   visualr  s      r/   r  zExpr.count_ops  s    'v&&r1   c           	     8   | j                   rt        | j                        }n| g}t        |      D ]  \  }}|j                  r|d| }||d } n |}g }|rN|rL|d   j
                  r=|d   j                  r.|d   t        j                  urt        j                  |d    g|dd |rlt        |      }	t        |      }|	rT|rRt        |      |	k7  rDt        d|D 
cg c],  }
t        | j                        j                  |
      dkD  s+|
. c}
z        ||gS c c}
w )a  Return [commutative factors, non-commutative factors] of self.

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

        self is treated as a Mul and the ordering of the factors is maintained.
        If ``cset`` is True the commutative factors will be returned in a set.
        If there were repeated factors (as may happen with an unevaluated Mul)
        then an error will be raised unless it is explicitly suppressed by
        setting ``warn`` to False.

        Note: -1 is always separated from a Number unless split_1 is False.

        Examples
        ========

        >>> from sympy import symbols, oo
        >>> A, B = symbols('A B', commutative=0)
        >>> x, y = symbols('x y')
        >>> (-2*x*y).args_cnc()
        [[-1, 2, x, y], []]
        >>> (-2.5*x).args_cnc()
        [[-1, 2.5, x], []]
        >>> (-2*x*A*B*y).args_cnc()
        [[-1, 2, x, y], [A, B]]
        >>> (-2*x*A*B*y).args_cnc(split_1=False)
        [[-2, x, y], [A, B]]
        >>> (-2*x*y).args_cnc(cset=True)
        [{-1, 2, x, y}, []]

        The arg is always treated as a Mul:

        >>> (-2 + x + A).args_cnc()
        [[], [x - 2 + A]]
        >>> (-oo).args_cnc() # -oo is a singleton
        [[-1, oo], []]
        Nr   r   z"repeated commutative arguments: %s)rK   r   rD   r  ra   r   is_extended_negativer   rc   rN   r  r   count)r8   csetwarnsplit_1rD   r-   mir*   ncclenr.   s              r/   args_cnczExpr.args_cnc  s   N ;;		?D6Dt_EAr$$!H!"X	 % ABaDNNaD%%!AMM)]]QqTE*AbqEq6DAAQ4 !E/0!RqDO4I4I"4MPQ4Q"q!R"S T T2w "Ss   ,D
D
c                   t        |      }t        |t              st        j                  S t        |      }|st        j                  S || k(  r%|dk(  rt        j                  S t        j                  S |t        j                  u r`t        j                  |       D cg c]'  }|j                         d   t        j                  u r|) c}st        j                  S t         S |dk(  r|j                  r| j                  r| j                  ||      }|st        j                  S |s/| t        t        j                  |      D cg c]  }||z  	 c} z
  S | t        t        j                  |      D cg c]  }||z  	 c} z
  S | j                  |d      d   S ||z  }d }dd}g t        j                  |       }	| j                  }
|j                  }|
r|st        j                  S |r | j                  r|
s|st        j                  |      }t        t        j                  | j                  |      d         D cg c]  t        fd|D              r c} }|j                  ||d	
      }|j                  r|s|S t!        |j"                  D cg c]  }|j%                          c} \  }}t'        |      r|S t        |D cg c]  }t        j(                  |       c} S |
xs |}|j%                  dt+        |             \  }}|	D ]  }|j%                  dt+        |
             \  }}|g }t-        |      t-        |      kD  r?|j/                  |      }t-        |      t-        |      z   t-        |      k(  st|r$j1                  t        t3        |      |z           j1                  ||f        |r g k(  rt        j                  S rt         S yst        j                  S t        fdD              rk |d   d   ||      }|Y|s:t        t        D cg c]  \  }}t        |  c}} t        d   d   d|        S t        d   d   |t-        |      z   d  S t5        |d D              }|r ||||      }||sTd   d   }t7        dt-                    D ]  |j9                     d         }|r n t        t3        |      |d| z    S |t-        |      z   }t        D cg c]  \  }}t        t3        |      ||d z     c}} S t3        t;        t5        |d D                          }|rb ||||      }|V|s=t        D cg c])  \  }}t        t3        |      |dt-        |       |z    z    + c}} S t        ||t-        |      z   d  S d}t=              D ]-  \  \  }} ||||      }||s|||f} t        j                  S  |r6|\  }}}|st        t3        |      |d| z    S t        ||t-        |      z   d  S t        j                  S c c}w c c}w c c}w c c}w c c}w c c}w c c}}w c c}}w c c}}w )a  
        Returns the coefficient from the term(s) containing ``x**n``. If ``n``
        is zero then all terms independent of ``x`` will be returned.

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

        When ``x`` is noncommutative, the coefficient to the left (default) or
        right of ``x`` can be returned. The keyword 'right' is ignored when
        ``x`` is commutative.

        Examples
        ========

        >>> from sympy import symbols
        >>> from sympy.abc import x, y, z

        You can select terms that have an explicit negative in front of them:

        >>> (-x + 2*y).coeff(-1)
        x
        >>> (x - 2*y).coeff(-1)
        2*y

        You can select terms with no Rational coefficient:

        >>> (x + 2*y).coeff(1)
        x
        >>> (3 + 2*x + 4*x**2).coeff(1)
        0

        You can select terms independent of x by making n=0; in this case
        expr.as_independent(x)[0] is returned (and 0 will be returned instead
        of None):

        >>> (3 + 2*x + 4*x**2).coeff(x, 0)
        3
        >>> eq = ((x + 1)**3).expand() + 1
        >>> eq
        x**3 + 3*x**2 + 3*x + 2
        >>> [eq.coeff(x, i) for i in reversed(range(4))]
        [1, 3, 3, 2]
        >>> eq -= 2
        >>> [eq.coeff(x, i) for i in reversed(range(4))]
        [1, 3, 3, 0]

        You can select terms that have a numerical term in front of them:

        >>> (-x - 2*y).coeff(2)
        -y
        >>> from sympy import sqrt
        >>> (x + sqrt(2)*x).coeff(sqrt(2))
        x

        The matching is exact:

        >>> (3 + 2*x + 4*x**2).coeff(x)
        2
        >>> (3 + 2*x + 4*x**2).coeff(x**2)
        4
        >>> (3 + 2*x + 4*x**2).coeff(x**3)
        0
        >>> (z*(x + y)**2).coeff((x + y)**2)
        z
        >>> (z*(x + y)**2).coeff(x + y)
        0

        In addition, no factoring is done, so 1 + z*(1 + y) is not obtained
        from the following:

        >>> (x + z*(x + x*y)).coeff(x)
        1

        If such factoring is desired, factor_terms can be used first:

        >>> from sympy import factor_terms
        >>> factor_terms(x + z*(x + x*y)).coeff(x)
        z*(y + 1) + 1

        >>> n, m, o = symbols('n m o', commutative=False)
        >>> n.coeff(n)
        1
        >>> (3*n).coeff(n)
        3
        >>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
        1 + m
        >>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
        m

        If there is more than one possible coefficient 0 is returned:

        >>> (n*m + m*n).coeff(n)
        0

        If there is only one possible coefficient, it is returned:

        >>> (n*m + x*m*n).coeff(m*n)
        x
        >>> (n*m + x*m*n).coeff(m*n, right=1)
        1

        See Also
        ========

        as_coefficient: separate the expression into a coefficient and factor
        as_coeff_Add: separate the additive constant from an expression
        as_coeff_Mul: separate the multiplicative constant from an expression
        as_independent: separate x-dependent terms/factors from others
        sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
        sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used
        r   r   )rightT)as_Addc                    | r|sg S t        t        |       t        |            }t        |      D ]  }| |   ||   k7  s| d | c S  | d d  S r$   )minrN   range)l1l2r   r-   s       r/   incommonzExpr.coeff.<locals>.incommon  sS    R	CGSW%A1Xa5BqE>bq6M  a5Lr1   c                    r rt              t               kD  ryt              }|s  j                          j                          t        t               |z
  dz         D ]#  t         fdt        |      D              s# n d|s  j                          j                          |st               |z   z
  S )a   Find where list sub appears in list l. When ``first`` is True
            the first occurrence from the left is returned, else the last
            occurrence is returned. Return None if sub is not in l.

            Examples
            ========

            >> l = range(5)*2
            >> find(l, [2, 3])
            2
            >> find(l, [2, 3], first=0)
            7
            >> find(l, [2, 4])
            None

            Nr   c              3  :   K   | ]  }|z      |   k(    y wr$   r4   )r   jr-   lsubs     r/   r   z+Expr.coeff.<locals>.find.<locals>.<genexpr>  s#     <8aqQx3q6)8   )rN   r  r  r   )r  r  firstr   r-   s   ``  @r/   findzExpr.coeff.<locals>.find  s    " a3s8c!f#4CA		3q6A:>*<58<< + 		}UFa!e$Hr1   c              3  L   K   | ]  }|t        j                        v   y wr$   )r[   r&   )r   xir-   s     r/   r   zExpr.coeff.<locals>.<genexpr>  s      >"rS]]1--s   !$F)r  _first)r  r  Nc              3  :   K   | ]  \  }}|d    d   k(    yw)r   r   Nr4   )r   r   r   r+   s      r/   r   zExpr.coeff.<locals>.<genexpr>  s"     0RTQ11a=Rr   c              3  &   K   | ]	  }|d      ywr   Nr4   r   r   s     r/   r   zExpr.coeff.<locals>.<genexpr>&  s     #5"QAaD"s   c              3  J   K   | ]  }t        t        |d                  ywr  )r   reversedr	  s     r/   r   zExpr.coeff.<locals>.<genexpr>5  s     !C1$x!~"6s   !#T)r   rm  r
   r   rS  r   rC   r%   r&   r>   rI   r'   as_independentra   r[   r   r   rD   r  r   rb   rT  rN   
differencer(   r   r   r  intersectionr  r  )r8   r   r   r  r  r  r*   r  r  rD   self_cx_cxargsr-   r  rvc_partnc_partone_cnxmargsr  residiir   beggcdcr  endhitr+   s                `                @r/   r'   z
Expr.coeff6  s:   ` AJ!U#66M1I66M9Avuu66M: ]]40 30^^%a(AEE1 0 3Bvv8O6xxDKKJJqJ.66M#S]]15E'F5E!5E'F"GGGcq1A#B1AAAaC1A#BCCC&&q&6q99 qD	!	F }}T"$$#66Mdkk&MM!$Et/B/B1/Ea/H!I @!IA>>> !I @ AA%6B99E	!"''#B'QAJJL'#BCOFG6"	G<Gq*G<==#JJDtG}J=	rA

4F
3C
DIE2z5zCJ&$$U+E5zCJ&#e*4IIcDK"$467IIubk*  RxvvBx  vv0R00"Q%(B.> "3R(@RTQaR(@#A31aQTRTCVWW"BqE!HR#b'\]$;<<#5"#56C#r5)> !!uQx!&q#b'!2A#'#4#4RU1X#>D#' % "3  #T$Z#cr(%:<<RL"$LAS47QqrU?%<$LMMxx!C!CDF GC#r5)> "VX$YVXdaQRS47QS	B5G+G%IVX$YZZ"CSW$677C&r]	6Aq!R'> !Qh 66M + "HB1 "T!Wq"v%577"Ab3r7lm$45566Ms3 (G#Bv@
 $C =< )A  %M %Zs6   ,X>Y
7Y
YYY3Y
!Y"
/.Y(
c                    | S )a/  
        Convert a polynomial to a SymPy expression.

        Examples
        ========

        >>> from sympy import sin
        >>> from sympy.abc import x, y

        >>> f = (x**2 + x*y).as_poly(x, y)
        >>> f.as_expr()
        x**2 + x*y

        >>> sin(x).as_expr()
        sin(x)

        r4   )r8   r  s     r/   as_exprzExpr.as_exprP  s	    $ r1   c                R    | j                  |      }|r|j                  |      s|S yy)a,  
        Extracts symbolic coefficient at the given expression. In
        other words, this functions separates 'self' into the product
        of 'expr' and 'expr'-free coefficient. If such separation
        is not possible it will return None.

        Examples
        ========

        >>> from sympy import E, pi, sin, I, Poly
        >>> from sympy.abc import x

        >>> E.as_coefficient(E)
        1
        >>> (2*E).as_coefficient(E)
        2
        >>> (2*sin(E)*E).as_coefficient(E)

        Two terms have E in them so a sum is returned. (If one were
        desiring the coefficient of the term exactly matching E then
        the constant from the returned expression could be selected.
        Or, for greater precision, a method of Poly can be used to
        indicate the desired term from which the coefficient is
        desired.)

        >>> (2*E + x*E).as_coefficient(E)
        x + 2
        >>> _.args[0]  # just want the exact match
        2
        >>> p = Poly(2*E + x*E); p
        Poly(x*E + 2*E, x, E, domain='ZZ')
        >>> p.coeff_monomial(E)
        2
        >>> p.nth(0, 1)
        2

        Since the following cannot be written as a product containing
        E as a factor, None is returned. (If the coefficient ``2*x`` is
        desired then the ``coeff`` method should be used.)

        >>> (2*E*x + x).as_coefficient(E)
        >>> (2*E*x + x).coeff(E)
        2*x

        >>> (E*(x + 1) + x).as_coefficient(E)

        >>> (2*pi*I).as_coefficient(pi*I)
        2
        >>> (2*I).as_coefficient(pi*I)

        See Also
        ========

        coeff: return sum of terms have a given factor
        as_coeff_Add: separate the additive constant from an expression
        as_coeff_Mul: separate the multiplicative constant from an expression
        as_independent: separate x-dependent terms/factors from others
        sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly
        sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used


        N)extract_multiplicativelyr?  )r8   rP   r   s      r/   as_coefficientzExpr.as_coefficientd  s.    @ ))$/QUU4[H !1r1   c                :   ddl m} ddlm} ddlm} | t        j                  u r| | fS | j                  }|j                  dt        | t                    rt        }nt        }t               g |D ]1  }t        ||      rj                  |       !j                  |       3 fd}	||us|t        ur,|t        ur$ |	|       r|j                  | fS | |j                  fS |t        u rt!        | j"                        }
n| j%                         \  }
}t'        |
|	      }|d   }|d   }|t        u rt        |  || fS t)              D ]4  \  }} |	|      r|j+                  ||d	         n|j                  |       6 t        | |rt        |d
difS  || fS )a  
        A mostly naive separation of a Mul or Add into arguments that are not
        are dependent on deps. To obtain as complete a separation of variables
        as possible, use a separation method first, e.g.:

        * separatevars() to change Mul, Add and Pow (including exp) into Mul
        * .expand(mul=True) to change Add or Mul into Add
        * .expand(log=True) to change log expr into an Add

        The only non-naive thing that is done here is to respect noncommutative
        ordering of variables and to always return (0, 0) for `self` of zero
        regardless of hints.

        For nonzero `self`, the returned tuple (i, d) has the
        following interpretation:

        * i will has no variable that appears in deps
        * d will either have terms that contain variables that are in deps, or
          be equal to 0 (when self is an Add) or 1 (when self is a Mul)
        * if self is an Add then self = i + d
        * if self is a Mul then self = i*d
        * otherwise (self, S.One) or (S.One, self) is returned.

        To force the expression to be treated as an Add, use the hint as_Add=True

        Examples
        ========

        -- self is an Add

        >>> from sympy import sin, cos, exp
        >>> from sympy.abc import x, y, z

        >>> (x + x*y).as_independent(x)
        (0, x*y + x)
        >>> (x + x*y).as_independent(y)
        (x, x*y)
        >>> (2*x*sin(x) + y + x + z).as_independent(x)
        (y + z, 2*x*sin(x) + x)
        >>> (2*x*sin(x) + y + x + z).as_independent(x, y)
        (z, 2*x*sin(x) + x + y)

        -- self is a Mul

        >>> (x*sin(x)*cos(y)).as_independent(x)
        (cos(y), x*sin(x))

        non-commutative terms cannot always be separated out when self is a Mul

        >>> from sympy import symbols
        >>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
        >>> (n1 + n1*n2).as_independent(n2)
        (n1, n1*n2)
        >>> (n2*n1 + n1*n2).as_independent(n2)
        (0, n1*n2 + n2*n1)
        >>> (n1*n2*n3).as_independent(n1)
        (1, n1*n2*n3)
        >>> (n1*n2*n3).as_independent(n2)
        (n1, n2*n3)
        >>> ((x-n1)*(x-y)).as_independent(x)
        (1, (x - y)*(x - n1))

        -- self is anything else:

        >>> (sin(x)).as_independent(x)
        (1, sin(x))
        >>> (sin(x)).as_independent(y)
        (sin(x), 1)
        >>> exp(x+y).as_independent(x)
        (1, exp(x + y))

        -- force self to be treated as an Add:

        >>> (3*x).as_independent(x, as_Add=True)
        (0, 3*x)

        -- force self to be treated as a Mul:

        >>> (3+x).as_independent(x, as_Add=False)
        (1, x + 3)
        >>> (-3+x).as_independent(x, as_Add=False)
        (1, x - 3)

        Note how the below differs from the above in making the
        constant on the dep term positive.

        >>> (y*(-3+x)).as_independent(x)
        (y, x - 3)

        -- use .as_independent() for true independence testing instead
           of .has(). The former considers only symbols in the free
           symbols while the latter considers all symbols

        >>> from sympy import Integral
        >>> I = Integral(x, (x, 1, 2))
        >>> I.has(x)
        True
        >>> x in I.free_symbols
        False
        >>> I.as_independent(x) == (I, 1)
        True
        >>> (I + x).as_independent(x) == (I, x)
        True

        Note: when trying to get independent terms, a separation method
        might need to be used first. In this case, it is important to keep
        track of what you send to this routine so you know how to interpret
        the returned values

        >>> from sympy import separatevars, log
        >>> separatevars(exp(x+y)).as_independent(x)
        (exp(y), exp(x))
        >>> (x + x*y).as_independent(y)
        (x, x*y)
        >>> separatevars(x + x*y).as_independent(y)
        (x, y + 1)
        >>> (x*(1 + y)).as_independent(y)
        (x, y + 1)
        >>> (x*(1 + y)).expand(mul=True).as_independent(y)
        (x, x*y)
        >>> a, b=symbols('a b', positive=True)
        >>> (log(a*b).expand(log=True)).as_independent(b)
        (log(a), log(b))

        See Also
        ========

        separatevars
        expand_log
        sympy.core.add.Add.as_two_terms
        sympy.core.mul.Mul.as_two_terms
        as_coeff_mul
        r   )r  _unevaluated_Add_unevaluated_Mulr  c                j     | j                    }s|S |xs  | j                   | j                  z   S )zreturn the standard has() if there are no literal symbols, else
            check to see that symbol-deps are in the free symbols.)r?  r   )r  	has_otherrj   r  s     r/   r?  z Expr.as_independent.<locals>.hasE  s<     uI  >(< >>r1   TFNevaluate)r  r  r  r&  mulr(  r   rS  funcr  rm  r%   r[   r  r(   identityr   rD   r  r   r  extend)r8   depshintr  r&  r(  r-  wantr  r?  rD   r  dependindepr-   r   rj   r  s                   @@r/   r  zExpr.as_independent  s   L 	#))166>$<yy88Hjs35DD eA!V$
Q	 	? CDO4yt,,dmm,,s{DII==?bsO4%3;K!16!:;;!"1q6MM"QR&)Q	 &
 ;02V,e,+ + &)+ +r1   c                \    |j                  d      | k(  ryddlm}m}  ||        ||       fS )a  Performs complex expansion on 'self' and returns a tuple
           containing collected both real and imaginary parts. This
           method cannot be confused with re() and im() functions,
           which does not perform complex expansion at evaluation.

           However it is possible to expand both re() and im()
           functions and get exactly the same results as with
           a single call to this function.

           >>> from sympy import symbols, I

           >>> x, y = symbols('x,y', real=True)

           >>> (x + y*I).as_real_imag()
           (x, y)

           >>> from sympy.abc import z, w

           >>> (z + w*I).as_real_imag()
           (re(z) - im(w), re(w) + im(z))

        ignoreNr   )r   r   )r  rh   r   r   )r8   deephintsr   r   s        r/   r   zExpr.as_real_imagh  s.    . 99X$&CtHbh''r1   c                d    t        t              }|j                  | j                         g       |S )a  Return self as a dictionary of factors with each factor being
        treated as a power. The keys are the bases of the factors and the
        values, the corresponding exponents. The resulting dictionary should
        be used with caution if the expression is a Mul and contains non-
        commutative factors since the order that they appeared will be lost in
        the dictionary.

        See Also
        ========
        as_ordered_factors: An alternative for noncommutative applications,
                            returning an ordered list of factors.
        args_cnc: Similar to as_ordered_factors, but guarantees separation
                  of commutative and noncommutative factors.
        )r"   r   updateas_base_exp)r8   r  s     r/   as_powers_dictzExpr.as_powers_dict  s+     	$""$%&r1   c                z   t        t              }|s}t        j                  |       D ])  }|j	                         \  }}||   j                  |       + |j                         D ]'  \  }}t        |      dk(  r	|d   ||<   t        | ||<   ) n | j                  |ddi\  }}	t        j                  |	      D ]  }
|
j                  r[ |
j                  | \  }}|t        j                  u r||
   j                  |       H| |
j                  |    j                  |       j|
sm||
   j                  t        j                          |D ci c]  }|t        ||     }}|t        j                  ur!|j                  t        j                  |i       t        t               }|j                  |       |S c c}w )aO  Return a dictionary mapping terms to their Rational coefficient.
        Since the dictionary is a defaultdict, inquiries about terms which
        were not present will return a coefficient of 0.

        If symbols ``syms`` are provided, any multiplicative terms
        independent of them will be considered a coefficient and a
        regular dictionary of syms-dependent generators as keys and
        their corresponding coefficients as values will be returned.

        Examples
        ========

        >>> from sympy.abc import a, x, y
        >>> (3*x + a*x + 4).as_coefficients_dict()
        {1: 4, x: 3, a*x: 1}
        >>> _[a]
        0
        >>> (3*a*x).as_coefficients_dict()
        {a*x: 3}
        >>> (3*a*x).as_coefficients_dict(x)
        {x: 3*a}
        >>> (3*a*x).as_coefficients_dict(y)
        {1: 3*a*x}

        r   r   r  T)r"   r   r%   r&   r>   r(   r  rN   r  rK   r@  r   rC   _new_rawargsrS  r:  r   )r8   r  r  air*   r  r  vinddepr-   r   dis                r/   as_coefficients_dictzExpr.as_coefficients_dict  sy   4 mmD)(1!A * 	1q6Q;Q4AaD7AaD	 " +t**D>>HC]]3'88)1>>40DAqAEEz!A.!..!,-44Q7aDKK& ( )**1C1JA*!&& !%%&
		!	 +s   F8c                &    | t         j                  fS r$   r   rC   r7   s    r/   r;  zExpr.as_base_exp  s    QUU{r1   c                R    |r | j                   | s| dfS t        j                  | ffS )a  Return the tuple (c, args) where self is written as a Mul, ``m``.

        c should be a Rational multiplied by any factors of the Mul that are
        independent of deps.

        args should be a tuple of all other factors of m; args is empty
        if self is a Number or if self is independent of deps (when given).

        This should be used when you do not know if self is a Mul or not but
        you want to treat self as a Mul or if you want to process the
        individual arguments of the tail of self as a Mul.

        - if you know self is a Mul and want only the head, use self.args[0];
        - if you do not want to process the arguments of the tail but need the
          tail then use self.as_two_terms() which gives the head and tail;
        - if you want to split self into an independent and dependent parts
          use ``self.as_independent(*deps)``

        >>> from sympy import S
        >>> from sympy.abc import x, y
        >>> (S(3)).as_coeff_mul()
        (3, ())
        >>> (3*x*y).as_coeff_mul()
        (3, (x, y))
        >>> (3*x*y).as_coeff_mul(x)
        (3*y, (x,))
        >>> (3*y).as_coeff_mul(x)
        (3*y, ())
        r4   )r?  r   rC   )r8   r0  kwargss      r/   r@  zExpr.as_coeff_mul  s-    < 488T?Rxuutg~r1   c                R    |r | j                   | s| dfS t        j                  | ffS )a  Return the tuple (c, args) where self is written as an Add, ``a``.

        c should be a Rational added to any terms of the Add that are
        independent of deps.

        args should be a tuple of all other terms of ``a``; args is empty
        if self is a Number or if self is independent of deps (when given).

        This should be used when you do not know if self is an Add or not but
        you want to treat self as an Add or if you want to process the
        individual arguments of the tail of self as an Add.

        - if you know self is an Add and want only the head, use self.args[0];
        - if you do not want to process the arguments of the tail but need the
          tail then use self.as_two_terms() which gives the head and tail.
        - if you want to split self into an independent and dependent parts
          use ``self.as_independent(*deps)``

        >>> from sympy import S
        >>> from sympy.abc import x, y
        >>> (S(3)).as_coeff_add()
        (3, ())
        >>> (3 + x).as_coeff_add()
        (3, (x,))
        >>> (3 + x + y).as_coeff_add(x)
        (y + 3, (x,))
        >>> (3 + y).as_coeff_add(x)
        (y + 3, ())

        r4   )has_freer   rS  )r8   r0  s     r/   as_coeff_addzExpr.as_coeff_add  s.    >  4==$'Rxvvwr1   c                    | s t         j                  t         j                  fS | j                  d      \  }}|j                  r| | }}||fS )aR  Return the positive Rational that can be extracted non-recursively
        from every term of self (i.e., self is treated like an Add). This is
        like the as_coeff_Mul() method but primitive always extracts a positive
        Rational (never a negative or a Float).

        Examples
        ========

        >>> from sympy.abc import x
        >>> (3*(x + 1)**2).primitive()
        (3, (x + 1)**2)
        >>> a = (6*x + 2); a.primitive()
        (2, 3*x + 1)
        >>> b = (x/2 + 3); b.primitive()
        (1/2, x + 6)
        >>> (a*b).primitive() == (1, a*b)
        True
        Tr   )r   rC   rS  r>   r  )r8   r*   r   s      r/   	primitivezExpr.primitive  sM    & 55!&&=   $ /1==2rqA!tr1   c                &    t         j                  | fS )a  This method should recursively remove a Rational from all arguments
        and return that (content) and the new self (primitive). The content
        should always be positive and ``Mul(*foo.as_content_primitive()) == foo``.
        The primitive need not be in canonical form and should try to preserve
        the underlying structure if possible (i.e. expand_mul should not be
        applied to self).

        Examples
        ========

        >>> from sympy import sqrt
        >>> from sympy.abc import x, y, z

        >>> eq = 2 + 2*x + 2*y*(3 + 3*y)

        The as_content_primitive function is recursive and retains structure:

        >>> eq.as_content_primitive()
        (2, x + 3*y*(y + 1) + 1)

        Integer powers will have Rationals extracted from the base:

        >>> ((2 + 6*x)**2).as_content_primitive()
        (4, (3*x + 1)**2)
        >>> ((2 + 6*x)**(2*y)).as_content_primitive()
        (1, (2*(3*x + 1))**(2*y))

        Terms may end up joining once their as_content_primitives are added:

        >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
        (11, x*(y + 1))
        >>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
        (9, x*(y + 1))
        >>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
        (1, 6.0*x*(y + 1) + 3*z*(y + 1))
        >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
        (121, x**2*(y + 1)**2)
        >>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive()
        (1, 4.84*x**2*(y + 1)**2)

        Radical content can also be factored out of the primitive:

        >>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
        (2, sqrt(2)*(1 + 2*sqrt(5)))

        If clear=False (default is True) then content will not be removed
        from an Add if it can be distributed to leave one or more
        terms with integer coefficients.

        >>> (x/2 + y).as_content_primitive()
        (1/2, x + 2*y)
        >>> (x/2 + y).as_content_primitive(clear=False)
        (1, x/2 + y)
        rF  )r8   r,  clears      r/   as_content_primitivezExpr.as_content_primitive3  s    n uud{r1   c                &    | t         j                  fS )a/  Return the numerator and the denominator of an expression.

        expression -> a/b -> a, b

        This is just a stub that should be defined by
        an object's class methods to get anything else.

        See Also
        ========

        normal: return ``a/b`` instead of ``(a, b)``

        rF  r7   s    r/   rx  zExpr.as_numer_denoml  s     QUU{r1   c                    ddl m} | j                         \  }}|t        j                  u r|S |j
                  r ||d|z        S ||z  S )zReturn the expression as a fraction.

        expression -> a/b

        See Also
        ========

        as_numer_denom: return ``(a, b)`` instead of ``a/b``

        r   r'  )r,  r(  rx  r   rC   r   )r8   r(  r   r  s       r/   normalzExpr.normal|  sJ     	*""$1:H;;#Aqs++Q3Jr1   c                	   ddl m} ddlm} t	        |      }| t
        j                  u ry|t
        j                  u r| S || k(  rt
        j                  S |j                  r3|j                         \  }}|t
        j                  urt        ||d      }|j                  r9|j                         \  }}| j                  |      }||j                  |      S |S | |z  }	| j                  rG| t
        j                  u r|j                   r't
        j                  S | t
        j"                  u r8|j$                  rt
        j                  S |j                   rt
        j"                  S | t
        j&                  u r|j(                  st
        j&                  S | j*                  r(|	j*                  sy| j                   r|	j$                  ry|	S | j,                  r(|	j,                  sy| j                   r|	j$                  ry|	S | j.                  r(|	j.                  sy| j                   r|	j$                  ry|	S yyyy| j0                  s| j2                  s| t
        j4                  u r|	j                  r^t7        |	j8                        dk(  rF|	j8                  d   j*                  rK|	j8                  d   j                   r1|	j8                  d   | k(  r|	S |	j*                  r|j                  r|	S yyyyy| j                  r| j                         \  }
}|j                  r]|t
        j:                  urK|
t
        j                  ur8|j$                  r|
j                  |        }n|
j                  |      }|||z  S y||k(  r|
S g }|j8                  D ](  }|j                  |      }| y|j=                  |       * |
t
        j                  ur|D cg c]  }|
|z  	 }} || S t?        j@                  |      S | j                  rKtC        | j8                        }tE        |      D ]'  \  }}|j                  |      }||||<   t        | c S  y| jF                  stI        | |      r{| jK                         \  }}|jK                         \  }}||k(  r |jM                  |      }|tO        ||      S y||k(  r*| j                  jM                  d      }|tO        ||      S yyyc c}w )	a  Return None if it's not possible to make self in the form
           c * something in a nice way, i.e. preserving the properties
           of arguments of self.

           Examples
           ========

           >>> from sympy import symbols, Rational

           >>> x, y = symbols('x,y', real=True)

           >>> ((x*y)**3).extract_multiplicatively(x**2 * y)
           x*y**2

           >>> ((x*y)**3).extract_multiplicatively(x**4 * y)

           >>> (2*x).extract_multiplicatively(2)
           x

           >>> (2*x).extract_multiplicatively(3)

           >>> (Rational(1, 2)*x).extract_multiplicatively(3)
           x/6

        r   )r;   r   r%  NF)r+  r   )(rs  r;   r  r&  r   r   r   rC   rI   rM  r[   rK   as_two_termsr"  r   r   r  r   r  rl  r  r   r  r   is_NumberSymbolrG  r   rN   rD   rc   r(   r%   rb   r   r  r?   rm  r;  extract_additivelyr}   )r8   r*   r;   r&  ccpcr  r  r   quotientcspsxcnewargsrQ   newargtrD   r-   sbsecbcenew_exps                           r/   r"  zExpr.extract_multiplicatively  sM   4 	?)AJ155=:K$Y55L88[[]FBB/88>>#DAq--a0A}11!44!8>>qzz!==::%+++==::%]]---***yy,,,**%%(*>*>#O!!++%%(*>*>#O((%%(*>*>#O ! ! # !> !!T^^tq7N3x}}#5#:==#..8==3C3O3OT\TaTabcTdhlTl#O$$ *5$ Um3O. [[^^%FB{{q5QUU?}}!::A2>?88;~!"uBw	Gww55a8>v&	 
 &-.g1g.'..~~g..[[		?D#D/355a8%$DG:%	 *
 [[JtS1%%'FB]]_FBRx//3&r7++ 'b((55a8&r7++ '  2 /s   Sc                   t        |      }| t        j                  u ry|j                  r| S || k(  rt        j                  S | t        j                  k(  ry| j
                  r5|j
                  sy| }||z
  }|dkD  r
|dk\  r||k  s|dk  r|dk  r||kD  r|S y|j
                  r,| j                         \  }}|j                  |      }|y||z   S |j                  r|j                  d   j
                  r| j                  |      }|j                  d      xs d|z  }|r$| ||z  z
  }||j                  |      xs |z   xs dS |j                         \  }}| j                         \  }}	|j                  |      }|y|	j                  |      }
|
y||
z   S t        | |      \  }}|j                  d      xs d|z  }|r||j                  |      xs |z   xs dS g }t        j                  |      D ]q  }|j                         \  }}| j                  |      }|s y|j                         \  }}|j                  |      }| y| ||z  z  } |j                  ||z   |z         s |j                  |        t        | S )ap  Return self - c if it's possible to subtract c from self and
        make all matching coefficients move towards zero, else return None.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> e = 2*x + 3
        >>> e.extract_additively(x + 1)
        x + 2
        >>> e.extract_additively(3*x)
        >>> e.extract_additively(4)
        >>> (y*(x + 1)).extract_additively(x + 1)
        >>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
        (x + 1)*(x + 2*y) + 3

        See Also
        ========
        extract_multiplicatively
        coeff
        as_coefficient

        Nr   r   )r   r   r   r  rS  r   as_coeff_AddrW  rI   rD   r'   r0   r%   r&   r>   r(   )r8   r*   r+   r  r`  xaxa0hshstxa2coeffsr  acatcoccots                    r/   rW  zExpr.extract_additively	  s   2 AJ155=99K$Y66MQVV^>>;;B6DQ419FtqyTBY;;%%'EB&&q)Bz6M
 88q	++AB((+0q!3Cbd{t66q9ATBKtK>>#DAq&&(FB&&q)Bz''*C{8O $?D$$Q',1a/42215=>G4Gq!A^^%FBBB(HC''+BzBrEMDMM38R-( " 	dF|r1   c                    t        ddd       | j                  D ch c]  }|j                  D ]  }|  c}}S c c}}w )a0  
        Like ``free_symbols``, but returns the free symbols only if
        they are contained in an expression node.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> (x + y).expr_free_symbols # doctest: +SKIP
        {x, y}

        If the expression is contained in a non-expression object, do not return
        the free symbols. Compare:

        >>> from sympy import Tuple
        >>> t = Tuple(x + y)
        >>> t.expr_free_symbols # doctest: +SKIP
        set()
        >>> t.free_symbols
        {x, y}
        
        The expr_free_symbols property is deprecated. Use free_symbols to get
        the free symbols of an expression.
        1.9deprecated-expr-free-symbolsdeprecated_since_versionactive_deprecations_target)r   rD   expr_free_symbols)r8   r-   r  s      r/   rz  zExpr.expr_free_symbolsw	  sG    . 	" # &+'E	G  99B9aa.A.A.A9BBBs   <c                     y)a  Return True if self has -1 as a leading factor or has
        more literal negative signs than positive signs in a sum,
        otherwise False.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> e = x - y
        >>> {i.could_extract_minus_sign() for i in (e, -e)}
        {False, True}

        Though the ``y - x`` is considered like ``-(x - y)``, since it
        is in a product without a leading factor of -1, the result is
        false below:

        >>> (x*(y - x)).could_extract_minus_sign()
        False

        To put something in canonical form wrt to sign, use `signsimp`:

        >>> from sympy import signsimp
        >>> signsimp(x*(y - x))
        -x*(x - y)
        >>> _.could_extract_minus_sign()
        True
        Fr4   r7   s    r/   could_extract_minus_signzExpr.could_extract_minus_sign	  s    8 r1   c                V   ddl m} ddlm} t        j
                  }t        j                  }t        j                  |       }g }|D ]$  }t        ||      r||j                  gz  } ||z  }& t        j
                  }	g }
t        j                  t        j                  z  }|rZ|j                         }|j                  r||j                  z  }.|j                   r|j#                  |      }||	|z  }	S|
|gz  }
|rZ|	j$                  r|	}d}n |	j&                  |	j(                   \  }} ||dz  t        j*                  z
        dz  }||dz  z  }||z
  }|r(|j-                  d      }||t        j*                  z  }|}|t/        |f|z    z  t/        |
 z   }|dk7  r| ||      z  }||fS )ac  
        Try to write self as ``exp_polar(2*pi*I*n)*z`` in a nice way.
        Return (z, n).

        >>> from sympy import exp_polar, I, pi
        >>> from sympy.abc import x, y
        >>> exp_polar(I*pi).extract_branch_factor()
        (exp_polar(I*pi), 0)
        >>> exp_polar(2*I*pi).extract_branch_factor()
        (1, 1)
        >>> exp_polar(-pi*I).extract_branch_factor()
        (exp_polar(I*pi), -1)
        >>> exp_polar(3*pi*I + x).extract_branch_factor()
        (exp_polar(x + I*pi), 1)
        >>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
        (y*exp_polar(2*pi*x), -1)
        >>> exp_polar(-I*pi/2).extract_branch_factor()
        (exp_polar(-I*pi/2), 0)

        If allow_half is True, also extract exp_polar(I*pi):

        >>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
        (1, 1/2)
        >>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
        (1, 1)
        >>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
        (1, 3/2)
        >>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
        (1, -1/2)
        r   )	exp_polarceilingr4   r   r   )rs  r~  r   r  r   rS  rC   r[   r&   rm  r;   Pir   r  rI   rD   rK   r#  r   rK  r   HalfrW  r%   )r8   
allow_halfr~  r  r   resrD   expsrQ   piimultextrasipir;   r'   tail
branchfactr*   r  newexps                      r/   extract_branch_factorzExpr.extract_branch_factor	  s   > 	E?FFee}}T"C#y)	!s
	 
 &&dd1??"((*Czz zz**3/$u$GseOF  ED.'..0D0DEKE4U1Wqvv-.q0
	Z\J%%a(B~QVVSA54<))CL8Q;9V$$CAvr1   c                z    |rt        t        t        |            }n| j                  }|sy| j	                  |      S )a  
        Return True if self is a polynomial in syms and False otherwise.

        This checks if self is an exact polynomial in syms.  This function
        returns False for expressions that are "polynomials" with symbolic
        exponents.  Thus, you should be able to apply polynomial algorithms to
        expressions for which this returns True, and Poly(expr, \*syms) should
        work if and only if expr.is_polynomial(\*syms) returns True. The
        polynomial does not have to be in expanded form.  If no symbols are
        given, all free symbols in the expression will be used.

        This is not part of the assumptions system.  You cannot do
        Symbol('z', polynomial=True).

        Examples
        ========

        >>> from sympy import Symbol, Function
        >>> x = Symbol('x')
        >>> ((x**2 + 1)**4).is_polynomial(x)
        True
        >>> ((x**2 + 1)**4).is_polynomial()
        True
        >>> (2**x + 1).is_polynomial(x)
        False
        >>> (2**x + 1).is_polynomial(2**x)
        True
        >>> f = Function('f')
        >>> (f(x) + 1).is_polynomial(x)
        False
        >>> (f(x) + 1).is_polynomial(f(x))
        True
        >>> (1/f(x) + 1).is_polynomial(f(x))
        False

        >>> n = Symbol('n', nonnegative=True, integer=True)
        >>> (x**n + 1).is_polynomial(x)
        False

        This function does not attempt any nontrivial simplifications that may
        result in an expression that does not appear to be a polynomial to
        become one.

        >>> from sympy import sqrt, factor, cancel
        >>> y = Symbol('y', positive=True)
        >>> a = sqrt(y**2 + 2*y + 1)
        >>> a.is_polynomial(y)
        False
        >>> factor(a)
        y + 1
        >>> factor(a).is_polynomial(y)
        True

        >>> b = (y**2 + 2*y + 1)/(y + 1)
        >>> b.is_polynomial(y)
        False
        >>> cancel(b)
        y + 1
        >>> cancel(b).is_polynomial(y)
        True

        See also .is_rational_function()

        T)r  mapr   r   _eval_is_polynomialr8   r  s     r/   is_polynomialzExpr.is_polynomial
  s;    B s7D)*D$$D''--r1   c                .    | |v ry | j                   | syy NTrJ  r  s     r/   r  zExpr._eval_is_polynomialK
  s"    4<t}}d# $r1   c                    |rt        t        t        |            }n| j                  }|s| t        vS | j                  |      S )a	  
        Test whether function is a ratio of two polynomials in the given
        symbols, syms. When syms is not given, all free symbols will be used.
        The rational function does not have to be in expanded or in any kind of
        canonical form.

        This function returns False for expressions that are "rational
        functions" with symbolic exponents.  Thus, you should be able to call
        .as_numer_denom() and apply polynomial algorithms to the result for
        expressions for which this returns True.

        This is not part of the assumptions system.  You cannot do
        Symbol('z', rational_function=True).

        Examples
        ========

        >>> from sympy import Symbol, sin
        >>> from sympy.abc import x, y

        >>> (x/y).is_rational_function()
        True

        >>> (x**2).is_rational_function()
        True

        >>> (x/sin(y)).is_rational_function(y)
        False

        >>> n = Symbol('n', integer=True)
        >>> (x**n + 1).is_rational_function(x)
        False

        This function does not attempt any nontrivial simplifications that may
        result in an expression that does not appear to be a rational function
        to become one.

        >>> from sympy import sqrt, factor
        >>> y = Symbol('y', positive=True)
        >>> a = sqrt(y**2 + 2*y + 1)/y
        >>> a.is_rational_function(y)
        False
        >>> factor(a)
        (y + 1)/y
        >>> factor(a).is_rational_function(y)
        True

        See also is_algebraic_expr().

        )r  r  r   r   _illegal_eval_is_rational_functionr  s     r/   is_rational_functionzExpr.is_rational_functionS
  sC    f s7D)*D$$D8++..t44r1   c                2    | |v ry| j                  |      syy r  )	has_xfreer  s     r/   r  zExpr._eval_is_rational_function
  s     4<~~d# $r1   c                    |j                   st        dj                  |            t        |      }| j	                  ||      S )a  
        This tests whether an expression is meromorphic as
        a function of the given symbol ``x`` at the point ``a``.

        This method is intended as a quick test that will return
        None if no decision can be made without simplification or
        more detailed analysis.

        Examples
        ========

        >>> from sympy import zoo, log, sin, sqrt
        >>> from sympy.abc import x

        >>> f = 1/x**2 + 1 - 2*x**3
        >>> f.is_meromorphic(x, 0)
        True
        >>> f.is_meromorphic(x, 1)
        True
        >>> f.is_meromorphic(x, zoo)
        True

        >>> g = x**log(3)
        >>> g.is_meromorphic(x, 0)
        False
        >>> g.is_meromorphic(x, 1)
        True
        >>> g.is_meromorphic(x, zoo)
        False

        >>> h = sin(1/x)*x**2
        >>> h.is_meromorphic(x, 0)
        False
        >>> h.is_meromorphic(x, 1)
        True
        >>> h.is_meromorphic(x, zoo)
        True

        Multivalued functions are considered meromorphic when their
        branches are meromorphic. Thus most functions are meromorphic
        everywhere except at essential singularities and branch points.
        In particular, they will be meromorphic also on branch cuts
        except at their endpoints.

        >>> log(x).is_meromorphic(x, -1)
        True
        >>> log(x).is_meromorphic(x, 0)
        False
        >>> sqrt(x).is_meromorphic(x, -1)
        True
        >>> sqrt(x).is_meromorphic(x, 0)
        False

        z{} should be of symbol type)	is_symbolr   r   r   _eval_is_meromorphicr8   r   r  s      r/   is_meromorphiczExpr.is_meromorphic
  s?    n {{9@@CDDAJ((A..r1   c                4    | |k(  ry| j                  |      syy r  r  r  s      r/   r  zExpr._eval_is_meromorphic
  s     19}}Q  r1   c                z    |rt        t        t        |            }n| j                  }|sy| j	                  |      S )a
  
        This tests whether a given expression is algebraic or not, in the
        given symbols, syms. When syms is not given, all free symbols
        will be used. The rational function does not have to be in expanded
        or in any kind of canonical form.

        This function returns False for expressions that are "algebraic
        expressions" with symbolic exponents. This is a simple extension to the
        is_rational_function, including rational exponentiation.

        Examples
        ========

        >>> from sympy import Symbol, sqrt
        >>> x = Symbol('x', real=True)
        >>> sqrt(1 + x).is_rational_function()
        False
        >>> sqrt(1 + x).is_algebraic_expr()
        True

        This function does not attempt any nontrivial simplifications that may
        result in an expression that does not appear to be an algebraic
        expression to become one.

        >>> from sympy import exp, factor
        >>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1)
        >>> a.is_algebraic_expr(x)
        False
        >>> factor(a).is_algebraic_expr()
        True

        See Also
        ========

        is_rational_function

        References
        ==========

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

        T)r  r  r   r   _eval_is_algebraic_exprr  s     r/   is_algebraic_exprzExpr.is_algebraic_expr
  s;    V s7D)*D$$D++D11r1   c                .    | |v ry | j                   | syy r  r  r  s     r/   r  zExpr._eval_is_algebraic_expr  s"    4<t}}d# $r1   r   c           	     
   9| j                   }|s| S t        |      dkD  rt        d      |j                         ddlm}m}	 t        |	      r| j                   v }
n& |       }|| j                  |i      j                   v }
|
s|
d | fD        S | S t        |      dk7  s|dvrt        d      t              t              ddl
m}m} j                  s4j                  rj                  rd	nd
}n |      j                  rd	nd
}nr#j                   r |      j#                         nat%        |      d	k(  rt&        j(                  nBt%        |      d
k(  rt&        j*                  n#t&        j,                  k(  rt&        j(                  t/              z  r^j                   rRddlm} 	 | j5                  z        j7                  |d	d      }|fd|D        S |j5                  z        S sdk7  rY| j5                  z  z   i      j7                  d|d	|d      }|fd|D        S |j5                  z  z  z
  i      S j                  j:                  cxu rn j<                  durQ |dd      | j5                        j7                  |||      }|fd|D        S |j5                        S ddlm  || jC                  ||      }|jE                         xs t&        j,                  }|rL|jG                         }||kD  r5|dk7  r#||j5                  tI        ||      z        z  }n| d      z  }n||k  rddl%m&} tO        dd      D ]  }| jC                  ||z   |      }|jG                         }||k7  s1| |||z
  |z  ||z
  z        z   }| jC                  ||      }|jG                         |k  r.| jC                  ||      }|dz  }|jG                         |k  r. n t        dt%        |      d|       | |z        z  }|jE                         }|jQ                         }nV|jS                        r|S  |z        }|jU                         }	 ||z   jQ                         |k(  rt&        j,                  }	 ddl,m-}  ||      |z   S fd} || jQ                         j]                  |            S # |$ r> | j5                  z        j9                  |      }|j5                  z        cY S w xY w# tV        $ r |cY S w xY w# tV        $ r ||z   cY S w xY w)a  
        Series expansion of "self" around ``x = x0`` yielding either terms of
        the series one by one (the lazy series given when n=None), else
        all the terms at once when n != None.

        Returns the series expansion of "self" around the point ``x = x0``
        with respect to ``x`` up to ``O((x - x0)**n, x, x0)`` (default n is 6).

        If ``x=None`` and ``self`` is univariate, the univariate symbol will
        be supplied, otherwise an error will be raised.

        Parameters
        ==========

        expr : Expression
               The expression whose series is to be expanded.

        x : Symbol
            It is the variable of the expression to be calculated.

        x0 : Value
             The value around which ``x`` is calculated. Can be any value
             from ``-oo`` to ``oo``.

        n : Value
            The value used to represent the order in terms of ``x**n``,
            up to which the series is to be expanded.

        dir : String, optional
              The series-expansion can be bi-directional. If ``dir="+"``,
              then (x->x0+). If ``dir="-", then (x->x0-). For infinite
              ``x0`` (``oo`` or ``-oo``), the ``dir`` argument is determined
              from the direction of the infinity (i.e., ``dir="-"`` for
              ``oo``).

        logx : optional
               It is used to replace any log(x) in the returned series with a
               symbolic value rather than evaluating the actual value.

        cdir : optional
               It stands for complex direction, and indicates the direction
               from which the expansion needs to be evaluated.

        Examples
        ========

        >>> from sympy import cos, exp, tan
        >>> from sympy.abc import x, y
        >>> cos(x).series()
        1 - x**2/2 + x**4/24 + O(x**6)
        >>> cos(x).series(n=4)
        1 - x**2/2 + O(x**4)
        >>> cos(x).series(x, x0=1, n=2)
        cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1))
        >>> e = cos(x + exp(y))
        >>> e.series(y, n=2)
        cos(x + 1) - y*sin(x + 1) + O(y**2)
        >>> e.series(x, n=2)
        cos(exp(y)) - x*sin(exp(y)) + O(x**2)

        If ``n=None`` then a generator of the series terms will be returned.

        >>> term=cos(x).series(n=None)
        >>> [next(term) for i in range(2)]
        [1, -x**2/2]

        For ``dir=+`` (default) the series is calculated from the right and
        for ``dir=-`` the series from the left. For smooth functions this
        flag will not alter the results.

        >>> abs(x).series(dir="+")
        x
        >>> abs(x).series(dir="-")
        -x
        >>> f = tan(x)
        >>> f.series(x, 2, 6, "+")
        tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) +
        (x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 +
        5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 +
        2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))

        >>> f.series(x, 2, 3, "-")
        tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2))
        + O((x - 2)**3, (x, 2))

        For rational expressions this method may return original expression without the Order term.
        >>> (1/x).series(x, n=8)
        1/x

        Returns
        =======

        Expr : Expression
            Series expansion of the expression about x0

        Raises
        ======

        TypeError
            If "n" and "x0" are infinity objects

        PoleError
            If "x0" is an infinity object

        r   z+x must be given for multivariate functions.r  c              3      K   | ]  }|  y wr$   r4   )r   r9  s     r/   r   zExpr.series.<locals>.<genexpr>  s     *6a6s   z+-zDir must be '+' or '-'r   )r   signrj  rk  	PoleError)r   r  r  c              3  H   K   | ]  }|j                  z          y wr$   r   )r   r2  r  r   s     r/   r   zExpr.series.<locals>.<genexpr>  s!     ;2BGGAtAv.s   ")r   )x0r   r  logxr  c              3  V   K   | ]   }|j                  z  z  z
  i       " y wr$   r   )r   r2  r  r   r  s     r/   r   zExpr.series.<locals>.<genexpr>  s-     C2AdFRW$4 56s   &)Tr   r[  r  r  c              3  B   K   | ]  }|j                          y wr$   r   )r   r9  r   xposs     r/   r   zExpr.series.<locals>.<genexpr>  s     4AtQs   Orderr   r  r  r  	   zCould not calculate z terms for collectc              3  P  K   | D ]  }|j                   s| d} |      z  }d}t        |j                        }	 ||z
  |z   j                         }|z  }|r|j                  r+|j                   r|t        |j                        z  }n|dz  }| ||k(  r||z  }d yw)z&Return terms of lseries one at a time.r   r   N)rI   rN   rD   r  r  )	r9  r2  yieldedr  ndidndodor  r   s	          r/   yield_lseriesz"Expr.series.<locals>.yield_lseries  s     B99    Gb!QADbgg,C 7lQ.779Q!R[[$99 CL0D AID 3;!2  s   B#B&)/r   rN   r   r  r  r  r  rm  xreplacer   rh   r   r  r  rE  r  r  r  rH   r   rC   rc   rS  r   r  r  r   seriesaseriesr  rG  sympy.series.orderr  _eval_nseriesr  r  Rationalr   r  r  r  r?  doitrF  sympy.simplify.radsimpr  _eval_lseries)r8   r   r  r   r  r  r  r  r  r  rB  r  r   r  r  r9  r  s1r  ngotr  morenewnr  s1doner  r  r  r  s    ``   `                    @@r/   r  zExpr.series  s@   T 9$$DTQ !NOO
A)a t(((CAt}}aV,999Cy*D6**s8q=CtO566R[t}A||||!--c3X11csbnnBx((*SSuuSS}}uuCI~"..+)IIaa(//QCa/H9;;;vvaa(( 		1b46k*+221aStZ[2\AyCCC661afr$w./00 ==AMM1Q[[5Lt,D1d#**4Q$T*RBy444wwtQ'',=##AD#AB	#QVVAvvx!8 AvaffQ8At+<(<==eAqk)AX
 L %a!//QXDt/T!wwy4<"#gq4xotd{.K&L"LC!%!3!3A4d!3!SB"$'')a-%)%7%7StRV%7%W #q #%'')a- " !, ),/FD*: ; ;%1a.(BGGIZZ\	!Q$N
++-7FF:r1~))
&6 !!=!=adQU!=!VWWS  )IIaa(00a08vvaa(()H + I ' Avs=   >5T 4T $&U U" A UUUU"U32U3c                z   ddl m} |j                  |j                  cxu rAn n> |dd      }| j	                  ||      j                  ||||      j	                  ||      S ddlm} ddlm	}m
}	 	  || |      \  }
}dd	lm}m} dd
lm} ||
v rt| j	                  | ||            j                  ||||      j	                  | ||            }|j!                         r"| |d||z  z  |t"        j$                  f      z   S |S  |dd       |	||
|      \  }}| |
v r|dk  r| S | j                  j                  |||      } |j&                  |j(                  D cg c]  }|j+                          c} }	  ||j	                  |d|z        j-                  |      j	                  |d|z              } || j(                  d   |j(                  d   z
        z  } |d|z        }|j/                  d|      }|r|j	                   ||            S |j!                         }t1        t3        j4                  |j+                               fd      }t"        j6                  }d}|D ]u  }|j9                        \  }}|j;                  |      rI|j                  |||dz
        }|r|j!                         r n%|j!                         rd}|||z  z  z  }q||z  }w |r|r|j	                   ||            S ||z   j	                   ||            S # |$ r | cY S w xY wc c}w # |$ r | }Y w xY w)a  Asymptotic Series expansion of self.
        This is equivalent to ``self.series(x, oo, n)``.

        Parameters
        ==========

        self : Expression
               The expression whose series is to be expanded.

        x : Symbol
            It is the variable of the expression to be calculated.

        n : Value
            The value used to represent the order in terms of ``x**n``,
            up to which the series is to be expanded.

        hir : Boolean
              Set this parameter to be True to produce hierarchical series.
              It stops the recursion at an early level and may provide nicer
              and more useful results.

        bound : Value, Integer
                Use the ``bound`` parameter to give limit on rewriting
                coefficients in its normalised form.

        Examples
        ========

        >>> from sympy import sin, exp
        >>> from sympy.abc import x

        >>> e = sin(1/x + exp(-x)) - sin(1/x)

        >>> e.aseries(x)
        (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)

        >>> e.aseries(x, n=3, hir=True)
        -exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))

        >>> e = exp(exp(x)/(1 - 1/x))

        >>> e.aseries(x)
        exp(exp(x)/(1 - 1/x))

        >>> e.aseries(x, bound=3) # doctest: +SKIP
        exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))

        For rational expressions this method may return original expression without the Order term.
        >>> (1/x).aseries(x, n=8)
        1/x

        Returns
        =======

        Expr
            Asymptotic series expansion of the expression.

        Notes
        =====

        This algorithm is directly induced from the limit computational algorithm provided by Gruntz.
        It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first
        to look for the most rapidly varying subexpression w of a given expression f and then expands f
        in a series in w. Then same thing is recursively done on the leading coefficient
        till we get constant coefficients.

        If the most rapidly varying subexpression of a given expression f is f itself,
        the algorithm tries to find a normalised representation of the mrv set and rewrites f
        using this normalised representation.

        If the expansion contains an order term, it will be either ``O(x ** (-n))`` or ``O(w ** (-n))``
        where ``w`` belongs to the most rapidly varying expression of ``self``.

        References
        ==========

        .. [1] Gruntz, Dominik. A new algorithm for computing asymptotic series.
               In: Proc. 1993 Int. Symp. Symbolic and Algebraic Computation. 1993.
               pp. 239-244.
        .. [2] Gruntz thesis - p90
        .. [3] https://en.wikipedia.org/wiki/Asymptotic_expansion

        See Also
        ========

        Expr.aseries: See the docstring of this function for complete details of this wrapper.
        r   r  r   Tr[  r  r   )mrvrewrite)r;   rd  r  r  )boundc                >    t        | j                        d         S )Nr   )r   as_coeff_exponent)r-   r  s    r/   r.  zExpr.aseries.<locals>.<lambda>  s    QEXEXYZE[\]E^A_r1   r/  F)r  r  r  r  r   r  r  r  sympy.series.gruntzr  r  rs  r;   rd  r  r  r  r   r   r-  rD   r  as_leading_termr  r  r%   r&   rS  r  r?  )r8   r   r   r  hirr  r  r  r  r  omr  r;   rd  r  r9  r-  logwr`  r  r  r  has_ordr'   exposnewr  s                             @r/   r  zExpr.aseries!  s   r 	"==AMM1t,D99Q%--dAucBGGaPP'4	4|HB 	D,7		!SV$,,Q5#>CCAs1vNAvvx51a4!QZZ999H#%T2q!,
d2:z""1au"5Aaff5ff56A!&&AaC.88;@@AaCHI tyy|chhqk12Q6Dqu:DKK1a  66!SY''FFHs}}QYY[17_`FF A--a0KE4yy|}}Qq}9tyy{YY["GdQWn%Q  G66!SY''A||As4y)){  	K	0 6  s*   3L  L*<=L/ L'&L'/L:9L:c                    ddl m} ddlm} t	        |      } |d      }| j                  ||      j                  ||      j                  ||      j                  |d      ||z  z   ||      z  S )zGeneral method for the taylor term.

        This method is slow, because it differentiates n-times. Subclasses can
        redefine it to make it faster by using the "previous_terms".
        r   r  r   )	factorialr   )r  r  (sympy.functions.combinatorial.factorialsr  r   r   r  )r8   r   r   previous_termsr  r  _xs          r/   taylor_termzExpr.taylor_term  sg     	"FAJ3ZyyB$$R+00Q7<<QBQTIIVWLXXr1   c                0    | j                  ||d|||      S )a  
        Wrapper for series yielding an iterator of the terms of the series.

        Note: an infinite series will yield an infinite iterator. The following,
        for exaxmple, will never terminate. It will just keep printing terms
        of the sin(x) series::

          for term in sin(x).lseries(x):
              print term

        The advantage of lseries() over nseries() is that many times you are
        just interested in the next term in the series (i.e. the first term for
        example), but you do not know how many you should ask for in nseries()
        using the "n" parameter.

        See also nseries().
        N)r   r  r  r  )r  )r8   r   r  r  r  r  s         r/   lserieszExpr.lseries  s    $ {{1bDc4{HHr1   c              #    K   d}| j                  ||||      }|j                  r'|dz  }| j                  ||||      }|j                  r'|j                         }| |t        j                  u ry 	 	 |dz  }| j                  ||||      j                         }||k7  rn%|| z
  j                         t        j                  u ry S||z
   |}^w)Nr   r  r   )r  r  r  r   rS  rw  )r8   r   r  r  r   r  r  s          r/   r  zExpr._eval_lseries  s      ##AD#AooFA''QT'EF oo NN;Q++AD+IQQS;TM))+qvv5  1*A s   A
CBCc                    |r|| j                   vr| S ||s|dk7  r| j                  |||||      S | j                  ||||      S )a  
        Wrapper to _eval_nseries if assumptions allow, else to series.

        If x is given, x0 is 0, dir='+', and self has x, then _eval_nseries is
        called. This calculates "n" terms in the innermost expressions and
        then builds up the final series just by "cross-multiplying" everything
        out.

        The optional ``logx`` parameter can be used to replace any log(x) in the
        returned series with a symbolic value to avoid evaluating log(x) at 0. A
        symbol to use in place of log(x) should be provided.

        Advantage -- it's fast, because we do not have to determine how many
        terms we need to calculate in advance.

        Disadvantage -- you may end up with less terms than you may have
        expected, but the O(x**n) term appended will always be correct and
        so the result, though perhaps shorter, will also be correct.

        If any of those assumptions is not met, this is treated like a
        wrapper to series which will try harder to return the correct
        number of terms.

        See also lseries().

        Examples
        ========

        >>> from sympy import sin, log, Symbol
        >>> from sympy.abc import x, y
        >>> sin(x).nseries(x, 0, 6)
        x - x**3/6 + x**5/120 + O(x**6)
        >>> log(x+1).nseries(x, 0, 5)
        x - x**2/2 + x**3/3 - x**4/4 + O(x**5)

        Handling of the ``logx`` parameter --- in the following example the
        expansion fails since ``sin`` does not have an asymptotic expansion
        at -oo (the limit of log(x) as x approaches 0):

        >>> e = sin(log(x))
        >>> e.nseries(x, 0, 6)
        Traceback (most recent call last):
        ...
        PoleError: ...
        ...
        >>> logx = Symbol('logx')
        >>> e.nseries(x, 0, 6, logx=logx)
        sin(logx)

        In the following example, the expansion works but only returns self
        unless the ``logx`` parameter is used:

        >>> e = x**y
        >>> e.nseries(x, 0, 2)
        x**y
        >>> e.nseries(x, 0, 2, logx=logx)
        exp(logx*y)

        rj  )r  r  )r   r  r  )r8   r   r  r   r  r  r  s          r/   nserieszExpr.nseries  sZ    x $+++K9cSj;;q"a4;88%%a14d%CCr1   c                D    t        t        d| j                  z              )aA  
        Return terms of series for self up to O(x**n) at x=0
        from the positive direction.

        This is a method that should be overridden in subclasses. Users should
        never call this method directly (use .nseries() instead), so you do not
        have to write docstrings for _eval_nseries().
        z
                     The _eval_nseries method should be added to
                     %s to give terms up to O(x**n) at x=0
                     from the positive direction so it is available when
                     nseries calls it.)rF  r   r-  r8   r   r   r  r  s        r/   r  zExpr._eval_nseriesF  s+     "* .* -1II	.6 #7  	r1   c                $    ddl m}  || |||      S )z  Compute limit x->xlim.
        r   )re  )rt  re  )r8   r   xlimr  re  s        r/   re  z
Expr.limitV  s     	.T1dC((r1   c                8   ddl m}  |dddd      j                          ddlm}m} | j                  |      r	 ||       }n| }| j                         dk(  r| S d	d
lm	} ddl
m} ddlm}	 |}
| |d      n|} |	d	      }t        j                  }|j                   rS|j#                  |d	|z   |      j%                         j'                         j)                         }|dz  }|j                   rS|
|j+                  | ||            }|j-                  |      S )zDeprecated function to compute the leading term of a series.

        as_leading_term is only allowed for results of .series()
        This is a wrapper to compute a series first.
        r   )SymPyDeprecationWarningcompute_leading_termr  iSU  z1.12)feature
useinsteadissuerx  )	Piecewisepiecewise_foldr   r  rc  r  r  )r   r  r   )sympy.utilities.exceptionsr  r  $sympy.functions.elementary.piecewiser  r  r?  r  r  r  rs  rd  r  r  r   rC   r  r  rw  powsimptrigsimpr   r  )r8   r   r  r  r  r  rP   r  rd  r  _logxr  incrs                r/   r  zExpr.compute_leading_term\  s     	G*(%+		

 $&R88I!$'DD<<>QK!>, $uV}$Ahuull$$Q!D&t$<CCEMMOXXZCAID ll =((4Q(C""1%%r1   r  c               F   t        |      dkD  r| }|D ]  }|j                  |||      } |S |s| S t        |d         }|j                  st	        d|z        || j
                  vr| S | j                  |||      }|ddlm}  ||dd      S t        d	| d
|d      )a  
        Returns the leading (nonzero) term of the series expansion of self.

        The _eval_as_leading_term routines are used to do this, and they must
        always return a non-zero value.

        Examples
        ========

        >>> from sympy.abc import x
        >>> (1 + x + x**2).as_leading_term(x)
        1
        >>> (1/x**2 + x + x**2).as_leading_term(x)
        x**(-2)

        r   r  r   zexpecting a Symbol but got %sr  Tr;   )r7  combinezas_leading_term(, ))
rN   r  r   r  r   r   _eval_as_leading_termsympy.simplify.powsimpr  rF  )r8   r  r  symbolsr*   r   r   r  s           r/   r  zExpr.as_leading_term  s    $ w<!A%%ad%> HKGAJ{{<q@AAD%%%K((D(A?63T599!tQ"GHHr1   c                    | S r$   r4   )r8   r   r  r  s       r/   r  zExpr._eval_as_leading_term  r_   r1   c                    ddl m}  || |      }|j                  |      \  }}t        |      dk(  r|d   j	                         \  }}||k(  r||fS |t
        j                  fS )zC ``c*x**e -> c,e`` where x can be any symbolic expression.
        r   r  r   )r  r  r@  rN   r;  r   rS  )r8   r   r  r9  r*   pr  r  s           r/   r  zExpr.as_coeff_exponent  sd     	3D!~~a 1q6Q;Q4##%DAqAv!t!&&yr1   c                l   ddl m} ddlm} | j	                  |||      } |d      }|j                   ||            r|j                   ||      |      }|j                  |      \  }}	||j                  v r t        t        d| d|d	|d
|            |j                  | ||            }||	fS )z
        Returns the leading term a*x**b as a tuple (a, b).

        Examples
        ========

        >>> from sympy.abc import x
        >>> (1+x+x**2).leadterm(x)
        (1, 0)
        >>> (1/x**2+x+x**2).leadterm(x)
        (1, -2)

        r   r  r   rc  r  r  z)
                cannot compute leadterm(r  z<). The coefficient
                should have been free of z	 but got )r  r  rs  rd  r  r?  r   r  r   r   r   )
r8   r   r  r  r  rd  r  r  r*   r  s
             r/   r  zExpr.leadterm  s     	">  D 9&M55Q=s1vq!A""1%1Z=A1a)L M N N FF1c!f!tr1   c                &    t         j                  | fS )z1Efficiently extract the coefficient of a product.rF  r8   r   s     r/   r>   zExpr.as_coeff_Mul  s    uud{r1   c                &    t         j                  | fS )z3Efficiently extract the coefficient of a summation.)r   rS  r  s     r/   rg  zExpr.as_coeff_Add  s    vvt|r1   c           
     ,    ddl m}  || |||||||      S )z
        Compute formal power power series of self.

        See the docstring of the :func:`fps` function in sympy.series.formal for
        more information.
        r   )fps)sympy.series.formalr  )	r8   r   r  r  hyperr=   r   fullr  s	            r/   r  zExpr.fps  s      	,4BUE8TBBr1   c                     ddl m}  || |      S )zCompute fourier sine/cosine series of self.

        See the docstring of the :func:`fourier_series` in sympy.series.fourier
        for more information.
        r   )fourier_series)sympy.series.fourierr  )r8   limitsr  s      r/   r  zExpr.fourier_series  s     	8dF++r1   c                D    |j                  dd       t        | g|i |S )Nr+  T)
setdefault_derivative_dispatch)r8   r  assumptionss      r/   r  z	Expr.diff  s'    z40#DB7BkBBr1   c                X     | j                   di |\  }}|t        j                  |z  z   S )Nr4   )r   r   r   )r8   r8  r  r  s       r/   _eval_expand_complexzExpr._eval_expand_complex   s/    &T&&//
daood***r1   c                :   d}|rmt        | dd      r`| j                  sTg }| j                  D ]2  }t        j                  ||fi |\  }}||z  }|j                  |       4 |r | j                  | } t        | |      r t        | |      di |}|| k7  r|dfS | |fS )a  
        Helper for ``expand()``.  Recursively calls ``expr._eval_expand_hint()``.

        Returns ``(expr, hit)``, where expr is the (possibly) expanded
        ``expr`` and ``hit`` is ``True`` if ``expr`` was truly expanded and
        ``False`` otherwise.
        FrD   r4   T)rR  rG   rD   r3   _expand_hintr(   r-  r   )	rP   r1  r7  r8  r  sargsrQ   arghitnewexprs	            r/   r  zExpr._expand_hint  s      GD&"-dllEyy"//TCUCVvS! !
  tyy%(4)gdD)2E2G$&c{r1   c	           	     z  	 ddl m 	j                  ||||||       | }
	fd}	j                  dd      r1 ||       D cg c]  } |j                  d||d	 c}\  }}||z  S 	j                  dd      r# ||       \  }}| |j                  d||d	z  S 	j                  d	d      r# ||       \  }} |j                  d||d	|z  S d
 }t        	j                         |      D ]+  }	|   }|sd|z   }t        j                  |
|fd|i	\  }
}- 	 |
}	j                  dd      rt        j                  |
dfd|i	\  }
}	j                  dd      rt        j                  |
dfd|i	\  }
}	j                  dd      rt        j                  |
dfd|i	\  }
}|
|k(  rn|t        |      }|j                  r|dk  rt        d|z        g }t        j                  |
      D ]3  }|j                  d      \  }}||z  }|s |j!                  ||z         5 t        | }
|
S c c}w )z
        Expand an expression using hints.

        See the docstring of the expand() function in sympy.core.function for
        more information.

        r   )fraction)
power_base	power_expr,  rd  multinomialbasicc                6     | j                  dd            S )NexactF)r  )r   r  r8  s    r/   r.  zExpr.expand.<locals>.<lambda>3  s    hq%))GU*CDr1   fracF)r7  modulusr   numerc                    | dk(  ry| S )z Make multinomial come before mulr,  mulzr4   )r1  s    r/   _expand_hint_keyz%Expr.expand.<locals>._expand_hint_keyO  s    u}Kr1   r/  _eval_expand_r7  Tr  _eval_expand_multinomialr,  _eval_expand_mulrd  _eval_expand_logz*modulus must be a positive integer, got %sr   r4   )r  r  r:  r  expandr  keysr3   r  r  r   r   r   r%   r&   r>   r(   )r8   r7  r#  r  r  r,  rd  r  r  r8  rP   	_fractionr  r   r  r'  r1  use_hintr  wasr  r  r  r'   r  r  s            `               @r/   r,  zExpr.expand"  s    	4
iS5 	 	: D	99VU#&t_., AHHA$A5A,.DAqQ3JYYw&T?DAqXQXXB4BEBBBYYw&T?DAq188@w@%@BB$	 5::<-=>DT{H&- --dDMtMuM	c	 ? Cyy.++4J;?JCHJayy&++,B37B;@Bayy&++,B37B;@Bas{  g&G%%A @7JL L Ed+"///>t LLt, , ;DO.s   H8c                &    ddl m}  || g|i |S )z-See the integrate function in sympy.integralsr   )	integrate)sympy.integrals.integralsr2  )r8   rD   rH  r2  s       r/   r2  zExpr.integrate  s    7////r1   c                $    ddl m}  || |||      S )z,See the nsimplify function in sympy.simplifyr   )r&  )r;  r&  )r8   	constants	tolerancer
  r&  s        r/   r&  zExpr.nsimplify  s    5y)T::r1   c                $    ddl m}  || ||      S )z+See the separate function in sympy.simplifyr   )expand_power_base)r7  force)r  r8  )r8   r7  r9  r8  s       r/   separatezExpr.separate  s    / D>>r1   c                (    ddl m}  || |||||      S )z*See the collect function in sympy.simplifyr   r  )r  r  )r8   r  r-  r+  r!  distribute_order_termr  s          r/   r  zExpr.collect  s    2tT45:OPPr1   c                &    ddl m}  || g|i |S )z(See the together function in sympy.polysr   )together)sympy.polys.rationaltoolsr>  )r8   rD   rH  r>  s       r/   r>  zExpr.together  s    6.t.v..r1   c                "    ddl m}  || |fi |S )z%See the apart function in sympy.polysr   )apart)sympy.polys.partfracrA  )r8   r   rD   rA  s       r/   rA  z
Expr.apart  s    .T1%%%r1   c                    ddl m}  ||       S )z*See the ratsimp function in sympy.simplifyr   )ratsimp)sympy.simplify.ratsimprD  )r8   rD  s     r/   rD  zExpr.ratsimp  s    2t}r1   c                     ddl m}  || fi |S )z+See the trigsimp function in sympy.simplifyr   )r  )sympy.simplify.trigsimpr  )r8   rD   r  s      r/   r  zExpr.trigsimp  s    4%%%r1   c                     ddl m}  || fi |S )z*See the radsimp function in sympy.simplifyr   )radsimp)r  rI  )r8   rH  rI  s      r/   rI  zExpr.radsimp  s    2t&v&&r1   c                &    ddl m}  || g|i |S )z*See the powsimp function in sympy.simplifyr   r  )r  r  )r8   rD   rH  r  s       r/   r  zExpr.powsimp  s    2t-d-f--r1   c                    ddl m}  ||       S )z+See the combsimp function in sympy.simplifyr   )combsimp)sympy.simplify.combsimprL  )r8   rL  s     r/   rL  zExpr.combsimp  s    4~r1   c                    ddl m}  ||       S )z,See the gammasimp function in sympy.simplifyr   )	gammasimp)sympy.simplify.gammasimprO  )r8   rO  s     r/   rO  zExpr.gammasimp  s    6r1   c                &    ddl m}  || g|i |S )z2See the factor() function in sympy.polys.polytoolsr   )r  )r  r  )r8   r  rD   r  s       r/   r  zExpr.factor      0d*T*T**r1   c                &    ddl m}  || g|i |S )z&See the cancel function in sympy.polysr   )rw  )r  rw  )r8   r  rD   rw  s       r/   rw  zExpr.cancel  rR  r1   c                r    | j                   rt        |dd      rt        | |      S ddlm}  || |g|i |S )zReturn the multiplicative inverse of ``self`` mod ``g``
        where ``self`` (and ``g``) may be symbolic expressions).

        See Also
        ========
        sympy.core.intfunc.mod_inverse, sympy.polys.polytools.invert
        r   Tr   )invert)r   rR  r   r  rU  )r8   r  r  rD   rU  s        r/   rU  zExpr.invert  s=     >>gad;tQ''0dA----r1   c                   | }|j                   st        d      |j                  s3t        |j	                  d      d      s!t        dt        |      z        |t        v r|S |j                  x}sm|j                         \  }}|du r4|j                  |      t        j                  |j                  |      z  z   S |j                  d      r|j                  |      S |s|t        j                  S |S t        |xs d      }|j                  rt!        t        t#        |      |            S t%        |      }||z   }|j'                  t(              D 	cg c]  }	|	j*                   }
}	|
rt-        t/        |
            nd}|t/        d	|      }nt1        ||      }| |z   }d
}|j	                  ||z         t3        d|      z  }|j4                  r6|j*                  d
k(  r'|j                  d      rt)        d      S t7        d      t!        |      }|dkD  rd
nd}|||z
  j	                  |      z  }|dk  rt9        d      |dkD  r||z  }n|dk(  r||dz  r|n| z  }||z
  }t        |j:                  |      }t=        |t3        d|            }|j                  r||S t)        t?        |      |      S |s
|| kD  r|d
z  }t)        ||      S c c}	w )a,  Return x rounded to the given decimal place.

        If a complex number would results, apply round to the real
        and imaginary components of the number.

        Examples
        ========

        >>> from sympy import pi, E, I, S, Number
        >>> pi.round()
        3
        >>> pi.round(2)
        3.14
        >>> (2*pi + E*I).round()
        6 + 3*I

        The round method has a chopping effect:

        >>> (2*pi + I/10).round()
        6
        >>> (pi/10 + 2*I).round()
        2*I
        >>> (pi/10 + E*I).round(2)
        0.31 + 2.72*I

        Notes
        =====

        The Python ``round`` function uses the SymPy ``round`` method so it
        will always return a SymPy number (not a Python float or int):

        >>> isinstance(round(S(123), -2), Number)
        True
        z Cannot round symbolic expressionr   Tr  zExpected a number but got %s:Fr   Nr   r   
   znot computing with precisionr   z)not expecting int(x) to round away from 0g      ?) r   r   rG   r   r   r   r  r  r   r   r   r   r   rS  r   r   r   r   _magrC  r   r   r   r   r  r}   r   r   rF  r  r  rH   )r8   r   r   xrr   r-   r  digits_to_decimalallowrX  precsdpsshiftextraxfr  r  dif2ipr  s                       r/   r   z
Expr.round  s   F {{>??yyA53ilBD D(]H((((>>#DAqU{wwqzAOOAGGAJ$>>>xx{wwqz!Y166-A-16N<<5Q+,, G!A%"#''%.1.Q.1).k#e*%D; b%.CsOE #"S(^ SSuc"en,<<BHHMxx{Qx;<<R[ EqrR"WKK&&!8%;= ="9$JBRZ"Q$$TE)BY244_b#b%.)==y	R#&&R$Y
U##w 2s   Kc                ~    ddl m}  |t        j                  t        j                  g| j	                  |            gS )Nr   )_LeftRightArgs)higher)"sympy.matrices.expressions.matexprrd  r   rC   _eval_derivative)r8   r   rd  s      r/   _eval_derivative_matrix_linesz"Expr._eval_derivative_matrix_linesq  s,    Equu~d6K6KA6NOPPr1   r$   )returnr3   )r   rH   )Nr   r   r   r   )F)NF)FTT)r   FT)ri  ztuple[Expr, Expr]r  )ri  ztuple[Expr, tuple[Expr, ...]])FT)Nr      rj  Nr   )Nrj  r   F)Nr   rj  Nr   r   )rj  )r   rT  ri  tuple['Number', Expr])ri  rk  )Nr   r   Tr  TF)TNTTTTTT)r4   NF)FF)NTFT)__name__
__module____qualname____doc__r5   __annotations__	is_scalarpropertyr9   r   rF   rT   _op_priorityrW   r\   r^   re   ri   r   r   r   rn   rk   rt   rr   rx   rv   r~   r   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   r  r$  r   rY  r]  r_  r~  r  r  r  r  r  r  r  r  classmethodr  rL   r  rJ   r  r  r  r  r  r  r'   r   r#  r  r   r<  rD  r;  r@  rK  rM  rP  rx  rS  r"  rW  rz  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  re  r  r  r  r  r  r>   rg  r  r  r  r  r  r,  r2  r&  r:  r  r>  rA  rD  r  rI  r  rL  rO  r  rw  rU  r   	__round__rh  __classcell__r   s   @r/   r3   r3   +   sp   , "$I#I( (T !2 !2F, L   8 &'8:&  ' 9  &'89%  & 9  &'8:&! ' 9! &'89%! & 9! &'8:&  ' 9  &'89%  & 9  &'8:&  ' 9 &  &'89%  & 9  &'8>*$ + 9$ &'8=)% * 9% &'8:&  ' 9  &'89%  & 9  &'8?+# , 9# &'8>*# + 9#
 &'8=)5 * 95 &'8<(5 ) 954	>-
 &'8( 9( &'8% 9% &'8. 9. &'8+ 9+!
/ 	C 	C 17 17fL\jXKZ%NGHOb

".$"  8 D41l4l,A\'@DXt(BH~+@(:&4l!F"H47r (F,P]~ C C<<KZH.T:5x;/z22hFXPa*HYI(:ADF )&&P -1 !I !IF
8 FJ
C,C+  : IM8<Y Y~0
;
?
Q
/
&

&
'
.


+
+
.X$t IQr1   r3   c                  d     e Zd ZdZdZdZdZd Z fdZd Z	d Z
d	 Zd
 ZddZed        Z xZS )
AtomicExprz
    A parent class for object which are both atoms and Exprs.

    For example: Symbol, Number, Rational, Integer, ...
    But not: Add, Mul, Pow, ...
    FTr4   c                L    | |k(  rt         j                  S t         j                  S r$   )r   rC   rS  )r8   r9  s     r/   rg  zAtomicExpr._eval_derivative  s    1955Lvvr1   c                    ddl m} ddlm} ddlm} t        |||t        |f      rt        | %  ||      S ddl
m} ddlm} | |k(  r ||  ||d      fd ||d      fd      S  ||  ||d      fd      S )	Nr   )Tupler   )
MatrixExpr)
MatrixBase)Eq)r  )r   T)
containersr}  rf  r~  sympy.matrices.matrixbaser  rm  r   r   _eval_derivative_n_timesr   r  r  r  )	r8   r9  r   r}  r~  r  r  r  r   s	           r/   r  z#AtomicExpr._eval_derivative_n_times  sz    %A8a*eXzBC73Aq99"B19dBq!H-2a8}iHHdBq!H-y99r1   c                     yr  r4   r  s     r/   r  zAtomicExpr._eval_is_polynomial      r1   c                    | t         vS r$   )r  r  s     r/   r  z%AtomicExpr._eval_is_rational_function  s    8##r1   c                b    ddl m} | j                   xs | j                  xr t	        | |       S )Nr   ra  )rr  rb  r   	is_finiterm  )r8   r   r  rb  s       r/   r  zAtomicExpr._eval_is_meromorphic  s*    ANN"4dnn[j{>[:[[r1   c                     yr  r4   r  s     r/   r  z"AtomicExpr._eval_is_algebraic_expr  r  r1   c                    | S r$   r4   r  s        r/   r  zAtomicExpr._eval_nseries  r_   r1   c                $    t        ddd       | hS )Nrt  ru  rv  rw  r   r7   s    r/   rz  zAtomicExpr.expr_free_symbols  s!    ! # &+'E	G vr1   )r   )rl  rm  rn  ro  r   rG   r5   rg  r  r  r  r  r  r  rr  rz  rw  rx  s   @r/   rz  rz  v  sQ     IGI
:$\  r1   rz  c                   ddl m}m}m} t	        | j                               }|st        j                  S 	 t         | ||                  }|d|z  z  dk\  rd|d|z  z  cxk  rdk  sJ  J |dz  }|S # t        t        f$ r: t         |t        t        |j                  d             |d      z              }Y pw xY w)zReturn integer $i$ such that $0.1 \le x/10^i < 1$

    Examples
    ========

    >>> from sympy.core.expr import _mag
    >>> from sympy import Float
    >>> _mag(Float(.1))
    0
    >>> _mag(Float(.01))
    -1
    >>> _mag(Float(1234))
    4
    r   )log10ceilrd  5   rW  r   )mathr  r  rd  r   r   r   rS  r   r   OverflowErrorr   r   r   )r   r  r  rd  r  mag_first_digs         r/   rX  rX    s     &%qssu:DvvJDt-. 	R1$T"m++1r11111 & JDwtzz2'>!?B!GHIJs   A6 6AB?>B?c                      e Zd ZdZd Zd Zy)UnevaluatedExprz
    Expression that is not evaluated unless released.

    Examples
    ========

    >>> from sympy import UnevaluatedExpr
    >>> from sympy.abc import x
    >>> x*(1/x)
    1
    >>> x*UnevaluatedExpr(1/x)
    x*1/x

    c                J    t        |      }t        j                  | |fi |}|S r$   )r	   r3   __new__)r  rQ   rH  r   s       r/   r  zUnevaluatedExpr.__new__  s%    smll3.v.
r1   c                    |j                  dd      r | j                  d   j                  di |S | j                  d   S )Nr7  Tr   r4   )r  rD   r  )r8   r8  s     r/   r  zUnevaluatedExpr.doit  s<    99VT"$499Q<$$-u--99Q<r1   N)rl  rm  rn  ro  r  r  r4   r1   r/   r  r    s    
 r1   r  c                L     | | }|j                   | k(  xr |j                  |k(  S )a  Return True if `func` applied to the `args` is unchanged.
    Can be used instead of `assert foo == foo`.

    Examples
    ========

    >>> from sympy import Piecewise, cos, pi
    >>> from sympy.core.expr import unchanged
    >>> from sympy.abc import x

    >>> unchanged(cos, 1)  # instead of assert cos(1) == cos(1)
    True

    >>> unchanged(cos, pi)
    False

    Comparison of args uses the builtin capabilities of the object's
    arguments to test for equality so args can be defined loosely. Here,
    the ExprCondPair arguments of Piecewise compare as equal to the
    tuples that can be used to create the Piecewise:

    >>> unchanged(Piecewise, (x, x > 1), (0, True))
    True
    )r-  rD   )r-  rD   rX  s      r/   	unchangedr    s(    2 	dA66T>,affn,r1   c                  L    e Zd Zd
dZed        Zd ZddZddZd Z	d Z
d	 Zy)ExprBuilderNc                    t        |d      st        dj                  |            || _        |g | _        n|| _        || _        ||r| j                          y y y )N__call__zop {} needs to be callable)r   r   r   oprD   	validatorvalidate)r8   r  rD   r  checks        r/   __init__zExprBuilder.__init__  s]    r:&8??CDD<DIDI"!uMMO (-!r1   c                l    | D cg c]$  }t        |t              r|j                         n|& c}S c c}w r$   )rm  r  build)rD   r-   s     r/   _build_argszExprBuilder._build_args  s.    HLM1Z;7	Q>MMMs   )1c                r    | j                   y | j                  | j                        } | j                   |  y r$   )r  r  rD   )r8   rD   s     r/   r  zExprBuilder.validate  s1    >>!		*r1   c                    | j                  | j                        }| j                  r|r | j                  |   | j                  | S r$   )r  rD   r  r  )r8   r  rD   s      r/   r  zExprBuilder.build  s=    		*>>eDNND!tww~r1   c                    | j                   j                  |       | j                  r|r | j                  | j                     y y y r$   )rD   r(   r  r  )r8   rQ   r  s      r/   append_argumentzExprBuilder.append_argument$  s6    		>>eDMM499% $>r1   c                H    |dk(  r| j                   S | j                  |dz
     S )Nr   r   )r  rD   )r8   items     r/   __getitem__zExprBuilder.__getitem__)  s%    1977N99T!V$$r1   c                4    t        | j                               S r$   )rH   r  r7   s    r/   __repr__zExprBuilder.__repr__/  s    4::<  r1   c                    t        | j                        D ]M  \  }}t        |t              r|j	                  |      }|*|f|z   c S t        |      t        |      k(  sJ|fc S  y r$   )r  rD   rm  r  search_indexid)r8   elemr-   rQ   rets        r/   search_elementzExprBuilder.search_element2  s`    		*FAs#{+&&t,?4#:%CBtH$t + r1   )NNTr  )rl  rm  rn  r  rt  r  r  r  r  r  r  r  r4   r1   r/   r  r    s;    
 N N&
%!r1   r  rZ   rV   r|   )rB   r  r   )r>  )r   r   r  r  r   )K
__future__r   typingr   collections.abcr   	functoolsr   r   r   r	   r  r
   r   	singletonr   r   r   r   r   
decoratorsr   r   r   cacher   intfuncr   sortingr   r  r   r  r   sympy.utilities.miscr   r   r   sympy.utilities.iterablesr   r   mpmath.libmpr   r   mpmath.libmp.libintmathr    r  r!   collectionsr"   r0   r3   rz  rX  r  r  r  r,  r[   r  r%   r   r}   r  rB   r  r   r   r  r>  r   r   r  r  r   r4   r1   r/   <module>r     s    "   $  	 &   < < R R    %  @ > > 7 - /  #
 G=Q5* G=Q G=QTz6t 6r< d  :-:3 3l    4  # C Cr1   