
    wg+                      d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	 ddl
mZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddlmZmZ ddlmZ ddlmZ ddlmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z& d Z'g dZ(d#dZ) G d de      Z*e*jV                  Z, ee*jZ                        Z. ee*        G d de*      Z/d$dZ0d Z1ddl2m3Z3 ddl4m5Z6m7Z7m8Z8   eddd !      e6      Z5y")%z'Base class for all the objects in SymPy    )annotations)defaultdict)Mapping)chainzip_longest)
cmp_to_key   )_prepare_class_assumptions)cacheit)_sympifysympifySympifyError_external_converter)ordered)KindUndefinedKind)	Printable)
deprecated)sympy_deprecation_warning)iterablenumbered_symbols)
filldedent	func_name)getmroc                b    	 t        |       S # t        $ r t        dt        |       z        w xY w)zReturn expr as a Basic instance using strict sympify
    or raise a TypeError; this is just a wrapper to _sympify,
    raising a TypeError instead of a SympifyError.z)Argument must be a Basic object, not `%s`)r   r   	TypeErrorr   )exprs    U/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/core/basic.pyas_Basicr      s?    ~ 7);  	s   
 !.)DZeroOneHalfInfinityNaNNegativeOneNegativeInfinityIntegerRationalFloatExp1PiImaginaryUnitSymbolWildPowMulAdd
DerivativeIntegralAbsSignSqrtFloorCeilingReImArg	ConjugateExpLogSinCosTanCotASinACosATanACotSinhCoshTanhCothASinhACoshATanhACothRisingFactorialFallingFactorial	factorialbinomialGamma
LowerGamma
UpperGamma	PolyGammaErf	Chebyshev
Chebyshev2FunctionWildFunctionLambdaOrderEquality
UnequalityStrictGreaterThanStrictLessThanGreaterThanLessThanc                `   t        |t              sy| j                  }|j                  }||k(  ryt        t              dz   }	 t        j                  |      }	 t        j                  |      }||k(  r||k(  r||kD  ||k  z
  S ||kD  ||k  z
  S # t        $ r |}Y Cw xY w# t        $ r |}Y >w xY w)a[  return -1, 0, 1 if the name of x is before that of y.
    A string comparison is done if either name does not appear
    in `ordering_of_classes`. This is the helper for
    ``Basic.compare``

    Examples
    ========

    >>> from sympy import cos, tan, sin
    >>> from sympy.core import basic
    >>> save = basic.ordering_of_classes
    >>> basic.ordering_of_classes = ()
    >>> basic._cmp_name(cos, tan)
    -1
    >>> basic.ordering_of_classes = ["tan", "sin", "cos"]
    >>> basic._cmp_name(cos, tan)
    1
    >>> basic._cmp_name(sin, cos)
    -1
    >>> basic.ordering_of_classes = save

    r   r	   )
issubclassBasic__name__lenordering_of_classesindex
ValueError)xyn1n2UNKNOWNi1i2s          r   	_cmp_namert   P   s    0 a	
B	
B	Rx%&*G &&r* &&r* 
W}wRBG$$GR      s$   B B BBB-,B-c                  .    e Zd ZU dZdZded<   ded<   ed        Z fdZd	Z	d	Z
d	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Zd	Z d	Z!d	Z"d	Z#d	Z$d	Z%d	Z&d
ed<   d
ed<   d
ed<   d
ed<   d
ed<   e'Z(ded<   d Z)d Z*d Z+d Z,d Z- fdZ.dMdZ/d Z0ed        Z1d Z2e3d        Z4e5d        Z6e5d        Z7e8dNd       Z9d  Z:d! Z;d" Z<dNd#Z=d$ Z>edOd%       Z?ed&        Z@d' ZAed(        ZBd) ZCe3d*        ZDd+ ZEed,        ZFed-        ZGedPd.       ZHed/        ZIdQd1ZJd2 ZKe8d3        ZLd4 ZMd5 ZNd6 ZOe8d7        ZPdRd8ZQe8d9        ZRd: ZSdSd;ZTdTd<ZUd= ZVdUd>ZWdTd?ZXdNd@ZYdA ZZdB Z[dVdCZ\dD Z]d0dEdFZ^dG Z_dH Z`i Zae5dI        ZbdJ ZcdK ZddNdLZe xZfS )Wrg   a  
    Base class for all SymPy objects.

    Notes and conventions
    =====================

    1) Always use ``.args``, when accessing parameters of some instance:

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

    >>> cot(x).args
    (x,)

    >>> cot(x).args[0]
    x

    >>> (x*y).args
    (x, y)

    >>> (x*y).args[1]
    y


    2) Never use internal methods or variables (the ones prefixed with ``_``):

    >>> cot(x)._args    # do not use this, use cot(x).args instead
    (x,)


    3)  By "SymPy object" we mean something that can be returned by
        ``sympify``.  But not all objects one encounters using SymPy are
        subclasses of Basic.  For example, mutable objects are not:

        >>> from sympy import Basic, Matrix, sympify
        >>> A = Matrix([[1, 2], [3, 4]]).as_mutable()
        >>> isinstance(A, Basic)
        False

        >>> B = sympify(A)
        >>> isinstance(B, Basic)
        True
    )_mhash_args_assumptionstuple[Basic, ...]rw   z
int | Nonerv   c                     y)NT selfs    r   	__sympy__zBasic.__sympy__   s        c                8    t         |           t        |        y N)super__init_subclass__r
   )cls	__class__s    r   r   zBasic.__init_subclass__   s    
 	!#"3'r   Fzbool | Noneis_realis_extended_realis_zerois_negativeis_commutativer   kindc                n    t         j                  |       }| j                  |_        d |_        ||_        |S r   )object__new__default_assumptionsrx   rv   rw   )r   argsobjs      r   r   zBasic.__new__   s1    nnS!22
	
r   c                4     | j                   | j                   S r   )funcr   r|   s    r   copyz
Basic.copy   s    tyy$))$$r   c                    | j                   S r   r   r|   s    r   __getnewargs__zBasic.__getnewargs__   s    yyr   c                     y r   r{   r|   s    r   __getstate__zBasic.__getstate__       r   c                N    |j                         D ]  \  }}t        | ||        y r   )itemssetattr)r}   statenamevalues       r   __setstate__zBasic.__setstate__   s'     ;;= 	'KD%D$&	'r   c                F    |dk  rd}t        |      t        | 	  |      S )N   z6Only pickle protocol 2 or higher is supported by SymPy)NotImplementedErrorr   __reduce_ex__)r}   protocolmsgr   s      r   r   zBasic.__reduce_ex__   s*    a<JC%c**w$X..r   c                    | j                   }|7t        t        |       j                  f| j	                         z         }|| _         |S r   )rv   hashtyperh   _hashable_content)r}   hs     r   __hash__zBasic.__hash__   sC     KK9d4j))+d.D.D.FFGADKr   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__.rw   r|   s    r   r   zBasic._hashable_content	  s     zzr   c                    i S )a  
        Return object `type` assumptions.

        For example:

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

        are different objects. In other words, besides Python type (Symbol in
        this case), the initial assumptions are also forming their typeinfo.

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.abc import x
        >>> x.assumptions0
        {'commutative': True}
        >>> x = Symbol("x", positive=True)
        >>> x.assumptions0
        {'commutative': True, 'complex': True, 'extended_negative': False,
         'extended_nonnegative': True, 'extended_nonpositive': False,
         'extended_nonzero': True, 'extended_positive': True, 'extended_real':
         True, 'finite': True, 'hermitian': True, 'imaginary': False,
         'infinite': False, 'negative': False, 'nonnegative': True,
         'nonpositive': False, 'nonzero': True, 'positive': True, 'real':
         True, 'zero': False}
        r{   r|   s    r   assumptions0zBasic.assumptions0  s	    < 	r   c                   | |u ry| j                   }|j                   }t        ||      }|r|S | j                         }|j                         }t        |      t        |      kD  t        |      t        |      k  z
  }|r|S t	        ||      D ]l  \  }}t        |t              rt        | n|}t        |t              rt        | n|}t        |t              r|j                  |      }n||kD  ||k  z
  }|sj|c S  y)a  
        Return -1, 0, 1 if the object is less than, equal,
        or greater than other in a canonical sense.
        Non-Basic are always greater than Basic.
        If both names of the classes being compared appear
        in the `ordering_of_classes` then the ordering will
        depend on the appearance of the names there.
        If either does not appear in that list, then the
        comparison is based on the class name.
        If the names are the same then a comparison is made
        on the length of the hashable content.
        Items of the equal-lengthed contents are then
        successively compared using the same rules. If there
        is never a difference then 0 is returned.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> x.compare(y)
        -1
        >>> x.compare(x)
        0
        >>> y.compare(x)
        1

        r   )	r   rt   r   ri   zip
isinstance	frozensetrg   compare)	r}   otherro   rp   cstotlrs	            r   r   zBasic.compare3  s    < 5=^^__b"H##%$$&Ws2w3r7SW#45HBK 	DAq'95q	1A'95q	1A!U#IIaLUq1u%	 r   c                F   ddl m} t        | |      rt        ||      syt        | |      st        ||      ry| j                  rI|j                  r=| j                  |j
                  z  }|j                  | j
                  z  }||kD  ||k  z
  S ddlm}  |d       |d       |d      }}}| j                  |||z  z        }	|	rH||	v rD|	|   }
|j                  |||z  z        }|r&||v r"||   }t        j                  |
|      }|dk7  r|S t        j                  | |      S )	aT  return -1, 0, 1 if a is canonically less, equal or
        greater than b. This is used when 'order=old' is selected
        for printing. This puts Order last, orders Rationals
        according to value, puts terms in order wrt the power of
        the last power appearing in a term. Ties are broken using
        Basic.compare.
        r   )r]   r	   re   r.   p1p2p3)sympy.series.orderr]   r   is_Rationalpqsymbolr.   matchrg   r   )abr]   r   r   r.   r   r   r   r_aa3r_bb3r   s                 r   _compare_prettyzBasic._compare_prettyi  s    	-a
1e(<!U#
1e(<==Q]]acc	Aacc	AEa!e$$$dT$ZdBB''"r2v+&CrSyWggb2r6k*29RBb"-AAv  }}Q""r   c                $     | t        |      i |S )aa  
        Create a new object from an iterable.

        This is a convenience function that allows one to create objects from
        any iterable, without having to convert to a list or tuple first.

        Examples
        ========

        >>> from sympy import Tuple
        >>> Tuple.fromiter(i for i in range(5))
        (0, 1, 2, 3, 4)

        )tuple)r   r   assumptionss      r   fromiterzBasic.fromiter  s      E$K/;//r   c                     dd| j                   fS )zNice order of classes.   r   rh   r   s    r   	class_keyzBasic.class_key  s     !S\\!!r   c           	         fd}| j                   }t        |      t        |D cg c]
  } ||       c}      f}| j                         |t        j
                  j                         t        j
                  fS c c}w )a  
        Return a sort key.

        Examples
        ========

        >>> from sympy import S, I

        >>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
        [1/2, -I, I]

        >>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
        [x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
        >>> sorted(_, key=lambda x: x.sort_key())
        [x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]

        c                J    t        | t              r| j                        S | S r   )r   rg   sort_key)argorders    r   	inner_keyz!Basic.sort_key.<locals>.inner_key  s!    #u%||E**
r   )_sorted_argsri   r   r   Sr!   r   )r}   r   r   r   r   s    `   r   r   zBasic.sort_key  sb    *	   4y%4 @C3 @AA~~quu~~'7>> !As   A;
c                    t        |      j                  D ]&  }t        j                  |      }||  ||      k(  c S  t	        |d      r| |j                         k(  S t        S )a  Returns a boolean indicating whether a == b when either a
        or b is not a Basic. This is only done for types that were either
        added to `converter` by a 3rd party or when the object has `_sympy_`
        defined. This essentially reuses the code in `_sympify` that is
        specific for this use case. Non-user defined types that are meant
        to work with SymPy should be handled directly in the __eq__ methods
        of the `Basic` classes it could equate to and not be converted. Note
        that after conversion, `==`  is used again since it is not
        necessarily clear whether `self` or `other`'s __eq__ method needs
        to be used._sympy_)r   __mro__r   gethasattrr   NotImplemented)r}   r   
superclassconvs       r   _do_eq_sympifyzBasic._do_eq_sympify  se     u+-- 	+J&**:6DtE{**	+ 5)$5==?**r   c                   | |u ryt        |t              s| j                  |      S | j                  r|j                  st	        |       t	        |      k7  ry| j                         |j                         }}||k7  ryt        ||      D ]<  \  }}t        |t              s|j                  s$t	        |      t	        |      k7  s< y y)a  Return a boolean indicating whether a == b on the basis of
        their symbolic trees.

        This is the same as a.compare(b) == 0 but faster.

        Notes
        =====

        If a class that overrides __eq__() needs to retain the
        implementation of __hash__() from a parent class, the
        interpreter must be told this explicitly by setting
        __hash__ : Callable[[object], int] = <ParentClass>.__hash__.
        Otherwise the inheritance of __hash__() will be blocked,
        just as if __hash__ had been explicitly set to None.

        References
        ==========

        from https://docs.python.org/dev/reference/datamodel.html#object.__hash__
        TF)r   rg   r   	is_Numberr   r   r   )r}   r   r   r   s       r   __eq__zBasic.__eq__  s    * 5=%'&&u-- EOOT
d5k)%%')@)@)B161I 	DAqa'{{tAw$q'1		
 r   c                    | |k(   S )z``a != b``  -> Compare two symbolic trees and see whether they are different

        this is the same as:

        ``a.compare(b) != 0``

        but faster
        r{   )r}   r   s     r   __ne__zBasic.__ne__  s     5=  r   c                   | j                         }t        |      }|j                         }|j                  D cg c]  }|j                  s| }}t	        |      dk(  r|j                         }n||k(  S |0|j                  }t	        |      dk(  r|j                         }n||k(  S |j                         }	|j                  ||	i      |j                  ||	i      k(  S c c}w )a  
        Compare two expressions and handle dummy symbols.

        Examples
        ========

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

        >>> u = Dummy('u')

        >>> (u**2 + 1).dummy_eq(x**2 + 1)
        True
        >>> (u**2 + 1) == (x**2 + 1)
        False

        >>> (u**2 + y).dummy_eq(x**2 + y, x)
        True
        >>> (u**2 + y).dummy_eq(x**2 + y, y)
        False

        r	   )as_dummyr   free_symbolsis_Dummyri   popr   xreplace)
r}   r   r   soidummy_symbolsdummysymbolstmps
             r   dummy_eqzBasic.dummy_eq
  s    . MMOUOJJL$%NNAqajjAA}"!%%'E6M>nnG7|q  Avoozz5#,'1::vsm+DDD# Bs   CCc           	        |r4t        |D cg c]  }t        |t              r|n
t        |      ! c}      }t        |       }|r|D ch c]  }t        ||      s| }}|S |D ch c]  }|j                  r| }}|S c c}w c c}w c c}w )a-	  Returns the atoms that form the current object.

        By default, only objects that are truly atomic and cannot
        be divided into smaller pieces are returned: symbols, numbers,
        and number symbols like I and pi. It is possible to request
        atoms of any type, however, as demonstrated below.

        Examples
        ========

        >>> from sympy import I, pi, sin
        >>> from sympy.abc import x, y
        >>> (1 + x + 2*sin(y + I*pi)).atoms()
        {1, 2, I, pi, x, y}

        If one or more types are given, the results will contain only
        those types of atoms.

        >>> from sympy import Number, NumberSymbol, Symbol
        >>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
        {x, y}

        >>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
        {1, 2}

        >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
        {1, 2, pi}

        >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
        {1, 2, I, pi}

        Note that I (imaginary unit) and zoo (complex infinity) are special
        types of number symbols and are not part of the NumberSymbol class.

        The type can be given implicitly, too:

        >>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol
        {x, y}

        Be careful to check your assumptions when using the implicit option
        since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type
        of SymPy atom, while ``type(S(2))`` is type ``Integer`` and will find all
        integers in an expression:

        >>> from sympy import S
        >>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
        {1}

        >>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
        {1, 2}

        Finally, arguments to atoms() can select more than atomic atoms: any
        SymPy type (loaded in core/__init__.py) can be listed as an argument
        and those types of "atoms" as found in scanning the arguments of the
        expression recursively:

        >>> from sympy import Function, Mul
        >>> from sympy.core.function import AppliedUndef
        >>> f = Function('f')
        >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function)
        {f(x), sin(y + I*pi)}
        >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef)
        {f(x)}

        >>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
        {I*pi, 2*sin(y + I*pi)}

        )r   r   r   _preorder_traversalr   )r}   typestnodesnoderesults         r   atomszBasic.atoms8  s    J @EF1jD)tAw6FHE#D)',Ht
40GdHFH  (->tDIId>F> G I>s   $B BB&B
8B
c                V    t               } |j                  d | j                  D         S )a  Return from the atoms of self those which are free symbols.

        Not all free symbols are ``Symbol``. Eg: IndexedBase('I')[0].free_symbols

        For most expressions, all symbols are free symbols. For some classes
        this is not true. e.g. Integrals use Symbols for the dummy variables
        which are bound variables, so Integral has a method to return all
        symbols except those. Derivative keeps track of symbols with respect
        to which it will perform a derivative; those are
        bound variables, too, so it has its own free_symbols method.

        Any other method that uses bound variables should implement a
        free_symbols method.c              3  4   K   | ]  }|j                     y wr   )r   ).0r   s     r   	<genexpr>z%Basic.free_symbols.<locals>.<genexpr>  s     ?Q^^?s   )setunionr   )r}   emptys     r   r   zBasic.free_symbols  s&      Eu{{?TYY?@@r   c                2    t        ddd       t               S )Nz
        The expr_free_symbols property is deprecated. Use free_symbols to get
        the free symbols of an expression.
        z1.9zdeprecated-expr-free-symbolsdeprecated_since_versionactive_deprecations_target)r   r  r|   s    r   expr_free_symbolszBasic.expr_free_symbols  s!    ! # &+'E	G ur   c                n    ddl mm} fd}| j                  |      s| S | j	                  d |d      S )an  Return the expression with any objects having structurally
        bound symbols replaced with unique, canonical symbols within
        the object in which they appear and having only the default
        assumption for commutativity being True. When applied to a
        symbol a new symbol having only the same commutativity will be
        returned.

        Examples
        ========

        >>> from sympy import Integral, Symbol
        >>> from sympy.abc import x
        >>> r = Symbol('r', real=True)
        >>> Integral(r, (r, x)).as_dummy()
        Integral(_0, (_0, x))
        >>> _.variables[0].is_real is None
        True
        >>> r.as_dummy()
        _r

        Notes
        =====

        Any object that has structurally bound variables should have
        a property, `bound_symbols` that returns those symbols
        appearing in the object.
        r	   Dummyr-   c                J   | j                   }t        | j                        }||z  D ci c]
  }|         }}| j                  |      } | j	                  | j
                        } | j	                  |j                         D ci c]  \  }}||
 c}}      S c c}w c c}}w r   )r   r  bound_symbolssubsr   canonical_variablesr   )rm   freeboundr   dkvr  s          r   canzBasic.as_dummy.<locals>.can  s    >>D(E%*T\2EG2A2q	A

1001A::	:1q!t:;; 3
 ;s   BB
c                    t        | d      S )Nr  )r   rm   s    r   <lambda>z Basic.as_dummy.<locals>.<lambda>  s    ga1 r   F)simultaneous)r   r  r-   hasreplace)r}   r-   r  r  s      @r   r   zBasic.as_dummy  s?    8 	*		< xxK||1    	 r   c                R   t        | d      si S t        d      }i }| j                  }| j                  t	        |      z
  D ch c]  }|j
                   }}|D ]F  }t        |      }|j                  r(|j
                  |v rt        |      }|j
                  |v r|||<   H |S c c}w )aU  Return a dictionary mapping any variable defined in
        ``self.bound_symbols`` to Symbols that do not clash
        with any free symbols in the expression.

        Examples
        ========

        >>> from sympy import Lambda
        >>> from sympy.abc import x
        >>> Lambda(x, 2*x).canonical_variables
        {x: _0}
        r  _)r   r   r  r   r  r   next	is_Symbol)r}   dumsrepsr  r   namesr   r  s           r   r  zBasic.canonical_variables  s     t_-I$ ""!%!2!2SZ!?@A@@ 	AT
A{{ffoT
A ffoDG	  As   B$c                .    t         j                  | |      S )a  Apply on the argument recursively through the expression tree.

        This method is used to simulate a common abuse of notation for
        operators. For instance, in SymPy the following will not work:

        ``(x+Lambda(y, 2*y))(z) == x+2*z``,

        however, you can use:

        >>> from sympy import Lambda
        >>> from sympy.abc import x, y, z
        >>> (x + Lambda(y, 2*y)).rcall(z)
        x + 2*z
        )rg   _recursive_call)r}   r   s     r   rcallzBasic.rcall  s     $$T400r   c                    ddl m} d }t        |       r ||       rt        | |      r| S  | | S | j                  r;| j                  D cg c]  }t
        j                  ||       }} t        |       | S | S c c}w )zHelper for rcall method.r	   r-   c                h    t        t        |             D ]  }d|j                  v s|t        k7  c S  y )N__call__)r   r   __dict__rg   )r   r   s     r   the_call_method_is_overriddenz<Basic._recursive_call.<locals>.the_call_method_is_overridden  s0    d4j) (-%<'(r   )r   r-   callabler   r   rg   r+  r   )expr_to_callon_argsr-   r2  subr   s         r   r+  zBasic._recursive_call   s     	#	(
 L!&CL&Q,/###W--)5):):<"% ))W <D <%4%t,,	<s   
A9c                T    ddl m} ddlm} | j	                  |      ry  || |      d uS )Nr   )	hypersimp)	Piecewise)sympy.simplify.simplifyr8  $sympy.functions.elementary.piecewiser9  r!  )r}   r  r8  r9  s       r   is_hypergeometriczBasic.is_hypergeometric  s)    5B88Iq!--r   c                   | j                   }|du ry| j                  sy| j                         D cg c]!  }|j                  s|j	                  d      n|# c}\  }}|j                  r|j                  sy|ry|j
                  dk7  S c c}w )a  Return True if self can be computed to a real number
        (or already is a real number) with precision, else False.

        Examples
        ========

        >>> from sympy import exp_polar, pi, I
        >>> (I*exp_polar(I*pi/2)).is_comparable
        True
        >>> (I*exp_polar(I*pi*2)).is_comparable
        False

        A False result does not mean that `self` cannot be rewritten
        into a form that would be comparable. For example, the
        difference computed below is zero but without simplification
        it does not evaluate to a zero with precision:

        >>> e = 2**pi*(1 + 2**pi)
        >>> dif = e - e.expand()
        >>> dif.is_comparable
        False
        >>> dif.n(2)._prec
        1

        Fr   r	   )r   	is_numberas_real_imagr   evalf_prec)r}   r   r   nr   s        r   is_comparablezBasic.is_comparable  s    6  00u$~~ &&(* #$++
14 *1
 77a<*s   &Bc                    | j                   S )a  
        The top-level function in an expression.

        The following should hold for all objects::

            >> x == x.func(*x.args)

        Examples
        ========

        >>> from sympy.abc import x
        >>> a = 2*x
        >>> a.func
        <class 'sympy.core.mul.Mul'>
        >>> a.args
        (2, x)
        >>> a.func(*a.args)
        2*x
        >>> a == a.func(*a.args)
        True

        r   r|   s    r   r   z
Basic.funcK  s    0 ~~r   c                    | j                   S )a@  Returns a tuple of arguments of 'self'.

        Examples
        ========

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

        >>> cot(x).args
        (x,)

        >>> cot(x).args[0]
        x

        >>> (x*y).args
        (x, y)

        >>> (x*y).args[1]
        y

        Notes
        =====

        Never use self._args, always use self.args.
        Only use _args in __new__ when creating a new function.
        Do not override .args() from Basic (so that it is easy to
        change the interface in the future if needed).
        r   r|   s    r   r   z
Basic.argse  s    < zzr   c                    | j                   S )z
        The same as ``args``.  Derived classes which do not fix an
        order on their arguments should override this method to
        produce the sorted representation.
        r   r|   s    r   r   zBasic._sorted_args  s     yyr   Tc                &    t         j                  | fS )zA stub to allow Basic args (like Tuple) to be skipped when computing
        the content and primitive components of an expression.

        See Also
        ========

        sympy.core.expr.Expr.as_content_primitive
        )r   r!   )r}   radicalclears      r   as_content_primitivezBasic.as_content_primitive  s     uud{r   c                   ddl m} ddlm}m ddlm} d}t        |      dk(  r\|d   }t        |t              rd}nat        ||t        f      rd}|j                         }n<t        |      s1t        t        d            t        |      d	k(  r|g}nt        d
      fd}d }	|D 
cg c]  \  }
} ||
       |	|      f }}
}|D 
cg c]  \  }
}t        |
|      r|
|f }}
}|j!                  dd      }|rddlmm} t)        |      }t+        t-        |dfd|f            }|D cg c]	  }|||   f }}|sVt/        |      D cg c]  \  }}|d   |v s| }}}t1        |      D ]#  }|j3                  d|j!                  |             % |ri }| }d|d<    |d      }|D ]M  \  }}|j4                  }|d} |d|      } |j6                  |||z  fi |}t        |t8              s n|||<   O t:        j<                  ||<   |j?                  |      S | }|D ],  \  }} |j6                  ||fi |}t        |t8              r+ |S  |S c c}}
w c c}}
w c c}w c c}}w )a  
        Substitutes old for new in an expression after sympifying args.

        `args` is either:
          - two arguments, e.g. foo.subs(old, new)
          - one iterable argument, e.g. foo.subs(iterable). The iterable may be
             o an iterable container with (old, new) pairs. In this case the
               replacements are processed in the order given with successive
               patterns possibly affecting replacements already made.
             o a dict or set whose key/value items correspond to old/new pairs.
               In this case the old/new pairs will be sorted by op count and in
               case of a tie, by number of args and the default_sort_key. The
               resulting sorted list is then processed as an iterable container
               (see previous).

        If the keyword ``simultaneous`` is True, the subexpressions will not be
        evaluated until all the substitutions have been made.

        Examples
        ========

        >>> from sympy import pi, exp, limit, oo
        >>> from sympy.abc import x, y
        >>> (1 + x*y).subs(x, pi)
        pi*y + 1
        >>> (1 + x*y).subs({x:pi, y:2})
        1 + 2*pi
        >>> (1 + x*y).subs([(x, pi), (y, 2)])
        1 + 2*pi
        >>> reps = [(y, x**2), (x, 2)]
        >>> (x + y).subs(reps)
        6
        >>> (x + y).subs(reversed(reps))
        x**2 + 2

        >>> (x**2 + x**4).subs(x**2, y)
        y**2 + y

        To replace only the x**2 but not the x**4, use xreplace:

        >>> (x**2 + x**4).xreplace({x**2: y})
        x**4 + y

        To delay evaluation until all substitutions have been made,
        set the keyword ``simultaneous`` to True:

        >>> (x/y).subs([(x, 0), (y, 0)])
        0
        >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
        nan

        This has the added feature of not allowing subsequent substitutions
        to affect those already made:

        >>> ((x + y)/y).subs({x + y: y, y: x + y})
        1
        >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
        y/(x + y)

        In order to obtain a canonical result, unordered iterables are
        sorted by count_op length, number of arguments and by the
        default_sort_key to break any ties. All other iterables are left
        unsorted.

        >>> from sympy import sqrt, sin, cos
        >>> from sympy.abc import a, b, c, d, e

        >>> A = (sqrt(sin(2*x)), a)
        >>> B = (sin(2*x), b)
        >>> C = (cos(2*x), c)
        >>> D = (x, d)
        >>> E = (exp(x), e)

        >>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)

        >>> expr.subs(dict([A, B, C, D, E]))
        a*c*sin(d*e) + b

        The resulting expression represents a literal replacement of the
        old arguments with the new arguments. This may not reflect the
        limiting behavior of the expression:

        >>> (x**3 - 3*x).subs({x: oo})
        nan

        >>> limit(x**3 - 3*x, x, oo)
        oo

        If the substitution will be followed by numerical
        evaluation, it is better to pass the substitution to
        evalf as

        >>> (1/x).evalf(subs={x: 3.0}, n=21)
        0.333333333333333333333

        rather than

        >>> (1/x).subs({x: 3.0}).evalf(21)
        0.333333333333333314830

        as the former will ensure that the desired level of precision is
        obtained.

        See Also
        ========
        replace: replacement capable of doing wildcard-like matching,
                 parsing of match, and conditional replacements
        xreplace: exact node replacement in expr tree; also capable of
                  using matching rules
        sympy.core.evalf.EvalfMixin.evalf: calculates the given formula to a desired level of precision

        r	   )Dictr  )_illegalFr   Tz
                   When a single argument is passed to subs
                   it should be a dictionary of old: new pairs or an iterable
                   of (old, new) tuples.r   z$subs accepts either 1 or 2 argumentsc                    t        | t              r |       S t        | t              rt        | d      S t        | d      S NF)strictTr   strr   r   )oldr-   s    r   sympify_oldzBasic.subs.<locals>.sympify_old!  s;    #s#c{"C&s511s400r   c                b    t        | t        t        f      rt        | d      S t        | d      S rP  rR  )news    r   sympify_newzBasic.subs.<locals>.sympify_new+  s*    #T{+s511s400r   r   )_nodesdefault_sort_keyc                     |        S r   r{   )rm   rY  s    r   r  zBasic.subs.<locals>.<lambda>C  s    6!9* r   )defaultkeyshack2subs_msubs_d)commutative) 
containersrM  r   r  r-   numbersrN  ri   r   r  r   r   r   rl   r   _aresamer   sortingrY  rZ  dictlistr   	enumeratereversedinsertr   _subsrg   r   r!   r   )r}   r   kwargsrM  r  rN  	unorderedsequencerU  rX  s1s2r   rZ  r  r   seqredor(  rvmrT  rW  comr  r-   rY  s                            @@r   r  z
Basic.subs  s   b 	%)%	t9>AwH(C( 	HtWo6 	#>>+h'  -, "- . . Y!^vHCDD	1	1 FNN62r[_k"o6NN ,4LR8B;KRHLLzz.%89H~H WXu$ <  A 344QHQK(4H4(1((;Rfas1v?QRR!$ 8AOOAx||A78 DB"F7OhA$ S((;C(4 RXXc1Q31&1!"e,Q eeDG;;t$$B$ SRXXc31&1!"e,I	 Ii O M" 5 Ss$   -II $I 4I&I+$I+c                j    fd}t        | |      r|S | j                  ||      }|
 || ||      }|S )a
  Substitutes an expression old -> new.

        If self is not equal to old then _eval_subs is called.
        If _eval_subs does not want to make any special replacement
        then a None is received which indicates that the fallback
        should be applied wherein a search for replacements is made
        amongst the arguments of self.

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

        Examples
        ========

        Add's _eval_subs knows how to target x + y in the following
        so it makes the change:

        >>> (x + y + z).subs(x + y, 1)
        z + 1

        Add's _eval_subs does not need to know how to find x + y in
        the following:

        >>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None
        True

        The returned None will cause the fallback routine to traverse the args and
        pass the z*(x + y) arg to Mul where the change will take place and the
        substitution will succeed:

        >>> (z*(x + y) + 3).subs(x + y, 1)
        z + 3

        ** Developers Notes **

        An _eval_subs routine for a class should be written if:

            1) any arguments are not instances of Basic (e.g. bool, tuple);

            2) some arguments should not be targeted (as in integration
               variables);

            3) if there is something other than a literal replacement
               that should be attempted (as in Piecewise where the condition
               may be updated without doing a replacement).

        If it is overridden, here are some special cases that might arise:

            1) If it turns out that no special change was made and all
               the original sub-arguments should be checked for
               replacements then None should be returned.

            2) If it is necessary to do substitutions on a portion of
               the expression then _subs should be called. _subs will
               handle the case of any sub-expression being equal to old
               (which usually would not be the case) while its fallback
               will handle the recursion into the sub-arguments. For
               example, after Add's _eval_subs removes some matching terms
               it must process the remaining terms so it calls _subs
               on each of the un-matched terms and then adds them
               onto the terms previously obtained.

           3) If the initial expression should remain unchanged then
              the original expression should be returned. (Whenever an
              expression is returned, modified or not, no further
              substitution of old -> new is attempted.) Sum's _eval_subs
              routine uses this strategy when a substitution is attempted
              on any of its summation variables.
        c                0   d}t        | j                        }t        |      D ]=  \  }}t        |d      s |j                  ||fi }t        |||         r7d}|||<   ? |r | j                  | }j                  dd      }|r| j                  r|j                  sst        j                  }	g }
|D ]%  }|j                  r|	|z  }	|
j                  |       '  | j                  |
 }
|	t        j                  u r|
S | j                  |	|
d      S |S | S )zQ
            Try to replace old with new in any of self's arguments.
            F
_eval_subsTr^  )evaluate)rg  r   rh  r   rk  rd  r   r   is_Mulr   r!   r   append)r}   rT  rW  hitr   r   r   rs  r^  coeff	nonnumberhintss              r   fallbackzBasic._subs.<locals>.fallback  s    C		?D#D/ "3sL1ciiS2E2T!W-C!DG" TYY%		'51T[[EEE "I! 0;;!QJE%,,Q/	0
 !*		9 5I~((#yy	EyJJ	Kr   )rd  rx  )r}   rT  rW  r  r  rs  s      `  r   rk  zBasic._subsh  sC    P	@ D#J__S#&:$S)B	r   c                     y)zOverride this stub if you want to do anything more than
        attempt a replacement of old with new in the arguments of self.

        See also
        ========

        _subs
        Nr{   )r}   rT  rW  s      r   rx  zBasic._eval_subs  s     r   c                .    | j                  |      \  }}|S )a  
        Replace occurrences of objects within the expression.

        Parameters
        ==========

        rule : dict-like
            Expresses a replacement rule

        Returns
        =======

        xreplace : the result of the replacement

        Examples
        ========

        >>> from sympy import symbols, pi, exp
        >>> x, y, z = symbols('x y z')
        >>> (1 + x*y).xreplace({x: pi})
        pi*y + 1
        >>> (1 + x*y).xreplace({x: pi, y: 2})
        1 + 2*pi

        Replacements occur only if an entire node in the expression tree is
        matched:

        >>> (x*y + z).xreplace({x*y: pi})
        z + pi
        >>> (x*y*z).xreplace({x*y: pi})
        x*y*z
        >>> (2*x).xreplace({2*x: y, x: z})
        y
        >>> (2*2*x).xreplace({2*x: y, x: z})
        4*z
        >>> (x + y + 2).xreplace({x + y: 2})
        x + y + 2
        >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
        x + exp(y) + 2

        xreplace does not differentiate between free and bound symbols. In the
        following, subs(x, y) would not change x since it is a bound symbol,
        but xreplace does:

        >>> from sympy import Integral
        >>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
        Integral(y, (y, 1, 2*y))

        Trying to replace x with an expression raises an error:

        >>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP
        ValueError: Invalid limits given: ((2*y, 1, 4*y),)

        See Also
        ========
        replace: replacement capable of doing wildcard-like matching,
                 parsing of match, and conditional replacements
        subs: substitution of subexpressions as defined by the objects
              themselves.

        )	_xreplace)r}   ruler   r$  s       r   r   zBasic.xreplace  s    | >>$'qr   c                   | |v r||    dfS |rxg }d}| j                   D ]G  }t        |dd      }|% ||      }|j                  |d          ||d   z  }7|j                  |       I t        |      }|r | j                  | dfS | dfS )zV
        Helper for xreplace. Tracks whether a replacement actually occurred.
        TFr  Nr   r	   )r   getattrr{  r   r   )r}   r  r   changedr   r  a_xrs          r   r  zBasic._xreplace$  s     4<:t##DGYY ##A{D9	($T?DKKQ(tAw&GKKN# ;D tyy$'--U{r   c                0     | j                   t        g| S )a  
        Test whether any subexpression matches any of the patterns.

        Examples
        ========

        >>> from sympy import sin
        >>> from sympy.abc import x, y, z
        >>> (x**2 + sin(x*y)).has(z)
        False
        >>> (x**2 + sin(x*y)).has(x, y, z)
        True
        >>> x.has(x)
        True

        Note ``has`` is a structural algorithm with no knowledge of
        mathematics. Consider the following half-open interval:

        >>> from sympy import Interval
        >>> i = Interval.Lopen(0, 5); i
        Interval.Lopen(0, 5)
        >>> i.args
        (0, 5, True, False)
        >>> i.has(4)  # there is no "4" in the arguments
        False
        >>> i.has(0)  # there *is* a "0" in the arguments
        True

        Instead, use ``contains`` to determine whether a number is in the
        interval or not:

        >>> i.contains(4)
        True
        >>> i.contains(0)
        False


        Note that ``expr.has(*patterns)`` is exactly equivalent to
        ``any(expr.has(p) for p in patterns)``. In particular, ``False`` is
        returned when the list of patterns is empty.

        >>> x.has()
        False

        )_hasiterargs)r}   patternss     r   r!  z	Basic.has:  s    ^ tyy-H--r   c                v    t              t        urt        d      t        fdt	        |       D              S )aG  Return True if self has any of the patterns in s as a
        free argument, else False. This is like `Basic.has_free`
        but this will only report exact argument matches.

        Examples
        ========

        >>> from sympy import Function
        >>> from sympy.abc import x, y
        >>> f = Function('f')
        >>> f(x).has_xfree({f})
        False
        >>> f(x).has_xfree({f(x)})
        True
        >>> f(x + 1).has_xfree({x})
        True
        >>> f(x + 1).has_xfree({x + 1})
        True
        >>> f(x + y + 1).has_xfree({x + 1})
        False
        zexpecting set argumentc              3  &   K   | ]  }|v  
 y wr   r{   )r  r   r   s     r   r  z"Basic.has_xfree.<locals>.<genexpr>  s     6a166s   )r   r  r   anyiterfreeargs)r}   r   s    `r   	has_xfreezBasic.has_xfreek  s3    . 7#4556<#5666r   c                    |sy|d   }t        |      dk(  r/t        |      r$t        |t              st	        t        d            t        |      }| j                  |      }|r|S  | j                  t        g| S )af  Return True if self has object(s) ``x`` as a free expression
        else False.

        Examples
        ========

        >>> from sympy import Integral, Function
        >>> from sympy.abc import x, y
        >>> f = Function('f')
        >>> g = Function('g')
        >>> expr = Integral(f(x), (f(x), 1, g(y)))
        >>> expr.free_symbols
        {y}
        >>> expr.has_free(g(y))
        True
        >>> expr.has_free(*(x, f(x)))
        False

        This works for subexpressions and types, too:

        >>> expr.has_free(g)
        True
        >>> (x + y + 1).has_free(y + 1)
        True
        Fr   r	   z
                Expecting 1 or more Basic args, not a single
                non-Basic iterable. Don't forget to unpack
                iterables: `eq.has_free(*patterns)`)
ri   r   r   rg   r   r   r  r  r  r  )r}   r  p0r   rs  s        r   has_freezBasic.has_free  s    6 a[x=A(2,z"e7L J (7 8 9 9
 M^^AItyy111r   c                   t               }t               }|D ]a  }t        |t              r"t        |t              r|j                  |       5t        |t              s	 t        |      }|j                  |       c t        |      } ||       D ]  }||v r yt        ||      s y ||z
  D ];  }t        |d      s|j                         t        fd ||       D              s; y y# t        $ r Y w xY w)NT_has_matcherc              3  .   K   | ]  } |        y wr   r{   )r  r   r   s     r   r  zBasic._has.<locals>.<genexpr>  s     8#5:8s   F)r  r   r   rf   rg   addr   r   r   r   r  r  )	r}   r  r  type_setp_setr   r   r   r   s	           @r   r  z
Basic._has  s    5 		A!T"z!U';Qa' A IIaL		 h$ 	AEz!U#		 ! 	A1n-NN$E8$88	 - $ s   C,,	C87C8c                  	
 	 t              	 t              t        t              r7fd	t        t              rfd
nt	              rfd
nt        d      t        t              rlfd	|#ddlm} t        j                  |            dkD  }t        t              r|rfd
n^fd	
nXt	              r|rfd

nEfd
n?t        d      t	              r	t	              rfd
nt        d      t        d      fdi 	
fd} | |      }r|fS |S # t        $ r Y 0w xY w# t        $ r Y 4w xY w)a  
        Replace matching subexpressions of ``self`` with ``value``.

        If ``map = True`` then also return the mapping {old: new} where ``old``
        was a sub-expression found with query and ``new`` is the replacement
        value for it. If the expression itself does not match the query, then
        the returned value will be ``self.xreplace(map)`` otherwise it should
        be ``self.subs(ordered(map.items()))``.

        Traverses an expression tree and performs replacement of matching
        subexpressions from the bottom to the top of the tree. The default
        approach is to do the replacement in a simultaneous fashion so
        changes made are targeted only once. If this is not desired or causes
        problems, ``simultaneous`` can be set to False.

        In addition, if an expression containing more than one Wild symbol
        is being used to match subexpressions and the ``exact`` flag is None
        it will be set to True so the match will only succeed if all non-zero
        values are received for each Wild that appears in the match pattern.
        Setting this to False accepts a match of 0; while setting it True
        accepts all matches that have a 0 in them. See example below for
        cautions.

        The list of possible combinations of queries and replacement values
        is listed below:

        Examples
        ========

        Initial setup

        >>> from sympy import log, sin, cos, tan, Wild, Mul, Add
        >>> from sympy.abc import x, y
        >>> f = log(sin(x)) + tan(sin(x**2))

        1.1. type -> type
            obj.replace(type, newtype)

            When object of type ``type`` is found, replace it with the
            result of passing its argument(s) to ``newtype``.

            >>> f.replace(sin, cos)
            log(cos(x)) + tan(cos(x**2))
            >>> sin(x).replace(sin, cos, map=True)
            (cos(x), {sin(x): cos(x)})
            >>> (x*y).replace(Mul, Add)
            x + y

        1.2. type -> func
            obj.replace(type, func)

            When object of type ``type`` is found, apply ``func`` to its
            argument(s). ``func`` must be written to handle the number
            of arguments of ``type``.

            >>> f.replace(sin, lambda arg: sin(2*arg))
            log(sin(2*x)) + tan(sin(2*x**2))
            >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args)))
            sin(2*x*y)

        2.1. pattern -> expr
            obj.replace(pattern(wild), expr(wild))

            Replace subexpressions matching ``pattern`` with the expression
            written in terms of the Wild symbols in ``pattern``.

            >>> a, b = map(Wild, 'ab')
            >>> f.replace(sin(a), tan(a))
            log(tan(x)) + tan(tan(x**2))
            >>> f.replace(sin(a), tan(a/2))
            log(tan(x/2)) + tan(tan(x**2/2))
            >>> f.replace(sin(a), a)
            log(x) + tan(x**2)
            >>> (x*y).replace(a*x, a)
            y

            Matching is exact by default when more than one Wild symbol
            is used: matching fails unless the match gives non-zero
            values for all Wild symbols:

            >>> (2*x + y).replace(a*x + b, b - a)
            y - 2
            >>> (2*x).replace(a*x + b, b - a)
            2*x

            When set to False, the results may be non-intuitive:

            >>> (2*x).replace(a*x + b, b - a, exact=False)
            2/x

        2.2. pattern -> func
            obj.replace(pattern(wild), lambda wild: expr(wild))

            All behavior is the same as in 2.1 but now a function in terms of
            pattern variables is used rather than an expression:

            >>> f.replace(sin(a), lambda a: sin(2*a))
            log(sin(2*x)) + tan(sin(2*x**2))

        3.1. func -> func
            obj.replace(filter, func)

            Replace subexpression ``e`` with ``func(e)`` if ``filter(e)``
            is True.

            >>> g = 2*sin(x**3)
            >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
            4*sin(x**9)

        The expression itself is also targeted by the query but is done in
        such a fashion that changes are not made twice.

            >>> e = x*(x*y + 1)
            >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x)
            2*x*(2*x*y + 1)

        When matching a single symbol, `exact` will default to True, but
        this may or may not be the behavior that is desired:

        Here, we want `exact=False`:

        >>> from sympy import Function
        >>> f = Function('f')
        >>> e = f(1) + f(0)
        >>> q = f(a), lambda a: f(a + 1)
        >>> e.replace(*q, exact=False)
        f(1) + f(2)
        >>> e.replace(*q, exact=True)
        f(0) + f(2)

        But here, the nature of matching makes selecting
        the right setting tricky:

        >>> e = x**(1 + y)
        >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False)
        x
        >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True)
        x**(-x - y + 1)
        >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False)
        x
        >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True)
        x**(1 - y)

        It is probably better to use a different form of the query
        that describes the target expression more precisely:

        >>> (1 + x**(1 + y)).replace(
        ... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1,
        ... lambda x: x.base**(1 - (x.exp - 1)))
        ...
        x**(1 - y) + 1

        See Also
        ========

        subs: substitution of subexpressions as defined by the objects
              themselves.
        xreplace: exact node replacement in expr tree; also capable of
                  using matching rules

        c                    t        |       S r   r   r   querys    r   r  zBasic.replace.<locals>.<lambda>  s    *T5"9 r   c                "     | j                    S r   r   r   r  r   s     r   r  zBasic.replace.<locals>.<lambda>      eTYY.? r   c                "     | j                    S r   r   r  s     r   r  zBasic.replace.<locals>.<lambda>  r  r   z:given a type, replace() expects another type or a callablec                &    | j                        S r   r   r  s    r   r  zBasic.replace.<locals>.<lambda>  s    $**U"3 r   r	   r   c                \    t        |j                               rj                  |      S | S r   )allvaluesr  r  s     r   r  zBasic.replace.<locals>.<lambda>  s)    v}}/ 49::f3E 59 r   c                &    j                  |      S r   )r  r  s     r   r  zBasic.replace.<locals>.<lambda>  s    %**V2D r   c                    t        d |j                         D              r6 di |j                         D ci c]  \  }}t        |      d d | c}}S | S c c}}w )Nc              3      K   | ]  }|  y wr   r{   )r  vals     r   r  z2Basic.replace.<locals>.<lambda>.<locals>.<genexpr>  s     >ss>s   re   r{   )r  r  r   rS  r   r  r  r  r   s       r   r  zBasic.replace.<locals>.<lambda>  s[    >fmmo>> 49 4E4:LLNCDAqQaC4E DH Cs   Ac                |     di |j                         D ci c]  \  }}t        |      d d | c}}S c c}}w )Nre   r{   )r   rS  r  s       r   r  zBasic.replace.<locals>.<lambda>  s<    % 3E4:LLNCDAqQaC3E Cs   8zGgiven an expression, replace() expects another expression or a callablec                     |       S r   r{   r  s     r   r  zBasic.replace.<locals>.<lambda>  s    eDk r   z4given a callable, replace() expects another callablezGfirst argument to replace() must be a type, an expression or a callablec           	         t        | dd      }|e|r[t        |D cg c]  } ||       c}      }||k7  r6 | j                  | } r%t        |      D ]  \  }}| |k(  s|||   k7  s| c S   ||       } | S c c}w )z4Apply ``F`` to args and then to result.
            r   N)r  r   r   rh  )	rs  Fr   r   newargsr   er   walks	          r   r  zBasic.replace.<locals>.walk  s     2vt,D#$>AT!QZ$>?Gw$RWWg.' )2$ .1#%7qGAJ+-I. rUI %?s   A8c                X     |       }|s|i k(  r | |      }||| k7  r	r|| <   |} | S r   r{   )r   r  r  _query_valuemapmappings      r   rec_replacez"Basic.replace.<locals>.rec_replace  sB    D\F24(=Q$Y()DKr   )r   r   r   r   r3  r   rg   r   r.   ri   r  )r}   r  r   r  r   exactr.   r  rs  r  r  r  r  s    ````    @@@@r   r"  zBasic.replace  ss   F	UOE	UOE eT"9F%&?%?)* * u%3F}(U[[./!3%';F EF%
 JFEF  78 8 e_F9'( ( 45 5	& 	 $$ #G}++w  		  		s"   D9 E	 9	EE		EEc                    t        |      }t        t        |t        |                   }|st	        |      S i }|D ]  }||v r||xx   dz  cc<   d||<    |S )z)Find all subexpressions matching a query.r	   )_make_find_queryrg  filterr   r  )r}   r  groupresultsgroupsr  s         r   findz
Basic.find  sj     've%8%>?@w<F! 'V#6Na'N%&F6N	' Mr   c                T    t              t        fdt        |       D              S )z,Count the number of matching subexpressions.c              3  @   K   | ]  }t         |              y wr   )bool)r  r6  r  s     r   r  zBasic.count.<locals>.<genexpr>  s     I4c
#Is   )r  sumr   )r}   r  s    `r   countzBasic.count  s$     'I/B4/HIIIr   c                   t        |      }t        || j                        sy|i }n|j                         }| |k(  r|S t	        | j
                        t	        |j
                        k7  ry|}t        | j
                  |j
                        D ]c  \  }}||k(  r|j                  r%	 |j                  |      j                  |||      }n#|j                  |      j                  |||      }|c y |S # t        $ r d}Y w xY w)a  
        Helper method for match() that looks for a match between Wild symbols
        in self and expressions in expr.

        Examples
        ========

        >>> from sympy import symbols, Wild, Basic
        >>> a, b, c = symbols('a b c')
        >>> x = Wild('x')
        >>> Basic(a + x, x).matches(Basic(a + b, c)) is None
        True
        >>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
        {x_: b + c}
        NrT  )r   r   r   r   ri   r   r   is_Relationalr   matchesr   )r}   r   	repl_dictrT  r  r   	other_args          r   r  zBasic.matches  s     t}$/I!(I4<tyy>S^+!$))TYY7 	NCi  Q//	1#/FA Q//	1#/FAy	  ! As   &#C55DDc                   t        |      }d } ||      j                   ||       |      }||S ddlm} ddlm} ddlm}m}m	}	 |j                  |||||	      }
t        |      |
z
  rt        t        d            |
t        |      z
  }|s|S |j                  |      }|j                  | |      }|r|j                  |       |S )	a*  
        Pattern matching.

        Wild symbols match all.

        Return ``None`` when expression (self) does not match
        with pattern. Otherwise return a dictionary such that::

          pattern.xreplace(self.match(pattern)) == self

        Examples
        ========

        >>> from sympy import Wild, Sum
        >>> from sympy.abc import x, y
        >>> p = Wild("p")
        >>> q = Wild("q")
        >>> r = Wild("r")
        >>> e = (x+y)**(x+y)
        >>> e.match(p**p)
        {p_: x + y}
        >>> e.match(p**q)
        {p_: x + y, q_: x + y}
        >>> e = (2*x)**2
        >>> e.match(p*q**r)
        {p_: 4, q_: x, r_: 2}
        >>> (p*q**r).xreplace(e.match(p*q**r))
        4*x**2

        Structurally bound symbols are ignored during matching:

        >>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p)))
        {p_: 2}

        But they can be identified if desired:

        >>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p)))
        {p_: 2, q_: x}

        The ``old`` flag will give the old-style pattern matching where
        expressions and patterns are essentially solved to give the
        match. Both of the following give None unless ``old=True``:

        >>> (x - 2).match(p - x, old=True)
        {p_: 2*x - 2}
        >>> (2/x).match(p*x, old=True)
        {p_: 2/x**2}

        c                >    | j                   r| S | j                         S r   )r&  r   r  s    r   r  zBasic.match.<locals>.<lambda>Q  s    1;;a AJJL r   r  r	   r   )r[   r   )
WildTensorWildTensorIndexWildTensorHeadz
            Some `matches` routine did not use a copy of repl_dict
            and injected unexpected symbols. Report this as an
            error at https://github.com/sympy/sympy/issues)r   r  r   r.   functionr[   tensor.tensorr  r  r  r  r  rl   r   r   update)r}   patternrT  	canonicalrt  r.   r[   r  r  r  wildbwildwpatws                 r   r   zBasic.match  s    d '"@	g&&yC&@9H *OO}}T<_n]q6D=Z )> ? @ @
 s1vH "LL3L'HHQKr   c                     ddl m}  || |      S )z7Wrapper for count_ops that returns the operation count.r	   )	count_ops)r  r  )r}   visualr  s      r   r  zBasic.count_opsn  s    'v&&r   c                    |j                  dd      rJ| j                  D cg c]&  }t        |t              r |j                  di |n|( }} | j
                  | S | S c c}w )a  Evaluate objects that are not evaluated by default like limits,
        integrals, sums and products. All objects of this kind will be
        evaluated recursively, unless some species were excluded via 'hints'
        or unless the 'deep' hint was set to 'False'.

        >>> from sympy import Integral
        >>> from sympy.abc import x

        >>> 2*Integral(x, x)
        2*Integral(x, x)

        >>> (2*Integral(x, x)).doit()
        x**2

        >>> (2*Integral(x, x)).doit(deep=False)
        2*Integral(x, x)

        deepTr{   )r   r   r   rg   doitr   )r}   r  termtermss       r   r  z
Basic.doits  sn    & 99VT"59YY@-1 ,6dE+BYTYY''L @E @499e$$K	@s   +Ac                     ddl m}  || fi |S )z+See the simplify function in sympy.simplifyr   )simplify)r:  r  )r}   rl  r  s      r   r  zBasic.simplify  s    4'''r   c                     ddl m}  || |      S )z,See the refine function in sympy.assumptionsr   )refine)sympy.assumptions.refiner  )r}   
assumptionr  s      r   r  zBasic.refine  s    3dJ''r   c                    ddl m} t        |t        |f      r1| }t	        |      D ]  }|j                  |      }||k(  s| |S |}! S y )Nr	   )r'   )rc  r'   r   intrange_eval_derivative)r}   r   rB  r'   r   r   obj2s          r   _eval_derivative_n_timeszBasic._eval_derivative_n_times  sa     	%a#w(C1X ++A.$;$,K 	
 Kr   r  c               f    |s S |j                  |       |dd }|d   }t        |t              rd|z  }n9t        |d      r|j                  }d|z  }n|j
                  j                  }d|z  }|r+t        |d         r|d   }t         fd|D              }|s S   j                  |||fi |S )a	  
        Rewrite *self* using a defined rule.

        Rewriting transforms an expression to another, which is mathematically
        equivalent but structurally different. For example you can rewrite
        trigonometric functions as complex exponentials or combinatorial
        functions as gamma function.

        This method takes a *pattern* and a *rule* as positional arguments.
        *pattern* is optional parameter which defines the types of expressions
        that will be transformed. If it is not passed, all possible expressions
        will be rewritten. *rule* defines how the expression will be rewritten.

        Parameters
        ==========

        args : Expr
            A *rule*, or *pattern* and *rule*.
            - *pattern* is a type or an iterable of types.
            - *rule* can be any object.

        deep : bool, optional
            If ``True``, subexpressions are recursively transformed. Default is
            ``True``.

        Examples
        ========

        If *pattern* is unspecified, all possible expressions are transformed.

        >>> from sympy import cos, sin, exp, I
        >>> from sympy.abc import x
        >>> expr = cos(x) + I*sin(x)
        >>> expr.rewrite(exp)
        exp(I*x)

        Pattern can be a type or an iterable of types.

        >>> expr.rewrite(sin, exp)
        exp(I*x)/2 + cos(x) - exp(-I*x)/2
        >>> expr.rewrite([cos,], exp)
        exp(I*x)/2 + I*sin(x) + exp(-I*x)/2
        >>> expr.rewrite([cos, sin], exp)
        exp(I*x)

        Rewriting behavior can be implemented by defining ``_eval_rewrite()``
        method.

        >>> from sympy import Expr, sqrt, pi
        >>> class MySin(Expr):
        ...     def _eval_rewrite(self, rule, args, **hints):
        ...         x, = args
        ...         if rule == cos:
        ...             return cos(pi/2 - x, evaluate=False)
        ...         if rule == sqrt:
        ...             return sqrt(1 - cos(x)**2)
        >>> MySin(MySin(x)).rewrite(cos)
        cos(-cos(-x + pi/2) + pi/2)
        >>> MySin(x).rewrite(sqrt)
        sqrt(1 - cos(x)**2)

        Defining ``_eval_rewrite_as_[...]()`` method is supported for backwards
        compatibility reason. This may be removed in the future and using it is
        discouraged.

        >>> class MySin(Expr):
        ...     def _eval_rewrite_as_cos(self, *args, **hints):
        ...         x, = args
        ...         return cos(pi/2 - x, evaluate=False)
        >>> MySin(x).rewrite(cos)
        cos(-x + pi/2)

        r  Nre   z_eval_rewrite_as_%srh   r   c              3  F   K   | ]  }j                  |      s|  y wr   )r!  r  r   r}   s     r   r  z Basic.rewrite.<locals>.<genexpr>  s     >!$((1+A>s   !!)	r  r   rS  r   rh   r   r   r   _rewrite)r}   r  r   r  r  r  methodclsnames   `       r   rewritezBasic.rewrite  s    T K$s)Bx dC *T1FT:&mmG*W4F nn--G*W4F
#!!*>w>>G t}}WdF<e<<r   c                Z    |j                  dd      }|r- j                  D cg c]  } |j                  |||fi | }}n j                  }|rt         fd|D              r0t	         |d       }|	 ||i |}	n  j
                  ||fi |}	|	|	S |s S   j                  | S c c}w )Nr  Tc              3  6   K   | ]  }t        |        y wr   r  r  s     r   r  z!Basic._rewrite.<locals>.<genexpr>  s     Cajq1Cs   )r   r   r  r  r  _eval_rewriter   )
r}   r  r  r  r  r  r   r   meth	rewrittens
   `         r   r  zBasic._rewrite  s    yy&!YY( AJJwf>> (D ( 99D#C7CC4.D $0%0	.D..tTCUC	$  Ktyy$(s   B(c                     y r   r{   )r}   r  r   r  s       r   r  zBasic._eval_rewrite%  r   r   c           
        |j                   j                  }t        t              }|j                  D ]j  }	 d t        |      j                         D        }t        j                  |      D ]/  \  }}||   j                  |D cg c]  }|||   vs| c}       1 l |j                  |g       D ]
  }	 |	|      } |S c c}w # t        $ r Y w xY w)Nc              3     K   | ]7  }|t         j                  v r#t         j                  |   j                          9 y wr   )rg   "_constructor_postprocessor_mappingr   )r  r   s     r   r  z9Basic._exec_constructor_postprocessors.<locals>.<genexpr>8  s:      *eFFF <<SAGGI*s   =?)r   rh   r   rg  r   r   mror   from_iterableextendr   r   )
r   r   r  postprocessorsr   postprocessor_mappingsr  r  jfs
             r    _exec_constructor_postprocessorsz&Basic._exec_constructor_postprocessors*  s     --(($T* 
	A	*#Aw{{}*&
 "//0FG [DAq"1%,,-YAa~VWGX>Xa-YZ[
	  ##GR0 	AC&C	 
 .Z s*   ACC C 	C C	CCc                    | j                   }ddlm}  |        || j                   k(  rt        d      | j                         S )z
        Convert *self* to a symbolic expression of SageMath.

        This version of the method is merely a placeholder.
        r   )
sympy_initz)conversion to SageMath is not implemented)_sage_sage.interfaces.sympyr
  r   )r}   
old_methodr
  s      r   r  zBasic._sage_G  s;     [[
4$%&QRR ;;= r   c                     yNFr{   r|   s    r   could_extract_minus_signzBasic.could_extract_minus_signV  s    r   c                    ddl m} ddlm} t	         ||        ||            D ]T  }d|v r y|\  } }t        | |      rt        ||      s y|r || |      c S | |k(  r| j                  |j                  k(  rT y y)a  Return True if a and b are structurally the same, else False.
        If `approx` is supplied, it will be used to test whether two
        numbers are the same or not. By default, only numbers of the
        same type will compare equal, so S.Half != Float(0.5).

        Examples
        ========

        In SymPy (unlike Python) two numbers do not compare the same if they are
        not of the same type:

        >>> from sympy import S
        >>> 2.0 == S(2)
        False
        >>> 0.5 == S.Half
        False

        By supplying a function with which to compare two numbers, such
        differences can be ignored. e.g. `equal_valued` will return True
        for decimal numbers having a denominator that is a power of 2,
        regardless of precision.

        >>> from sympy import Float
        >>> from sympy.core.numbers import equal_valued
        >>> (S.Half/4).is_same(Float(0.125, 1), equal_valued)
        True
        >>> Float(1, 2).is_same(Float(1, 10), equal_valued)
        True

        But decimals without a power of 2 denominator will compare
        as not being the same.

        >>> Float(0.1, 9).is_same(Float(0.1, 10), equal_valued)
        False

        But arbitrary differences can be ignored by supplying a function
        to test the equivalence of two numbers:

        >>> import math
        >>> Float(0.1, 9).is_same(Float(0.1, 10), math.isclose)
        True

        Other objects might compare the same even though types are not the
        same. This routine will only return True if two expressions are
        identical in terms of class types.

        >>> from sympy import eye, Basic
        >>> eye(1) == S(eye(1))  # mutable vs immutable
        True
        >>> Basic.is_same(eye(1), S(eye(1)))
        False

        r	   )Number)postorder_traversalNFT)rc  r  	traversalr  r   r   r   )r   r   approxr  potr   s         r   is_samezBasic.is_sameY  s    l 	$9SVSV, 
	AqyDAq!V$!!V, !!Q<'Fq{{akk9
	 r   )returnr  r   )r  
set[Basic])r  ry   )FT)r   r  )FTNFr  )T)grh   
__module____qualname____doc__	__slots____annotations__propertyr~   r   r>  is_Atomr&  	is_symbol
is_Indexedr   is_Wildis_Functionis_Addrz  is_Powr   is_Floatr   
is_Integeris_NumberSymbolis_Orderis_Derivativeis_Piecewiseis_Polyis_AlgebraicNumberr  is_Equality
is_Booleanis_Not	is_Matrix	is_Vectoris_Point	is_MatAdd	is_MatMulr   r   r   r   r   r   r   r   r   r   r   r   staticmethodr   classmethodr   r   r   r   r   r   r   r   r  r   r  r   r  r,  r+  r<  rC  r   r   r   rK  r  rk  rx  r   r  r!  r  r  r  r"  r  r  r  r   r  r  r  r  r  r  r  r  r   r  r  r  r  __classcell__rE  s   @r   rg   rg   ~   s:   *VI
  ( IGIIJHGKFFFIHKJOHMLGMKJFIIHII!!D$%'/  >4l  #  #D 0 0" " " ? ?<&(T	!,E\M^ A A"  , \  :1"    (. ,  , \  2  >  	M^ m m^	?B, .. ..`76 *2 *2X!F@,D$J
,\Ob'
4(
(
& #' f=P & *,& 8!Cr   rg   c                  f    e Zd ZdZdZdZddZddZd Ze	d        Z
edd	       Zd
 Zed        Zy)Atomz
    A parent class for atomic things. An atom is an expression with no subexpressions.

    Examples
    ========

    Symbol, Number, Rational, Integer, ...
    But not: Add, Mul, Pow, ...
    Tr{   Nc                6    | |k(  r|i S |j                         S y r   )r   )r}   r   r  rT  s       r   r  zAtom.matches  s&    4< 	>>## r   c                &    |j                  | |       S r   )r   )r}   r  r^  s      r   r   zAtom.xreplace  s    xxd##r   c                    | S r   r{   )r}   r  s     r   r  z	Atom.doit      r   c                     dd| j                   fS )Nr   r   r   r   s    r   r   zAtom.class_key  s    !S\\!!r   c                    | j                         dt        |       fft        j                  j	                         t        j                  fS )Nr	   )r   rS  r   r!   r   )r}   r   s     r   r   zAtom.sort_key  s2    ~~!c$i\!2AEENN4DaeeKKr   c                    | S r   r{   )r}   rl  s     r   _eval_simplifyzAtom._eval_simplify  r@  r   c                    t        d      )NzXAtoms have no args. It might be necessary to make a check for Atoms in the calling code.)AttributeErrorr|   s    r   r   zAtom._sorted_args  s      : ; 	;r   r  r  r   )rh   r  r  r  r!  r  r  r   r  r9  r   r   r   rD  r   r   r{   r   r   r<  r<    se     GI$$ " " L L ; ;r   r<  c                   t        |       }t               }t        | t              rt	        | dd      }|| hS t               S ddlm} ddlm}m	} t               }|D ]|  }	|	|v r|j                          |j                  |	       t        |	|      r|	|v r|j                  |	       Kt        |	||f      sZ|s|j                          |j                  |	       ~ |S )aM  Return atom-like quantities as far as substitution is
    concerned: Derivatives, Functions and Symbols. Do not
    return any 'atoms' that are inside such quantities unless
    they also appear outside, too, unless `recursive` is True.

    Examples
    ========

    >>> from sympy import Derivative, Function, cos
    >>> from sympy.abc import x, y
    >>> from sympy.core.basic import _atomic
    >>> f = Function('f')
    >>> _atomic(x + y)
    {x, y}
    >>> _atomic(x + f(y))
    {x, f(y)}
    >>> _atomic(Derivative(f(x), x) + cos(x) + y)
    {y, cos(x), Derivative(f(x), x)}

    r   Nr	   r.  )r2   rZ   )r   r  r   rg   r  r   r-   r  r2   rZ   skipr  )
r  	recursiver  seenr  r-   r2   rZ   r  r   s
             r   _atomicrK    s    * a
 C5D!Uq.$/<3Ju.EE 
9HHJa Q$YIIaLJ12
IIaL
 Lr   c                     	 t                t         t              r fdS t         t              r fdS  S # t        $ r Y 7w xY w)z4Convert the argument of Basic.find() into a callablec                    t        |       S r   r  r  s    r   r  z"_make_find_query.<locals>.<lambda>	  s    JtU3 r   c                *    | j                        d uS r   r  r  s    r   r  z"_make_find_query.<locals>.<lambda>	  s    DJJu-T9 r   )r   r   r   r   rg   )r  s   `r   r  r  	  sL     %33	E5	!99L  s   : 	AA)r   )preorder_traversalr  r  z
    Using preorder_traversal from the sympy.core.basic submodule is
    deprecated.

    Instead, use preorder_traversal from the top-level sympy namespace, like

        sympy.preorder_traversal
    z1.10z$deprecated-traversal-functions-movedr  N)rm   r   rn   r   r  r  r  )9r  
__future__r   collectionsr   collections.abcr   	itertoolsr   r   	functoolsr   r   r
   cacher   r   r   r   r   re  r   r   r   r   _print_helpersr   sympy.utilities.decoratorr   sympy.utilities.exceptionsr   sympy.utilities.iterablesr   r   sympy.utilities.miscr   r   inspectr   r   rj   rt   rg   r  rd  r   _args_sortkeyr<  rK  r  	singletonr   r  rO  r   r  r  r{   r   r   <module>r^     s    - " # # (   3  I I  % % 0 @ @ 6 	$$ L+!\^ I ^ @A == 5==)
 5 !-;5 -;`+\
  Z $E  r   