
    \h+                   8   S r SSKJr  SSKJr  SSKJrJr  SSKJ	r	  SSK
Jr  SSKJrJr  SS	KJr  SS
KJr  SSKJrJrJrJr  SSKJr  SSKJrJr  SSKJr  SSKJr  SSK J!r!  SSK"J#r#J$r$  SSK%J&r&J'r'  \(       a#  SSKJ(r(J)r)J*r*  SSK+J,r,  SSKJ-r-  SSK.J/r/  \)" SSS9r0S r1/ SQr2S+S jr3\S 5       r4\S 5       r5 " S S\5      r6\6Rn                  r8\" \6Rr                  5      r:\" \65         " S  S!\65      r;S,S" jr<S# r=SS$K>J?r?  SS%K@JArBJCrCJDrD  \" S&S'S(S)9" \B5      rAg*)-z'Base class for all the objects in SymPy    )annotations)Counter)MappingIterable)zip_longest)
cmp_to_key)TYPE_CHECKINGoverload   )_prepare_class_assumptions)cacheit)_sympifysympifySympifyError_external_converter)ordered)KindUndefinedKind)	Printable)
deprecated)sympy_deprecation_warning)iterablenumbered_symbols)
filldedent	func_name)ClassVarTypeVarAny)Self)	StdFactKBSymbolTbasicBasic)boundc                d     [        U 5      $ ! [         a    [        S[        U 5      -  5      ef = f)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    H/var/www/auris/envauris/lib/python3.13/site-packages/sympy/core/basic.pyas_Basicr*       s?    ~ 7);  	s   
 "/)DZeroOneHalfInfinityNaNNegativeOneNegativeInfinityIntegerRationalFloatExp1PiImaginaryUnitr"   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                f   U R                   nUR                   nX#:X  a  g[        U[        5      (       d  g[        [        5      S-   n [        R                  U5      n [        R                  U5      nXT:X  a  Xd:X  a	  X#:  X#:  -
  $ XV:  XV:  -
  $ ! [         a    Un N@f = f! [         a    Un N<f = f)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   )__name__
issubclassr$   lenordering_of_classesindex
ValueError)xyn1n2UNKNOWNi1i2s          r)   	_cmp_namer}   X   s    . 
B	
B	x a%&*G &&r* &&r* 
}BG$$G      s$   B B! BB!B0/B0c                    [        5       n[        U5      nU H+  nUR                  U S 5      nUc  M  UR                  U5        M-     U$ N)set_get_postprocessors_for_typegetupdate)clsnamearg_typepostprocessorsmappingsmappingfs         r)   _get_postprocessorsr      sJ     UN+H5HKK&=!!!$      c                B    [        S U R                  5        5       5      $ )Nc              3  t   #    U  H.  nU[         R                  ;   d  M  [         R                  U   v   M0     g 7fr   )r$   "_constructor_postprocessor_mapping).0clss     r)   	<genexpr>/_get_postprocessors_for_type.<locals>.<genexpr>   s2      !C%::: 	6005!s   88)tuplemro)r   s    r)   r   r      s"     <<>  r   c                    ^  \ rS rSr% SrSrS\S'   S\S'   \S 5       rU 4S	 jr	S
r
S
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
rS
r S
r!S
r"S
r#S
r$S
r%S
r&S
r'S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S '   S\S!'   S\S"'   S\S#'   S\S$'   S\S%'   S\S&'   S\S''   S\S('   S\S)'   S\S*'   S\S+'   S\S,'   \(r)S-\S.'   S/ r*S0 r+S1 r,S2 r-S3 r.U 4S4 jr/SoS5 jr0S6 r1\S7 5       r2S8 r3\4S9 5       r5\4SpS: j5       r6\7SqS; j5       r8S< r9S= r:S> r;SqS? jr<\=SrS@ j5       r>\=SsSA j5       r>StSB jr>\SrSC j5       r?\SD 5       r@SuSE jrA\SvSF j5       rBSG rCSH rD\SI 5       rESwSJ jrF\SK 5       rG\SxSL j5       rH\SM 5       rISySO jrJ\=SqSzSP jj5       rK\=SqS{SQ jj5       rK\=S|SR j5       rK Sq     S}SS jjrK\7ST 5       rLS~SU jrMSV rNSW rO\7SX 5       rPSSY jrQ\7SZ 5       rRS[ rSSSS\ jjrTSS] jrUS^ rVSS_ jrWSS` jrXSSa jrYSb rZSSc jr[SSd jr\Se r]SNSf.Sg jr^Sh r_Si r`0 ra\4Sj 5       rbSk rcSwSl jrdSqSm jreSnrfU =rg$ )r$      aJ  
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, ...]r   z
int | Noner   c                    g)NT selfs    r)   	__sympy__Basic.__sympy__   s    r   c                8   > [         TU ]  5         [        U 5        g r   )super__init_subclass__r   )r   	__class__s    r)   r   Basic.__init_subclass__   s    
 	!#"3'r   FzClassVar[StdFactKB]default_assumptionszbool | Noneis_compositeis_nonintegeris_extended_positiveis_negative
is_complexis_extended_nonpositive
is_integeris_positiveis_rationalis_extended_nonnegativeis_infiniteis_antihermitianis_extended_negativeis_extended_real	is_finiteis_polaris_imaginaryis_transcendentalis_extended_nonzero
is_nonzerois_oddis_algebraicis_primeis_commutativeis_nonnegativeis_nonpositiveis_hermitianis_irrationalis_realis_zerois_evenr   kindc                l    [         R                  U 5      nU R                  Ul        S Ul        Xl        U$ r   )object__new__r   r   r   r   )r   argsobjs      r)   r   Basic.__new__   s/    nnS!22
	
r   c                4    U R                   " U R                  6 $ r   )funcr   r   s    r)   copy
Basic.copy(  s    yy$))$$r   c                    U R                   $ r   r   r   s    r)   __getnewargs__Basic.__getnewargs__+  s    yyr   c                    g r   r   r   s    r)   __getstate__Basic.__getstate__.      r   c                N    UR                  5        H  u  p#[        XU5        M     g r   )itemssetattr)r   statenamevalues       r)   __setstate__Basic.__setstate__1  s     ;;=KDD& )r   c                H   > US:  a  Sn[        U5      e[        TU ]	  U5      $ )N   z6Only pickle protocol 2 or higher is supported by SymPy)NotImplementedErrorr   __reduce_ex__)r   protocolmsgr   s      r)   r   Basic.__reduce_ex__5  s*    a<JC%c**w$X..r   c                    U R                   nUc6  [        [        U 5      R                  4U R	                  5       -   5      nXl         U$ r   )r   hashtyperp   _hashable_content)r   hs     r)   __hash__Basic.__hash__;  sA     KK9d4j))+d.D.D.FFGAKr   c                    U R                   $ )ac  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__.r   r   s    r)   r   Basic._hashable_contentD  s     zzr   c                    0 $ )a9  
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)   assumptions0Basic.assumptions0N  s	    < 	r   c                ^   XL a  gU R                   nUR                   n[        X#5      nU(       a  U$ U R                  5       nUR                  5       n[        U5      n[        U5      nXx:  Xx:  -
  nU(       a  U$ [	        XV5       H  u  p[        U	[        5      (       a  U	R                  U
5      nOn[        U	[        5      (       aP  [        U	[        5      (       a  [        U	6 OU	n	[        U
[        5      (       a  [        U
6 OU
n
U	R                  U
5      nO	X:  X:  -
  nU(       d  M  Us  $    g)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   r}   r   rr   zip
isinstancer$   compare	frozenset)r   otherrx   ry   cstotlen_stlen_otlrs              r)   r   Basic.comparen  s   < =^^__bH##%$$&RR_1HKDA!U##IIaLAy))!+Ay!9!9E1Iq!+Ay!9!9E1IqIIaLUqu%q   r   c                $    U " [        U5      0 UD6$ )a  
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)

)r   )r   r   assumptionss      r)   fromiterBasic.fromiter  s      E$K/;//r   c                     SSU R                   4$ )zNice order of classes.   r   rp   r   s    r)   	class_keyBasic.class_key  s     !S\\!!r   c           	       ^ U4S jnU R                   n[        U5      [        U Vs/ s H
  oB" U5      PM     sn5      4nU R                  5       U[        R
                  R                  5       [        R
                  4$ s  snf )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                T   > [        U [        5      (       a  U R                  T5      $ U $ r   )r   r$   sort_key)argorders    r)   	inner_key!Basic.sort_key.<locals>.inner_key  s$    #u%%||E**
r   )_sorted_argsrr   r   r  Sr,   r  )r   r  r  r   r  s    `   r)   r  Basic.sort_key  sf    *	   4y%4 @4C34 @AA~~quu~~'7>> !As   A>
c                    [        U5      R                   H(  n[        R                  " U5      nUc  M  X" U5      :H  s  $    [	        US5      (       a  XR                  5       :H  $ [        $ )aT  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   r   hasattrr  NotImplemented)r   r   
superclassconvs       r)   _do_eq_sympifyBasic._do_eq_sympify  sa     u+--J&**:6DtE{** . 5)$$==?**r   c                   XL a  g[        U[        5      (       d  U R                  U5      $ U R                  (       a  UR                  (       d  [	        U 5      [	        U5      :w  a  gU R                  5       UR                  5       p2X#:w  a  g[        X#5       HI  u  p#[        U[        5      (       d  M  UR                  (       d  M/  [	        U5      [	        U5      :w  d  MI    g   g)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   r$   r  	is_Numberr   r   r   )r   r   abs       r)   __eq__Basic.__eq__  s    * =%''&&u-- EOOT
d5k)%%')@)@)B16IDAa''{{{tAw$q'1	 
 r   c                    X:X  + $ )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__Basic.__ne__  s       r   c                   U R                  5       n[        U5      nUR                  5       nUR                   Vs/ s H  oUR                  (       d  M  UPM     nn[	        U5      S:X  a  UR                  5       nOX4:H  $ Uc0  UR                  n[	        U5      S:X  a  UR                  5       nOX4:H  $ UR                  5       n	UR                  Xy05      UR                  X)05      :H  $ s  snf )a8  
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_Dummyrr   popr   xreplace)
r   r   symbolsoidummy_symbolsdummysymbolstmps
             r)   dummy_eqBasic.dummy_eq&  s    . MMOUOJJL$%NNANqjjNA}"!%%'E6M>nnG7|q  voozz5,'1::vm+DDD# Bs   C&C&c                    g r   r   r   s    r)   atomsBasic.atomsT  s    #&r   c                    g r   r   )r   typess     r)   r:  r;  V  s    CFr   c           	     P   [        U 5      nU(       aa  [        U Vs/ s H%  n[        U[        5      (       a  UO
[        U5      PM'     sn5      nU Vs1 s H  n[        XT5      (       d  M  UiM     sn$ U Vs1 s H  oUR                  (       a  M  UiM     sn$ s  snf s  snf s  snf )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)}

)_preorder_traversalr   r   r   r   )r   r=  nodesttypes2nodes         r)   r:  r;  Y  s    J $D)5Q5aAt!4!4A$q'A5QRF%*GUTj.FDUGG%*<UT))DU<< RG<s   ,BB+B8B#B#c                V    [        5       nUR                  " S U R                   5       6 $ )a  Return from the atoms of self those which are free symbols.

Not all free symbols are ``Symbol`` (see examples)

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.

Examples
========

>>> from sympy import Derivative, Integral, IndexedBase
>>> from sympy.abc import x, y, n
>>> (x + 1).free_symbols
{x}
>>> Integral(x, y).free_symbols
{x, y}

Not all free symbols are actually symbols:

>>> IndexedBase('F')[0].free_symbols
{F, F[0]}

The symbols of differentiation are not included unless they
appear in the expression being differentiated.

>>> Derivative(x + y, y).free_symbols
{x, y}
>>> Derivative(x, y).free_symbols
{x}
>>> Derivative(x, (y, n)).free_symbols
{n, x}

If you want to know if a symbol is in the variables of the
Derivative you can do so as follows:

>>> Derivative(x, y).has_free(y)
True
c              3  8   #    U  H  oR                   v   M     g 7fr   )r+  )r   r"  s     r)   r   %Basic.free_symbols.<locals>.<genexpr>  s     ?Y^^Ys   )r   unionr   )r   emptys     r)   r+  Basic.free_symbols  s%    ^  E{{?TYY?@@r   c                ,    [        SSSS9  [        5       $ )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_symbolsBasic.expr_free_symbols  s!    ! # &+'E	G ur   c                t   ^ SSK JmJn  U4S jnU R                  U5      (       d  U $ U R	                  S USS9$ )a  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                N  > U R                   n[        U R                  5      nX!-   Vs0 s H
  o3T" 5       _M     nnU R                  U5      n U R	                  U R
                  5      n U R	                  UR                  5        VVs0 s H  u  pVXe_M	     snn5      $ s  snf s  snnf r   )r+  r   bound_symbolssubsr.  canonical_variablesr   )rv   freer%   r2  dkvrR  s          r)   canBasic.as_dummy.<locals>.can  s    >>D(E%*\2\EG\A2q	A

1001A::	:	qt	:;; 3
 ;s   BB!
c                    [        U S5      $ )NrT  )r  )rv   s    r)   <lambda> Basic.as_dummy.<locals>.<lambda>  s    ga1r   F)simultaneous)r/  rR  r"   hasreplace)r   r"   r[  rR  s      @r)   r*  Basic.as_dummy  sB    8 	*		< xxK||1    	 r   c                \   [        U SS5      nUc  0 $ [        S5      n0 nU R                  [        U5      -
   Vs1 s H  oDR                  iM     nnU HP  n[        U5      nUR                  (       a-  UR                  U;   a  [        U5      nUR                  U;   a  M  XsU'   MR     U$ s  snf )a  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}
rT  N_)getattrr   r+  r   r   next	is_Symbol)r   r%   dumsrepsr2  namesr#  rX  s           r)   rV  Basic.canonical_variables  s     %,D/4$H=I$ "&!2!2SZ!?@!?A!?@AT
A{{ffoT
A ffoG   As   B)c                    [        U 5      (       a  U " U6 $ U R                  (       a7  U R                   Vs/ s H  o"R                  " U6 PM     nnU R                  " U6 $ U $ s  snf )ad  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
)callabler   rcallr   )r   r   subnewargss       r)   ro  Basic.rcall1  sV     D>>;YY3799=9Cyy$'9G=99g&&K >s   A c                \    SSK Jn  SSKJn  U R	                  U5      (       a  g U" X5      S L$ )Nr   )	hypersimp)	Piecewise)sympy.simplify.simplifyrt  $sympy.functions.elementary.piecewiseru  ra  )r   rY  rt  ru  s       r)   is_hypergeometricBasic.is_hypergeometricH  s*    5B88I!--r   c                "    U R                  5       $ )aL  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

)_eval_is_comparabler   s    r)   is_comparableBasic.is_comparableO  s    6 ''))r   c                    gNFr   r   s    r)   r{  Basic._eval_is_comparablel  s    r   c                    U R                   $ )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   
Basic.funcp  s    0 ~~r   c                    U R                   $ )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   
Basic.args  s    < zzr   c                    U R                   $ )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  Basic._sorted_args  s     yyr   Tc                &    [         R                  U 4$ )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_primitiveBasic.as_content_primitive  s     uud{r   c                    g r   r   r   arg1arg2kwargss       r)   rU  
Basic.subs  s    nqr   c                    g r   r   r  s       r)   rU  r    s    vyr   c                    g r   r   r  s       r)   rU  r    s    Z]r   c                  ^^ SSK Jn  SSKJnJm  SSKJn  SnUcj  [        U[        5      (       a  UnSnOT[        X[        45      (       a  SnUR                  5       nO+[        U5      (       d  [        [        S5      5      eUnOX4/nSU4S jjn	SS	 jn
U VVs/ s H  u  pU	" U5      U
" U5      4PM     nnnU VVs/ s H  u  p[        X5      (       a  M  X4PM     nnnUR                  S
S5      nU(       a  SSKJmJn  ['        U5      n[)        [+        USU4S jU4S95      nU Vs/ s H
  nUUU   4PM     nnU(       d^  [-        U5       VVs/ s H  u  nnUS   U;   d  M  UPM     nnn[/        U5       H$  nUR1                  SUR                  U5      5        M&     U(       a  0 nU nSUS'   U" S5      nU HQ  u  nnUR2                  nUc  SnU" SUS9nUR4                  " UUU-  40 UD6n[        U[6        5      (       d    O	UUU'   MS     [8        R:                  UU'   UR=                  U5      $ U nU H2  u  nnUR4                  " UU40 UD6n[        U[6        5      (       a  M1    U$    U$ s  snnf s  snnf s  snf s  snnf )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   )DictrQ  )_illegalFTz
                   When a single argument is passed to subs
                   it should be a dictionary of old: new pairs or an iterable
                   of (old, new) tuples.c                   > [        U [        5      (       a  T" U 5      $ [        U [        5      (       a
  [        U SS9$ [        U SS9$ NF)strictTr   strr   r   )oldr"   s    r)   sympify_oldBasic.subs.<locals>.sympify_oldQ  sA    #s##c{"C&&s511s400r   c                `    [        U [        [        45      (       a
  [        U SS9$ [        U SS9$ r  r  )news    r)   sympify_newBasic.subs.<locals>.sympify_new[  s-    #T{++s511s400r   r`  )_nodesdefault_sort_keyc                   > T" U 5      * $ r   r   )rv   r  s    r)   r^  Basic.subs.<locals>.<lambda>s  s    6!9*r   )defaultkeysr   hack2subs_msubs_d)commutativereturnr$   )
containersr  r/  rR  r"   numbersr  r   r   r   r   r   ru   r   _aresamer-  sortingr  r  dictlistr   	enumeratereversedinsertr   _subsr$   r  r,   r.  )r   r  r  r  r  rR  r  	unorderedr   r  r  s1s2sequencer`  r  sequence_dictrY  r2  seqredorj  rvmr  r  comrX  r"   r  s                               @@r)   rU  r    s   f 	%)% 	<$$$ 	D/22 	

d^^  -, "- . .
 \NE	1	1 FKKU62[_k"o6UK ,4L88B;KHRH8Lzz.%89 NM W]E$ A  A 899q!M!,-qH9(1((;R(;fas1v?Q(;R!$AOOAx||A7 ( DB"F7OhA$S((;C(4 XXc1Q31&1!"e,,Q % eeDG;;t$$B$SXXc31&1!"e,,I	 % Ii L M" : Ss$   I5 I;I;.JJ*Jc                r   ^ U4S jn[        X5      (       a  U$ U R                  X5      nUc	  U" XU5      nU$ )aj	  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                t  > Sn[        U R                  5      n[        U5       HF  u  pV[        US5      (       d  M  UR                  " X40 TD6n[        XdU   5      (       a  M@  SnXdU'   MH     U(       a  U R                  " U6 nTR                  SS5      nU(       a  U R                  (       a  UR                  (       dw  [        R                  n	/ n
U H+  nUR                  (       a  X-  n	M  U
R                  U5        M-     U R                  " U
6 n
U	[        R                  L a  U
$ U R                  XSS9$ U$ U $ )z9
Try to replace old with new in any of self's arguments.
F
_eval_subsTr  )evaluate)r  r   r  r  r  r  r   r   is_Mulr  r,   r!  append)r   r  r  hitr   r2  r  r  r  coeff	nonnumberhintss              r)   fallbackBasic._subs.<locals>.fallback  s	    C		?D#D/sL11ii2E2!W--C!G * YY%		'51T[[EEE "I!;;!JE%,,Q/	 "
 !%		9 5I~((#yyEyJJ	Kr   )r  r  )r   r  r  r  r  r  s      `  r)   r  Basic._subs  s@    P	@ DJ__S&:$S)B	r   c                    g)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   r  r  s      r)   r  Basic._eval_subs  s     r   c                ,    U R                  U5      u  p#U$ )aV  
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   re  s       r)   r.  Basic.xreplace  s    | >>$'r   c                .   X;   a  X   S4$ U(       a  / nSnU R                    HI  n[        USS5      nUb%  U" U5      nUR                  US   5        X6S   -  nM8  UR                  U5        MK     [        U5      nU(       a  U R                  " U6 S4$ U S4$ )zF
Helper for xreplace. Tracks whether a replacement actually occurred.
TFr  Nr   r   )r   rf  r  r   r   )r   r  r   changedr"  r  a_xrs          r)   r  Basic._xreplaceT  s     <:t##DGYY#A{D9	($T?DKKQ(Aw&GKKN  ;Dyy$'--U{r   c                0    U R                   " [        /UQ76 $ )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)   ra  	Basic.hasj  s    ^ yy-H--r   c                z   ^ [        T5      [        La  [        S5      e[        U4S j[	        U 5       5       5      $ )a  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  ,   >#    U  H	  oT;   v   M     g 7fr   r   )r   r"  r0  s     r)   r   "Basic.has_xfree.<locals>.<genexpr>  s     6#5a6#5s   )r   r   r'   anyiterfreeargs)r   r0  s    `r)   	has_xfreeBasic.has_xfree  s3    . 7#4556<#5666r   c                $   U(       d  gUS   n[        U5      S:X  a9  [        U5      (       a)  [        U[        5      (       d  [	        [        S5      5      e[        U5      nU R                  U5      nU(       a  U$ U R                  " [        /UQ76 $ )a  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)`)
rr   r   r   r$   r'   r   r   r  r  r  )r   r  p0r0  r  s        r)   has_freeBasic.has_free  s    6 a[x=A(2,,z"e7L7L J (7 8 9 9
 M^^AIyy111r   c                H  ^ [        5       n[        5       nU Hr  n[        U[        5      (       a(  [        U[        5      (       a  UR                  U5        M@  [        U[        5      (       d   [        U5      nUR                  U5        Mt     [        U5      nU" U 5       H  nXt;   a    g[        Xv5      (       d  M    g   XC-
   HH  n[        US5      (       d  M  UR                  5       m[        U4S jU" U 5       5       5      (       d  MH    g   g! [         a     GM  f = f)NT_has_matcherc              3  4   >#    U  H  nT" U5      v   M     g 7fr   r   )r   r  matchs     r)   r   Basic._has.<locals>.<genexpr>   s     8#5::s   F)r   r   r   rq   r$   addr   r   r   r  r  r  )	r   r  r  type_setp_setpr=  r2  r  s	           @r)   r  
Basic._has  s    5A!T""z!U';';Qa'' A IIaL  h$Az!##	   !A1n--NN$E8$888 " - $ s   .D
D! D!c                :  ^^^^^	^
^^  [        T5      m [        T5      m[        T[        5      (       aD  U4S jm	[        T[        5      (       a  U4S jm
O[	        T5      (       a  U4S jm
O[        S5      e[        T[        5      (       a  U4S jm	Uc#  SSKJn  [        TR                  U5      5      S:  n[        T[        5      (       a  U(       a  U4S jm
OvU4S	 jm
Oo[	        T5      (       a  U(       a  U4S
 jm
OQU4S jm
OJ[        S5      e[	        T5      (       a$  Tm	[	        T5      (       a  U4S jm
O[        S5      e[        S5      eUU4S jm0 mU	U
UU4S jnT" X5      nT(       a  UT4$ U$ ! [         a     GNsf = f! [         a     GNxf = f)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                   > [        U T5      $ r   r   r(   querys    r)   r^  Basic.replace.<locals>.<lambda>  s    *T5"9r   c                "   > T" U R                   6 $ r   r   r(   resultr   s     r)   r^  r        eTYY.?r   c                "   > T" U R                   6 $ r   r   r  s     r)   r^  r    r  r   z:given a type, replace() expects another type or a callablec                &   > U R                  T5      $ r   r  r  s    r)   r^  r    s    $**U"3r   r   )r8   c                f   > [        UR                  5       5      (       a  TR                  U5      $ U $ r   )allvaluesrU  r  s     r)   r^  r    s/    v}}// 49::f3E 4:594:r   c                &   > TR                  U5      $ r   )rU  r  s     r)   r^  r    s    %**V2Dr   c                   > [        S UR                  5        5       5      (       a8  T" S0 UR                  5        VVs0 s H  u  p#[        U5      S S U_M     snnD6$ U $ s  snnf )Nc              3  $   #    U  H  ov   M     g 7fr   r   )r   vals     r)   r   2Basic.replace.<locals>.<lambda>.<locals>.<genexpr>  s     >ossos   ro   r   )r  r  r   r  r(   r  rY  rZ  r   s       r)   r^  r    se    >fmmo>>> 49 4E4:LLNCNDAQaNC4E 4IDH4ICs   A!c                   > T" S0 UR                  5        VVs0 s H  u  p#[        U5      S S U_M     snnD6$ s  snnf )Nro   r   )r   r  r
  s       r)   r^  r    s<    % 3E4:LLNCNDAQaNC3ECs   :zGgiven an expression, replace() expects another expression or a callablec                   > T" U 5      $ r   r   r  s     r)   r^  r    s	    eDkr   z4given a callable, replace() expects another callablezGfirst argument to replace() must be a type, an expression or a callablec           	       > [        U SS5      nUbs  U(       ad  [        U Vs/ s H  nT" X15      PM     sn5      nX$:w  a=  U R                  " U6 n T(       a'  [        U5       H  u  pVX:X  d  M  XdU   :w  d  M  U s  $    U" U 5      n U $ s  snf )z4Apply ``F`` to args and then to result.
            r   N)rf  r   r   r  )	r  Fr   r"  rq  r2  er`  walks	          r)   r  Basic.replace.<locals>.walk  s     2vt,D#$>AT!Z$>?GWWg.' )2$#%7qAJ+-I )8 rUI %?s   Bc                n   > T" U 5      nU(       d  U0 :X  a  T" X5      nUb  X :w  a  T(       a  UTU '   Un U $ r   r   )r(   r  rZ  _query_valuemapr   s      r)   rec_replace"Basic.replace.<locals>.rec_replace  s>    D\F24(=QY()DKr   )r   r   r   r   rn  r'   r$   r/  r8   rr   r:  )r   r  r   r  r`  exactr8   r  r  r  r  r   r  s    ````    @@@@r)   rb  Basic.replace  s   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"   E; F ;
F	F	
FFc                    [        U5      n[        [        U[        U 5      5      5      nU(       d  [	        U5      $ [        [        U5      5      $ )z)Find all subexpressions matching a query.)_make_find_queryr  filterr?  r   r  r   )r   r  groupresultss       r)   find
Basic.find  s@     've%8%>?@w<GG$%%r   c                V   ^ [        T5      m[        U4S j[        U 5       5       5      $ )z,Count the number of matching subexpressions.c              3  F   >#    U  H  n[        T" U5      5      v   M     g 7fr   )bool)r   rp  r  s     r)   r   Basic.count.<locals>.<genexpr>  s     I/H4c
##/Hs   !)r  sumr?  )r   r  s    `r)   countBasic.count  s$     'I/B4/HIIIr   c                   [        U5      n[        XR                  5      (       d  gUc  0 nOUR                  5       nX:X  a  U$ [	        U R
                  5      [	        UR
                  5      :w  a  gUn[        U R
                  UR
                  5       Hb  u  pVXV:X  a  M  UR                  (       a!   UR                  U5      R                  XdUS9nOUR                  U5      R                  XdUS9nUb  Mb    g   U$ ! [         a    Sn Nf = f)aS  
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r  )r   r   r   r   rr   r   r   is_Relationalr.  matchesr'   )r   r(   	repl_dictr  rX  r  	other_args          r)   r+  Basic.matches  s      t}$//I!(I<tyy>S^+!$))TYY7NC  Q//	#/FA Q//	#/FAy 8  ! As   1C;;D
	D
c                6    [        U5      nUR                  XS9$ )au  
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

Since match is purely structural expressions that are equivalent up to
bound symbols will not match:

>>> print(Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p))))
None

An expression with bound symbols can be matched if the pattern uses
a distinct ``Wild`` for each bound symbol:

>>> 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}

See Also
========

matches: pattern.matches(expr) is the same as expr.match(pattern)
xreplace: exact structural replacement
replace: structural replacement with pattern matching
Wild: symbolic placeholders for expressions in pattern matching
r)  )r   r+  )r   patternr  s      r)   r  Basic.matchD  s     v '"t--r   c                    SSK Jn  U" X5      $ )z7Wrapper for count_ops that returns the operation count.r   )	count_ops)functionr3  )r   visualr3  s      r)   r3  Basic.count_ops  s    '&&r   c                    UR                  SS5      (       aR  U R                   Vs/ s H,  n[        U[        5      (       a  UR                  " S0 UD6OUPM.     nnU R
                  " U6 $ U $ s  snf )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   r$   doitr   )r   r  termtermss       r)   r9  
Basic.doit  sr    & 99VT""59YY@5>T ,6dE+B+BTYY''L5>  @99e$$K	@s   3A,c                     SSK Jn  U" U 40 UD6$ )z+See the simplify function in sympy.simplifyr   )simplify)rv  r>  )r   r  r>  s      r)   r>  Basic.simplify  s    4'''r   c                    SSK Jn  U" X5      $ )z,See the refine function in sympy.assumptionsr   )refine)sympy.assumptions.refinerA  )r   
assumptionrA  s      r)   rA  Basic.refine  s    3d''r   c                    SSK Jn  [        U[        U45      (       a6  U n[	        U5       H#  nUnUR                  U5      nUc    g XF:X  d  M"    U$    U$ g )Nr   )r2   )r  r2   r   intrange_eval_derivative)r   r0  nr2   r   r2  prevs          r)   _eval_derivative_n_timesBasic._eval_derivative_n_times  s_     	%a#w((C1X**1-;[J  Jr   r8  c                 ^  U(       d  T $ UR                  US9  USS nUS   nU[        L a  SSKJn  Un[	        U[
        5      (       a  SU-  nO>[        US5      (       a  UR                  nSU-  nOUR                  R                  nSU-  nU(       a6  [        US   5      (       a  US   n[        U 4S jU 5       5      nU(       d  T $ T R                  " XEU40 UD6$ )	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)

rM  Nro   r   )r>   z_eval_rewrite_as_%srp   c              3  X   >#    U  H  nTR                  U5      (       d  M  Uv   M!     g 7fr   )ra  r   r  r   s     r)   r    Basic.rewrite.<locals>.<genexpr>&  s     >w!$((1+AAws   *	*)r   abs$sympy.functions.elementary.complexesr>   r   r  r  rp   r   r   r   _rewrite)	r   r8  r   r  r0  r  r>   methodr   s	   `        r)   rewriteBasic.rewrite  s    T K$s)Bx 3;@D dC  *T1FT:&&mmG*W4F nn--G*W4F
##!!*>w>>G }}WF<e<<r   c                  ^  UR                  SS5      nU(       a/  T R                   Vs/ s H  nUR                  " XU40 UD6PM     nnOT R                  nU(       a  [        U 4S jU 5       5      (       a1  [	        T US 5      nUb	  U" U0 UD6n	OT R
                  " X'40 UD6n	U	b  U	$ U(       d  T $ T R                  " U6 $ s  snf )Nr8  Tc              3  <   >#    U  H  n[        TU5      v   M     g 7fr   r  rP  s     r)   r   !Basic._rewrite.<locals>.<genexpr>4  s     C7ajq117s   )r-  r   rT  r  rf  _eval_rewriter   )
r   r0  r  rU  r  r8  r"  r   meth	rewrittens
   `         r)   rT  Basic._rewrite-  s    yy&!YY(& JJwf>>&  (D 99D#C7CCC4.D $0%0	 ..tCUC	$  Kyy$(s   C c                    g r   r   )r   r  r   r  s       r)   r[  Basic._eval_rewrite@  r   r   c           
         UR                   R                  nUR                   VVs1 s H"  n[        U[	        U5      5        H  nUiM     M$     nnnU H  nU" U5      nM     U$ s  snnf r   )r   rp   r   r   r   )r   r   r   r2  r   r   s         r)    _exec_constructor_postprocessors&Basic._exec_constructor_postprocessorsE  sl     --((%(XX LX%8$q'%J %J X LAC&C   
Ls   )A%c                    U R                   nSSKJn  U" 5         XR                   :X  a  [        S5      eU R                  5       $ )zk
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.sympyre  r   )r   
old_methodre  s      r)   rf  Basic._sage_W  s9     [[
4$%&QRR ;;= r   c                    gr  r   r   s    r)   could_extract_minus_signBasic.could_extract_minus_signf  s    r   c                   SSK Jn  SSKJn  [	        U" U 5      U" U5      5       Hc  nSU;   a    gUu  p[        X5      (       a#  [        X5      (       d    gU(       a
  U" X5      s  $ X:X  a  U R                  UR                  :X  a  Mc    g   g)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)r  rn  	traversalro  r   r   r   )r"  r#  approxrn  potrA  s         r)   is_sameBasic.is_samei  sw    l 	$9SVSV,AqyDA!$$!!,, !!<'Fq{{akk9 - r   )r   )r  rF  )r  ztuple[int, int, str]r   )r  
set[Basic])r=  Tbasic | type[Tbasic]r  zset[Tbasic])r=  rv  r  zset[Basic] | set[Tbasic])r  z'Self')r  zdict[Basic, Symbol])r  r#  )r  r   )FT)r  z)Mapping[Basic | complex, Basic | complex]r  Noner  r   r  r$   )r  z1Iterable[tuple[Basic | complex, Basic | complex]]r  rw  r  r   r  r$   )r  Basic | complexr  rx  r  r   r  r$   )r  zoMapping[Basic | complex, Basic | complex] | Iterable[tuple[Basic | complex, Basic | complex]] | Basic | complexr  zBasic | complex | Noner  r   r  r$   )r  zBasic | None)r0  ru  )FTNr  Fr  )T)hrp   
__module____qualname____firstlineno____doc__	__slots____annotations__propertyr   r   	is_numberis_Atomrh  	is_symbol
is_Indexedr,  is_Wildis_Functionis_Addr  is_Powr!  is_Floatis_Rational
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   classmethodr  r  r   r  r  r$  r'  r7  r
   r:  r+  rN  r*  rV  ro  rx  r|  r{  r   r   r  r  rU  r  r  r.  r  ra  r  r  r  rb  r  r&  r+  r  r3  r9  r>  rA  rK  rV  rT  r[  r   rb  rf  rk  rs  __static_attributes____classcell__r  s   @r)   r$   r$      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$%'/  >8t 0 0" " " ? ?<&(T	!,E\ & &F FJ=X /A /Ab  , \  B.. * *8  2  >  	 q qy y] ] -1Q)Q<?QDIQf m m^	?B, .. ..`76 *2 *2X!F@,D&J
,\<.|'
4(
(
* #' k=Z & *,& "!C Cr   c                  t    \ rS rSrSrSrSrSS jrSS jrS r	\
S	 5       r\SS
 j5       rS r\S 5       rSrg)Atomi  z
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                8    X:X  a  Uc  0 $ UR                  5       $ g r   )r   )r   r(   r,  r  s       r)   r+  Atom.matches  s$    < 	>>## r   c                $    UR                  X 5      $ r   )r   )r   r  r  s      r)   r.  Atom.xreplace  s    xx##r   c                    U $ r   r   )r   r  s     r)   r9  	Atom.doit      r   c                     SSU R                   4$ )Nr   r   r	  r
  s    r)   r  Atom.class_key  s    !S\\!!r   c                    U R                  5       S[        U 5      44[        R                  R	                  5       [        R                  4$ )Nr   )r  r  r  r,   r  )r   r  s     r)   r  Atom.sort_key  s2    ~~!c$i\!2AEENN4DaeeKKr   c                    U $ r   r   )r   r  s     r)   _eval_simplifyAtom._eval_simplify  r  r   c                    [        S5      e)NzXAtoms have no args. It might be necessary to make a check for Atoms in the calling code.)AttributeErrorr   s    r)   r  Atom._sorted_args  s      : ; 	;r   r  ry  r   )rp   rz  r{  r|  r}  r  r~  r+  r.  r9  r  r  r   r  r  r  r  r  r   r   r)   r  r    se     GI$$ " " L L ; ;r   r  c                   [        U 5      n[        5       n[        U [        5      (       a  [	        U SS5      nUc  U 1$ O
[        5       $ SSKJn  SSKJnJ	n  [        5       nU H  n	X;   a  UR                  5         M  UR                  U	5        [        X5      (       a  X;   a  UR                  U	5        MS  [        XU45      (       d  Mg  U(       d  UR                  5         UR                  U	5        M     U$ )a  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!   )r<   rd   )r?  r   r   r$   rf  r/  r"   r4  r<   rd   skipr  )
r  	recursiverr  seenrW  r"   r<   rd   r:  r  s
             r)   _atomicr    s    * a
 C5D!Uq.$/<3J  u.EE9HHJa  QYIIaL122
IIaL  Lr   c                   ^   [        T 5      m [        T [        5      (       a  U 4S j$ [        T [        5      (       a  U 4S j$ T $ ! [         a     NDf = f)z4Convert the argument of Basic.find() into a callablec                   > [        U T5      $ r   r  r  s    r)   r^  "_make_find_query.<locals>.<lambda>	  s    JtU3r   c                *   > U R                  T5      S L$ r   r  r  s    r)   r^  r   	  s    DJJu-T9r   )r   r   r   r   r$   )r  s   `r)   r  r  	  sR     %33	E5	!	!99L  s   A 
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-movedrK  N)rv   r   rw   r   r  rF  ry  )Er}  
__future__r   collectionsr   collections.abcr   r   	itertoolsr   	functoolsr   typingr	   r
   r  r   cacher   r   r   r   r   r  r   r   r   r   _print_helpersr   sympy.utilities.decoratorr   sympy.utilities.exceptionsr   sympy.utilities.iterablesr   r   sympy.utilities.miscr   r   r   r   r   typing_extensionsr   r    r/  r"   r#   r*   rs   r}   r   r   r$   rs  r  r   _args_sortkeyr  r  r  	singletonr  rp  r  r?  r  r  r   r   r)   <module>r     s   - "  - !   * 3  I I  % % 0 @ @ 6 --&&XW-F	$$ L+!^ 		 		 	 	P I P d@ == 5==)
 5 !-;5 -;`+\
     $E  r   