U
    -e`                    @  s$  d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZ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!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: ddl;m<Z< ddl=m>Z>m?Z?m@Z@ ddlAZAddlBmCZC ddlDZDddlEmFZF dd ZGG dd  d eHZIG d!d" d"eJZKG d#d$ d$eLZMG d%d& d&eLZNd'd( ZOG d)d* d*ePZQG d+d, d,e
eQd-ZRG d.d/ d/eReZSG d0d1 d1eSZTG d2d3 d3ZUeU ZVG d4d5 d5eQZWG d6d7 d7eSeZXG d8d9 d9eZYd:d; ZZG d<d= d=eZ[G d>d? d?eZ\d@dA Z]d^dCdDZ^d_dFdGZ_d`dHdIZ`dadJdKZadbdLdMZbdcdNdOZcdddPdQZddedRdSZedfdTdUZfdgdVdWZgdhdXdYZhdid[d\Zidd]ljmkZkmlZl dS )ja  
There are three types of functions implemented in SymPy:

    1) defined functions (in the sense that they can be evaluated) like
       exp or sin; they have a name and a body:
           f = exp
    2) undefined function which have a name but no body. Undefined
       functions can be defined using a Function class as follows:
           f = Function('f')
       (the result will be a Function instance)
    3) anonymous function (or lambda function) which have a body (defined
       with dummy variables) but have no name:
           f = Lambda(x, exp(x)*x)
           f = Lambda((x, y), exp(x)*y)
    The fourth type of functions are composites, like (sin + cos)(x); these work in
    SymPy core, but are not yet part of SymPy.

    Examples
    ========

    >>> import sympy
    >>> f = sympy.Function("f")
    >>> from sympy.abc import x
    >>> f(x)
    f(x)
    >>> print(sympy.srepr(f(x).func))
    Function('f')
    >>> f(x).args
    (x,)

    )annotations)Any)Iterable   )Add)Basic_atomic)cacheit)TupleDict)
_sympifyit)pure_complex)Expr
AtomicExpr)	fuzzy_andfuzzy_or	fuzzy_not	FuzzyBool)Mul)RationalFloatInteger)	LatticeOp)global_parameters)	Transform)S)sympify_sympify)default_sort_keyordered)sympy_deprecation_warningSymPyDeprecationWarningignore_warnings)has_dupssiftiterableis_sequenceuniqtopological_sort)MPMATH_TRANSLATIONS)as_int
filldedent	func_nameN)prec_to_dps)Counterc                 C  s,   | j r| jd } | jr | jd } | jo*| jS )a(  Return True if the leading Number is negative.

    Examples
    ========

    >>> from sympy.core.function import _coeff_isneg
    >>> from sympy import S, Symbol, oo, pi
    >>> _coeff_isneg(-3*pi)
    True
    >>> _coeff_isneg(S(3))
    False
    >>> _coeff_isneg(-oo)
    True
    >>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1
    False

    For matrix expressions:

    >>> from sympy import MatrixSymbol, sqrt
    >>> A = MatrixSymbol("A", 3, 3)
    >>> _coeff_isneg(-sqrt(2)*A)
    True
    >>> _coeff_isneg(sqrt(2)*A)
    False
    r   )	is_MatMulargsis_Mul	is_NumberZis_extended_negativea r5   T/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/sympy/core/function.py_coeff_isnegC   s
    

r7   c                   @  s   e Zd ZdS )	PoleErrorN)__name__
__module____qualname__r5   r5   r5   r6   r8   e   s   r8   c                   @  s   e Zd Zdd ZdS )ArgumentIndexErrorc                 C  s   d| j d | j d f S )Nz9Invalid operation with argument number %s for Function %sr   r   )r0   selfr5   r5   r6   __str__j   s    zArgumentIndexError.__str__N)r9   r:   r;   r?   r5   r5   r5   r6   r<   i   s   r<   c                   @  s   e Zd ZdZdS )BadSignatureErrorz9Raised when a Lambda is created with an invalid signatureNr9   r:   r;   __doc__r5   r5   r5   r6   r@   o   s   r@   c                   @  s   e Zd ZdZdS )BadArgumentsErrorzDRaised when a Lambda is called with an incorrect number of argumentsNrA   r5   r5   r5   r6   rC   t   s   rC   c                 C  sv   t | d| }t|j }dd |D r.dS dd |D }ttt|dd dd	\}}|s`|S tt	||| d
 S )a  Return the arity of the function if it is known, else None.

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

    When default values are specified for some arguments, they are
    optional and the arity is reported as a tuple of possible values.

    Examples
    ========

    >>> from sympy import arity, log
    >>> arity(lambda x: x)
    1
    >>> arity(log)
    (1, 2)
    >>> arity(lambda *x: sum(x)) is None
    True
    evalc                 S  s    g | ]\}}|j |jkr|qS r5   )kindVAR_POSITIONAL.0_pr5   r5   r6   
<listcomp>   s      zarity.<locals>.<listcomp>Nc                 S  s    g | ]\}}|j |jkr|qS r5   )rE   POSITIONAL_OR_KEYWORDrG   r5   r5   r6   rK      s      c                 S  s   | j | jkS N)defaultempty)rJ   r5   r5   r6   <lambda>       zarity.<locals>.<lambda>T)binaryr   )
getattrinspect	signature
parametersitemsmaplenr$   tuplerange)clsZeval_rV   Zp_or_knoyesr5   r5   r6   arityz   s     r_   c                   @  sf   e Zd ZdZejZdd Zedd Z	edd Z
edd	 Zed
d ZdddddZdd ZdS )FunctionClassz
    Base class for function classes. FunctionClass is a subclass of type.

    Use Function('<function name>' [ , signature ]) to create
    undefined function classes.
    c                 O  s   | d| jdt| }|d krPd| jkrP| jD ]}t|dr2|j} qPq2q2q2t|r|sptt	dt
| ttt|}n|d k	rt|f}|| _t|dkr|d }d|krt|d tstdd S )Nnargs_nargsa  
                    Incorrectly specified nargs as %s:
                    if there are no arguments, it should be
                    `nargs = 0`;
                    if there are any number of arguments,
                    it should be
                    `nargs = None`      rD   zPeval on Function subclasses should be a class method (defined with @classmethod))pop__dict__getr_   __mro__hasattrrb   r&   
ValueErrorr+   strrZ   r   setr*   rY   
isinstanceclassmethod	TypeError)r\   r0   kwargsra   Zsupcls	namespacer5   r5   r6   __init__   s(    


zFunctionClass.__init__c                 C  s2   zddl m} W n tk
r&   Y dS X || jS )zp
        Allow Python 3's inspect.signature to give a useful signature for
        Function subclasses.
        r   )rU   N)rT   rU   ImportErrorrD   )r>   rU   r5   r5   r6   __signature__   s
    zFunctionClass.__signature__c                 C  s   t  S rM   )rl   r=   r5   r5   r6   free_symbols   s    zFunctionClass.free_symbolsc                   s    fddS )Nc                   s   |    S rM   rg   )rulerI   r=   r5   r6   rP      rQ   z(FunctionClass.xreplace.<locals>.<lambda>r5   r=   r5   r=   r6   xreplace   s    zFunctionClass.xreplacec                 C  s"   ddl m} | jr|| j S tjS )a`  Return a set of the allowed number of arguments for the function.

        Examples
        ========

        >>> from sympy import Function
        >>> f = Function('f')

        If the function can take any number of arguments, the set of whole
        numbers is returned:

        >>> Function('f').nargs
        Naturals0

        If the function was initialized to accept one or more arguments, a
        corresponding set will be returned:

        >>> Function('f', nargs=1).nargs
        {1}
        >>> Function('f', nargs=(2, 1)).nargs
        {1, 2}

        The undefined function, after application, also has the nargs
        attribute; the actual number of arguments is always available by
        checking the ``args`` attribute:

        >>> f = Function('f')
        >>> f(1).nargs
        Naturals0
        >>> len(f(1).args)
        1
        r   	FiniteSet)sympy.sets.setsrz   rb   r   	Naturals0r>   rz   r5   r5   r6   ra      s    "zFunctionClass.nargsintbool)nreturnc                 C  s(   | j r|| j kS | j}|tjkp&||kS )z Return True if the specified integer is a valid number of arguments

        The number of arguments n is guaranteed to be an integer and positive

        )rb   ra   r   r|   )r>   r   ra   r5   r5   r6   _valid_nargs  s    
zFunctionClass._valid_nargsc                 C  s   | j S rM   )r9   r\   r5   r5   r6   __repr__  s    zFunctionClass.__repr__N)r9   r:   r;   rB   type__new___newrr   propertyrt   ru   rx   ra   r   r   r5   r5   r5   r6   r`      s   #



&r`   c                      sH   e Zd ZdZdZe fddZedd Ze	dd Z
d	d
 Z  ZS )Applicationz
    Base class for applied functions.

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

    Instances of Application represent the result of applying an application of
    any type to any object.
    Tc                   s   ddl m} ddlm} ttt|}|dtj	}|dd  |rPt
d| |rj| j| }|d k	rj|S t j| f||}t }t|d|}	|	|k	rt|	rttt|	}
q|	d k	rt|	f}
qd }
n|j}
|
r||
 n| |_|S )Nr   r|   ry   evaluatera   zUnknown options: %s)sympy.sets.fancysetsr|   r{   rz   listrX   r   re   r   r   rj   rD   superr   objectrS   r&   rZ   r   rl   r*   rb   ra   )r\   r0   optionsr|   rz   r   Z	evaluatedobjsentinelZobjnargsra   	__class__r5   r6   r   $  s.    
zApplication.__new__c                 G  s   dS )a  
        Returns a canonical form of cls applied to arguments args.

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

        The ``eval()`` method is called when the class ``cls`` is about to be
        instantiated and it should return either some simplified instance
        (possible of some other class), or if the class ``cls`` should be
        unmodified, return None.

        Examples of ``eval()`` for the function "sign"

        .. code-block:: python

            @classmethod
            def eval(cls, arg):
                if arg is S.NaN:
                    return S.NaN
                if arg.is_zero: return S.Zero
                if arg.is_positive: return S.One
                if arg.is_negative: return S.NegativeOne
                if isinstance(arg, Mul):
                    coeff, terms = arg.as_coeff_Mul(rational=True)
                    if coeff is not S.One:
                        return cls(coeff) * cls(terms)

        Nr5   )r\   r0   r5   r5   r6   rD   Q  s    zApplication.evalc                 C  s   | j S rM   r   r=   r5   r5   r6   funcq  s    zApplication.funcc                   sT   j rP j rPtrPt rP| jkrPt| j jkrP  fdd| jD  S d S )Nc                   s   g | ]}|  qS r5   _subsrH   inewoldr5   r6   rK   y  s     z*Application._eval_subs.<locals>.<listcomp>)is_Functioncallabler   rY   r0   ra   )r>   r   r   r5   r   r6   
_eval_subsu  s    zApplication._eval_subs)r9   r:   r;   rB   r   r	   r   rn   rD   r   r   r   __classcell__r5   r5   r   r6   r     s   
,

r   )	metaclassc                      s   e Zd ZU dZedd Ze fddZedd Z	edd	 Z
d
d Zdd Zdd Zdd ZdZded< edd Zdd Zdd Zd#ddZd$dd Zd%d!d"Z  ZS )&Functionaj  
    Base class for applied mathematical functions.

    It also serves as a constructor for undefined function classes.

    See the :ref:`custom-functions` guide for details on how to subclass
    ``Function`` and what methods can be defined.

    Examples
    ========

    **Undefined Functions**

    To create an undefined function, pass a string of the function name to
    ``Function``.

    >>> from sympy import Function, Symbol
    >>> x = Symbol('x')
    >>> f = Function('f')
    >>> g = Function('g')(x)
    >>> f
    f
    >>> f(x)
    f(x)
    >>> g
    g(x)
    >>> f(x).diff(x)
    Derivative(f(x), x)
    >>> g.diff(x)
    Derivative(g(x), x)

    Assumptions can be passed to ``Function`` the same as with a
    :class:`~.Symbol`. Alternatively, you can use a ``Symbol`` with
    assumptions for the function name and the function will inherit the name
    and assumptions associated with the ``Symbol``:

    >>> f_real = Function('f', real=True)
    >>> f_real(x).is_real
    True
    >>> f_real_inherit = Function(Symbol('f', real=True))
    >>> f_real_inherit(x).is_real
    True

    Note that assumptions on a function are unrelated to the assumptions on
    the variables it is called on. If you want to add a relationship, subclass
    ``Function`` and define custom assumptions handler methods. See the
    :ref:`custom-functions-assumptions` section of the :ref:`custom-functions`
    guide for more details.

    **Custom Function Subclasses**

    The :ref:`custom-functions` guide has several
    :ref:`custom-functions-complete-examples` of how to subclass ``Function``
    to create a custom function.

    c                 C  s   dS NFr5   r=   r5   r5   r6   	_diff_wrt  s    zFunction._diff_wrtc           
        s    t krt||S t|} |sfd}t| t jdkr@dndt jdt jdk |d |dtj	}t
 j f||}|rt| r|jrև fdd	|jD }t|}|d
krt|}	|t|	}t|S )NzE%(name)s takes %(qual)s %(args)s argument%(plural)s (%(given)s given)r   Zexactlyzat leasts)nameZqualr0   pluralgivenr   c                   s   g | ]}  |qS r5   )_should_evalfrH   r4   r   r5   r6   rK     s     z$Function.__new__.<locals>.<listcomp>r   )r   UndefinedFunctionrY   r   ro   ra   minrg   r   r   r   r   rm   r0   maxevalfr-   r   )
r\   r0   r   r   tempr   resultr   Zpr2prr   r   r6   r     s*    


zFunction.__new__c                 C  s@   |j r|jS |jsdS t|}|dkr*dS t|d j|d jS )aw  
        Decide if the function should automatically evalf().

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

        By default (in this implementation), this happens if (and only if) the
        ARG is a floating point number (including complex numbers).
        This function is used by __new__.

        Returns the precision to evalf to, or -1 if it should not evalf.
        Nr   r   )Zis_FloatZ_precis_Addr   r   )r\   argmr5   r5   r6   r     s    zFunction._should_evalfc                 C  st   ddl m} ddddddd	d
ddddddd}| j}z|| }W n( tk
rh   t| j|r`dnd}Y nX d||fS )Nr   r   
                            !   (   )   *   +   )explogsincostanZcotsinhcoshtanhZcoth	conjugatereZimr   i'     )r   r|   r9   KeyErrorrm   ra   )r\   r|   funcsr   r   r5   r5   r6   	class_key  s,    zFunction.class_keyc              	     s  fdd}t dd }|d kr4|jj}j}n
| \}}|d krt dd }|d kr^d S z t|fddjD  W S  ttfk
r   Y d S X z8fdd|D }dd	  t fd
d|D rtW n tk
r   Y d S X t	 || }W 5 Q R X t
|S )Nc                   s:   t  trdS tt| s0t| d} | dkr0dS tt| S )z$Lookup mpmath function based on nameN)rm   AppliedUndefri   mpmathr)   rg   rS   )fnamer=   r5   r6   _get_mpmath_func  s    

z.Function._eval_evalf.<locals>._get_mpmath_func_eval_mpmathZ_imp_c                   s   g | ]}|  qS r5   )r   r   precr5   r6   rK   +  s     z(Function._eval_evalf.<locals>.<listcomp>c                   s   g | ]}|  d  qS )   )
_to_mpmathrH   r   r   r5   r6   rK   5  s     c                 S  s   ddl m}m} t| |r8| j} | d dko6| d dkS t| |r|| j\} }| d dkoz| d dkoz|d dkoz|d dkS dS d S )Nr   )mpfmpcr   r   F)r   r   r   rm   Z_mpf_Z_mpc_)r   r   r   r   r5   r5   r6   bad6  s    




z!Function._eval_evalf.<locals>.badc                 3  s   | ]} |V  qd S rM   r5   r   )r   r5   r6   	<genexpr>H  s     z'Function._eval_evalf.<locals>.<genexpr>)rS   r   r9   r0   r   ro   rj   anyr   Zworkprecr   _from_mpmath)r>   r   r   r   r   r0   impvr5   )r   r   r>   r6   _eval_evalf  s0    
 zFunction._eval_evalfc              	   C  st   d}g }| j D ]\}|d7 }||}|jr,qz| |}W n  tk
rZ   t| |}Y nX |||  qt| S )Nr   r   )r0   diffis_zerofdiffr<   r   appendr   )r>   r   r   lr4   daZdfr5   r5   r6   _eval_derivativeR  s    

zFunction._eval_derivativec                 C  s   t dd | jD S )Nc                 s  s   | ]}|j V  qd S rM   )is_commutativer   r5   r5   r6   r   c  s     z0Function._eval_is_commutative.<locals>.<genexpr>)r   r0   r=   r5   r5   r6   _eval_is_commutativeb  s    zFunction._eval_is_commutativec                   sb   | j s
dS t fdd| j dd  D r.dS | j d }| |sHd S tt| | |S )NTc                 3  s   | ]}|  V  qd S rM   hasr   xr5   r6   r   h  s     z0Function._eval_is_meromorphic.<locals>.<genexpr>r   Fr   )r0   r   _eval_is_meromorphicr   r   is_singularsubs)r>   r   r4   r   r5   r   r6   r   e  s     
zFunction._eval_is_meromorphicNzFuzzyBool | tuple[Expr, ...]_singularitiesc                   s(   | j }|dkr|S t fdd|D S )z
        Tests whether the argument is an essential singularity
        or a branch point, or the functions is non-holomorphic.
        )TNFc                 3  s(   | ] }|t jkr jn | jV  qd S rM   )r   ZComplexInfinityis_infiniter   )rH   r   r3   r5   r6   r   }  s   z'Function.is_singular.<locals>.<genexpr>)r   r   )r\   r4   ssr5   r3   r6   r   s  s    zFunction.is_singularc                 C  s
   | t jfS )zE
        Returns the method as the 2-tuple (base, exponent).
        )r   Oner=   r5   r5   r6   as_base_exp  s    zFunction.as_base_expc                 C  s   t tdt| |f dS )a  
        Compute an asymptotic expansion around args0, in terms of self.args.
        This function is only used internally by _eval_nseries and should not
        be called directly; derived classes can overwrite this to implement
        asymptotic expansions.
        zQ
            Asymptotic expansion of %s around %s is
            not implemented.N)r8   r+   r   )r>   r   args0r   logxr5   r5   r6   _eval_aseries  s    
zFunction._eval_aseriesr   c           "        s  ddl m} ddlm} ddlm} | j}fdd|D }	tdd	 |	D rdd
lm	m
m  fdd|D }
fdd|
D }tfdd	|D r| |	 S  fdd|D }
dd t|
|D }dd |D }g }d}t|||D ]D\}}}|r8|dk	r$t|||  |}n
|| q | j| }|dkr^|S || }| }| }||| ||j|| }|S | jjtjks| jj|dkr|	d stdd	 | jjD r| }| }||krt|jdkr"||jd  }|tj}|jdksH|tjkrTt d|  |}tj!}|d| }||}t"dD ]|}|t#|9 }|$|}||tj}|tjkr|%|tj}|jdkrt d|  ||  | }| }||7 }q~||  S |j& dS | jd }g }d}d } ||'( }!|!dkrb|! ) } t"| D ].}| *|||}|j& d}|| qjt+| |  S )ay  
        This function does compute series for multivariate functions,
        but the expansion is always in terms of *one* variable.

        Examples
        ========

        >>> from sympy import atan2
        >>> from sympy.abc import x, y
        >>> atan2(x, y).series(x, n=2)
        atan2(0, y) + x/y + O(x**2)
        >>> atan2(x, y).series(y, n=2)
        -y/x + atan2(x, 0) + O(y**2)

        This function also computes asymptotic expansions, if necessary
        and possible:

        >>> from sympy import loggamma
        >>> loggamma(1/x)._eval_nseries(x,0,None)
        -1/x - log(x)/x + log(x)/2 + O(1)

        r   )uniquely_named_symbolr   Orderry   c                   s   g | ]}|  d qS r   limitrH   tr   r5   r6   rK     s     z*Function._eval_nseries.<locals>.<listcomp>c                 s  s   | ]}|j d kV  qdS )FN)	is_finiter  r5   r5   r6   r     s     z)Function._eval_nseries.<locals>.<genexpr>)oozoonanc                   s   g | ]}|j  d qS )r   as_leading_termr  r   r   r5   r6   rK     s     c                   s   g | ]}|  d qS r   r  r  r   r5   r6   rK     s     c                 3  s    | ]}|   V  qd S rM   r   r  )r  r  r  r5   r6   r     s     c                   s   g | ]}|  qS r5   )_eval_nseriesr  )r   r   r   r5   r6   rK     s     c                 S  s   g | ]\}}|| qS r5   r5   )rH   rZr0r5   r5   r6   rK     s     c                 S  s   g | ]
}t  qS r5   Dummy)rH   rI   r5   r5   r6   rK     s     Nc                 s  s   | ]}|d kV  qdS r   Nr5   )rH   cr5   r5   r6   r     s     FzCannot expand %s around 0xir   r   rd   ),symbolr   sympy.series.orderr   r{   rz   r0   r   numbersr  r  r  r   zipr   NotImplementedErrorr   r   r  getOremoveOr   expandexprra   r   r|   rY   cancelZeror  NaNr8   r   r[   r   r   r  nseriesr  ZgetnZceilingZtaylor_termr   )"r>   r   r   r   cdirr   r   rz   r0   r   r4   Za0zrJ   qr   aiZzipie1r   oetermZseriesZfactZ_xr   r   r   r   gZntermscfr5   )r   r   r  r  r   r  r6   r    s    


$




zFunction._eval_nseriesr   c                 C  s   d|  krt | jks&n t| ||d }| j| }|jrt | jdksR|js\t| |S t| jD ]\}}||krf||jkrf qqft| |S td| t	|d}| jd| |f | j|d d  }t
t| j| |||S )z?
        Returns the first derivative of the function.
        r   xi_%i)dummy_indexN)rY   r0   r<   r   	is_Symbol_derivative_dispatch	enumerateru   r  hashSubs
Derivativer   )r>   ZargindexixAr   r   Dr0   r5   r5   r6   r     s    



&zFunction.fdiffc                   sb   ddl m}  fdd| jD }|dtfdd|D rTtd| j n
| j| S d	S )
a  Stub that should be overridden by new Functions to return
        the first non-zero term in a series if ever an x-dependent
        argument whose leading term vanishes as x -> 0 might be encountered.
        See, for example, cos._eval_as_leading_term.
        r   r   c                   s   g | ]}|j  d qS r	  r
  r   r  r5   r6   rK     s     z2Function._eval_as_leading_term.<locals>.<listcomp>r   c                 3  s"   | ]}|j ko |V  qd S rM   )ru   containsr   )r(  r   r5   r6   r     s     z1Function._eval_as_leading_term.<locals>.<genexpr>z'%s has no _eval_as_leading_term routineN)r  r   r0   r   r  r   )r>   r   r   r"  r   r0   r5   )r   r(  r   r6   _eval_as_leading_term  s    
zFunction._eval_as_leading_term)r   )r   )Nr   )r9   r:   r;   rB   r   r   r	   r   rn   r   r   r   r   r   r   r   __annotations__r   r   r   r  r   r9  r   r5   r5   r   r6   r   |  s*   
9
!

B

l
r   c                      s:   e Zd ZdZdZ fddZdddZed	d
 Z  Z	S )r   za
    Base class for expressions resulting from the application of an undefined
    function.
    Fc                   sZ   t tt|}dd |D }|rBtddt|dk d|f t j| f||}|S )Nc                 S  s   g | ]}t |tr|jqS r5   )rm   r   r   r   r5   r5   r6   rK   <  s     
 z(AppliedUndef.__new__.<locals>.<listcomp>zFInvalid argument: expecting an expression, not UndefinedFunction%s: %sr   r   , )r   rX   r   ro   rY   joinr   r   )r\   r0   r   ur   r   r5   r6   r   :  s     zAppliedUndef.__new__Nr   c                 C  s   | S rM   r5   )r>   r   r   r"  r5   r5   r6   r9  C  s    z"AppliedUndef._eval_as_leading_termc                 C  s   dS )a)  
        Allow derivatives wrt to undefined functions.

        Examples
        ========

        >>> from sympy import Function, Symbol
        >>> f = Function('f')
        >>> x = Symbol('x')
        >>> f(x)._diff_wrt
        True
        >>> f(x).diff(x)
        Derivative(f(x), x)
        Tr5   r=   r5   r5   r6   r   F  s    zAppliedUndef._diff_wrt)Nr   )
r9   r:   r;   rB   	is_numberr   r9  r   r   r   r5   r5   r   r6   r   2  s   	
r   c                   @  s   e Zd ZdZdd ZdS )UndefSageHelperz/
    Helper to facilitate Sage conversion.
    c                   sF   dd l m d kr"fddS dd jD   fddS d S )Nr   c                     s     jS rM   )functionr9   r5   )sagetypr5   r6   rP   `  rQ   z)UndefSageHelper.__get__.<locals>.<lambda>c                 S  s   g | ]}|  qS r5   )_sage_r   r5   r5   r6   rK   b  s     z+UndefSageHelper.__get__.<locals>.<listcomp>c                     s    jj  S rM   )r@  r   r9   r5   )r0   insrA  r5   r6   rP   c  rQ   )Zsage.allallr0   )r>   rD  rB  r5   )r0   rD  rA  rB  r6   __get__]  s
    zUndefSageHelper.__get__N)r9   r:   r;   rB   rF  r5   r5   r5   r6   r?  Y  s   r?  c                      sb   e Zd ZU dZefdf fdd	Zdd Zi Zded< d	d
 Z	dd Z
dd Zedd Z  ZS )r   z1
    The (meta)class of undefined functions.
    Nc           	        s   ddl m} ||\}}t|tr4||}|j}n@t|tsHtdn,|dd }t|f|j	}|d krt|
d |pzi }|dd | D  || || |d|i d |d< t | |||}||_t|_|S )	Nr   )_filter_assumptionsz#expecting string or Symbol for namecommutativec                 S  s   i | ]\}}d | |qS )zis_%sr5   rH   kr   r5   r5   r6   
<dictcomp>|  s      z-UndefinedFunction.__new__.<locals>.<dictcomp>_kwargsr:   )r  rG  rm   Symbol_merger   rk   ro   rg   Zassumptions0re   updaterW   r   r   _undef_sage_helperrC  )	Zmclr   basesrf   rp   rG  assumptionsrH  r   r   r5   r6   r   k  s*    






zUndefinedFunction.__new__c                 C  s   | t |jkS rM   )r   rh   )r\   instancer5   r5   r6   __instancecheck__  s    z#UndefinedFunction.__instancecheck__zdict[str, bool | None]rL  c                 C  s   t |  t| j fS rM   )r2  r   	frozensetrL  rW   r=   r5   r5   r6   __hash__  s    zUndefinedFunction.__hash__c                 C  s(   t || jo&|  | ko&| j|jkS rM   )rm   r   r   rL  r>   otherr5   r5   r6   __eq__  s
    
zUndefinedFunction.__eq__c                 C  s
   | |k S rM   r5   rW  r5   r5   r6   __ne__  s    zUndefinedFunction.__ne__c                 C  s   dS r   r5   r=   r5   r5   r6   r     s    zUndefinedFunction._diff_wrt)r9   r:   r;   rB   r   r   rT  rL  r:  rV  rY  rZ  r   r   r   r5   r5   r   r6   r   g  s   
!r   c                   @  s2   e Zd ZU dZe Zded< dd Zd
dd	ZdS )WildFunctiona=  
    A WildFunction function matches any function (with its arguments).

    Examples
    ========

    >>> from sympy import WildFunction, Function, cos
    >>> from sympy.abc import x, y
    >>> F = WildFunction('F')
    >>> f = Function('f')
    >>> F.nargs
    Naturals0
    >>> x.match(F)
    >>> F.match(F)
    {F_: F_}
    >>> f(x).match(F)
    {F_: f(x)}
    >>> cos(x).match(F)
    {F_: cos(x)}
    >>> f(x, y).match(F)
    {F_: f(x, y)}

    To match functions with a given number of arguments, set ``nargs`` to the
    desired value at instantiation:

    >>> F = WildFunction('F', nargs=2)
    >>> F.nargs
    {2}
    >>> f(x).match(F)
    >>> f(x, y).match(F)
    {F_: f(x, y)}

    To match functions with a range of arguments, set ``nargs`` to a tuple
    containing the desired number of arguments, e.g. if ``nargs = (1, 2)``
    then functions with 1 or 2 arguments will be matched.

    >>> F = WildFunction('F', nargs=(1, 2))
    >>> F.nargs
    {1, 2}
    >>> f(x).match(F)
    {F_: f(x)}
    >>> f(x, y).match(F)
    {F_: f(x, y)}
    >>> f(x, y, 1).match(F)

    zset[Any]includec                 K  sl   ddl m}m} || _|dtj}t||sbt|rHt	t
t|}n|d k	rZt|f}|| }|| _d S )Nr   )Setrz   ra   )r{   r]  rz   r   re   r   r|   rm   r&   rZ   r   rl   r*   ra   )r\   r   rR  r]  rz   ra   r5   r5   r6   rr     s    

zWildFunction.__init__NFc                 C  sH   t |ttfsd S t|j| jkr&d S |d kr4i }n| }||| < |S rM   )rm   r   r   rY   r0   ra   copy)r>   r  Z	repl_dictr   r5   r5   r6   matches  s    zWildFunction.matches)NF)	r9   r:   r;   rB   rl   r\  r:  rr   r_  r5   r5   r5   r6   r[    s   
0r[  c                   @  s  e Zd ZdZdZedd Zdd Zedd Ze	d	d
 Z
dd Zdd Zdd Zededd Zedd Zedd Zedd Zedd Zedd Zedd Zed d! Zd"d# Zd3d%d&Zd4d'd(Zd5d*d+Zd6d-d.Ze	d/d0 Ze	d1d2 Zd)S )7r4  aE  
    Carries out differentiation of the given expression with respect to symbols.

    Examples
    ========

    >>> from sympy import Derivative, Function, symbols, Subs
    >>> from sympy.abc import x, y
    >>> f, g = symbols('f g', cls=Function)

    >>> Derivative(x**2, x, evaluate=True)
    2*x

    Denesting of derivatives retains the ordering of variables:

        >>> Derivative(Derivative(f(x, y), y), x)
        Derivative(f(x, y), y, x)

    Contiguously identical symbols are merged into a tuple giving
    the symbol and the count:

        >>> Derivative(f(x), x, x, y, x)
        Derivative(f(x), (x, 2), y, x)

    If the derivative cannot be performed, and evaluate is True, the
    order of the variables of differentiation will be made canonical:

        >>> Derivative(f(x, y), y, x, evaluate=True)
        Derivative(f(x, y), x, y)

    Derivatives with respect to undefined functions can be calculated:

        >>> Derivative(f(x)**2, f(x), evaluate=True)
        2*f(x)

    Such derivatives will show up when the chain rule is used to
    evalulate a derivative:

        >>> f(g(x)).diff(x)
        Derivative(f(g(x)), g(x))*Derivative(g(x), x)

    Substitution is used to represent derivatives of functions with
    arguments that are not symbols or functions:

        >>> f(2*x + 3).diff(x) == 2*Subs(f(y).diff(y), y, 2*x + 3)
        True

    Notes
    =====

    Simplification of high-order derivatives:

    Because there can be a significant amount of simplification that can be
    done when multiple differentiations are performed, results will be
    automatically simplified in a fairly conservative fashion unless the
    keyword ``simplify`` is set to False.

        >>> from sympy import sqrt, diff, Function, symbols
        >>> from sympy.abc import x, y, z
        >>> f, g = symbols('f,g', cls=Function)

        >>> e = sqrt((x + 1)**2 + x)
        >>> diff(e, (x, 5), simplify=False).count_ops()
        136
        >>> diff(e, (x, 5)).count_ops()
        30

    Ordering of variables:

    If evaluate is set to True and the expression cannot be evaluated, the
    list of differentiation symbols will be sorted, that is, the expression is
    assumed to have continuous derivatives up to the order asked.

    Derivative wrt non-Symbols:

    For the most part, one may not differentiate wrt non-symbols.
    For example, we do not allow differentiation wrt `x*y` because
    there are multiple ways of structurally defining where x*y appears
    in an expression: a very strict definition would make
    (x*y*z).diff(x*y) == 0. Derivatives wrt defined functions (like
    cos(x)) are not allowed, either:

        >>> (x*y*z).diff(x*y)
        Traceback (most recent call last):
        ...
        ValueError: Can't calculate derivative wrt x*y.

    To make it easier to work with variational calculus, however,
    derivatives wrt AppliedUndef and Derivatives are allowed.
    For example, in the Euler-Lagrange method one may write
    F(t, u, v) where u = f(t) and v = f'(t). These variables can be
    written explicitly as functions of time::

        >>> from sympy.abc import t
        >>> F = Function('F')
        >>> U = f(t)
        >>> V = U.diff(t)

    The derivative wrt f(t) can be obtained directly:

        >>> direct = F(t, U, V).diff(U)

    When differentiation wrt a non-Symbol is attempted, the non-Symbol
    is temporarily converted to a Symbol while the differentiation
    is performed and the same answer is obtained:

        >>> indirect = F(t, U, V).subs(U, x).diff(x).subs(x, U)
        >>> assert direct == indirect

    The implication of this non-symbol replacement is that all
    functions are treated as independent of other functions and the
    symbols are independent of the functions that contain them::

        >>> x.diff(f(x))
        0
        >>> g(x).diff(f(x))
        0

    It also means that derivatives are assumed to depend only
    on the variables of differentiation, not on anything contained
    within the expression being differentiated::

        >>> F = f(x)
        >>> Fx = F.diff(x)
        >>> Fx.diff(F)  # derivative depends on x, not F
        0
        >>> Fxx = Fx.diff(x)
        >>> Fxx.diff(Fx)  # derivative depends on x, not Fx
        0

    The last example can be made explicit by showing the replacement
    of Fx in Fxx with y:

        >>> Fxx.subs(Fx, y)
        Derivative(y, x)

        Since that in itself will evaluate to zero, differentiating
        wrt Fx will also be zero:

        >>> _.doit()
        0

    Replacing undefined functions with concrete expressions

    One must be careful to replace undefined functions with expressions
    that contain variables consistent with the function definition and
    the variables of differentiation or else insconsistent result will
    be obtained. Consider the following example:

    >>> eq = f(x)*g(y)
    >>> eq.subs(f(x), x*y).diff(x, y).doit()
    y*Derivative(g(y), y) + g(y)
    >>> eq.diff(x, y).subs(f(x), x*y).doit()
    y*Derivative(g(y), y)

    The results differ because `f(x)` was replaced with an expression
    that involved both variables of differentiation. In the abstract
    case, differentiation of `f(x)` by `y` is 0; in the concrete case,
    the presence of `y` made that derivative nonvanishing and produced
    the extra `g(y)` term.

    Defining differentiation for an object

    An object must define ._eval_derivative(symbol) method that returns
    the differentiation result. This function only needs to consider the
    non-trivial case where expr contains symbol and it should call the diff()
    method internally (not _eval_derivative); Derivative should be the only
    one to call _eval_derivative.

    Any class can allow derivatives to be taken with respect to
    itself (while indicating its scalar nature). See the
    docstring of Expr._diff_wrt.

    See Also
    ========
    _sort_variable_count
    Tc                 C  s   | j jot|  tS )a{  An expression may be differentiated wrt a Derivative if
        it is in elementary form.

        Examples
        ========

        >>> from sympy import Function, Derivative, cos
        >>> from sympy.abc import x
        >>> f = Function('f')

        >>> Derivative(f(x), x)._diff_wrt
        True
        >>> Derivative(cos(x), x)._diff_wrt
        False
        >>> Derivative(x + 1, x)._diff_wrt
        False

        A Derivative might be an unevaluated form of what will not be
        a valid variable of differentiation if evaluated. For example,

        >>> Derivative(f(f(x)), x).doit()
        Derivative(f(x), x)*Derivative(f(f(x)), f(x))

        Such an expression will present the same ambiguities as arise
        when dealing with any other product, like ``2*x``, so ``_diff_wrt``
        is False:

        >>> Derivative(f(f(x)), x)._diff_wrt
        False
        )r  r   rm   doitr4  r=   r5   r5   r6   r     s     zDerivative._diff_wrtc           #      O  s  t |}t|dd }t|t}|s2ttd| |s|j}t|dkr|jrTt	j
S t|dkrrttd| nttd| g }tttf}ddlm}m}	 t|D ]0\}
}t|trtd| t||rJt|dkrqt|d |r$t|dkr||d }d}n|\}}||}n|\}}|dkr8q|t|| qt |}t|tr|
dkrttd	| |}|d
 \}}|dkrtd||f||dkr|  nt|||d
< qd}|t|| qg }|D ]p}|\}}|jr td|rH|d
 d |krH||d
 d 7 }|s8|  nt|||d
< n
|| q|}|D ]*\}}|js^d}ttd||f q^t|dkr|S |dd}|rt|tr|j}dd |D }d}|j}ddlm} |D ]\}}|j}|jr|rt|t r8t! }|"||i#|sd} qnNt||rPd} qn6t|t$rr||krrd} qn||@ sd} qq|r| %|S | &|}t|trt|j'| }|j(}t)|f||S |rt*|ds|r
||dfgkr
|j+r
t	j,S t-j.| |f| S d}g }ddl/m0} t|D ]\}
\}}|}d }|j1pft|t2t||	f}|s|}t!d}|"||i}t|tpt|t  }||jkr|s|3|  S |j+st*|ds||3|9 }| 4|||} | d k	r
| j5r
|   S ||7 }|d k	r6| d k	r2| 6||} |}| d krR||
d  } qZ| }q8|7dd dd }|rt|trt|j'| }|j(}t-j.| |f| }|dkdkr|ddrddl8m9}! ddl:m;}" |!|"|}|S )Nru   zp
                Since there are no variables in the expression %s,
                it cannot be differentiated.r   r   z
                        Since there are no variables in the expression,
                        the variable(s) of differentiation must be supplied
                        to differentiate %sz
                        Since there is more than one variable in the
                        expression, the variable(s) of differentiation
                        must be supplied to differentiate %s)Array	NDimArrayz.cannot differentiate wrt UndefinedFunction: %sz%First variable cannot be a number: %ir   ztuple {} followed by number {}z,order of differentiation must be nonnegative z9
                    Can't calculate derivative wrt %s.%sr   Fc                 S  s(   g | ] \}}t |tr|jn||fqS r5   )rm   r4  	canonicalrH   r   r  r5   r5   r6   rK   D  s   z&Derivative.__new__.<locals>.<listcomp>
MatrixExprTr   MatrixCommonr  c                 S  s
   t | tS rM   )rm   r4  r   r5   r5   r6   rP     rQ   z$Derivative.__new__.<locals>.<lambda>c                 S  s   | j S rM   )rd  r   r5   r5   r6   rP     rQ   simplify)factor_terms)signsimp)<r   rS   rm   rl   rj   r+   ru   rY   r>  r   r  rZ   r   r
   sympy.tensor.arrayra  rb  r1  r   ro   r   r   formatre   Zis_negativer   rg   r4  rd  "sympy.matrices.expressions.matexprrg  Zis_positiver   r  rx   r   rM  _get_zero_with_shape_like_sort_variable_countvariable_countr  r0  ri   Z	is_scalarr   r   r   sympy.matrices.commonri  	is_symbolr   r   !_dispatch_eval_derivative_n_timesr   r   replaceZ	exprtoolsrk  Zsympy.simplify.simplifyrl  )#r\   r  	variablesrp   Zsymbols_or_noneZhas_symbol_setrr  Zarray_likesra  rb  r   r   countprevZ	prevcountmergedr  r  __r   zerofreerg  Zvfreer7  ZnderivsZ	unhandledri  Zold_exprold_vrt  Zclashingr   rk  rl  r5   r5   r6   r     sN   

	














 


zDerivative.__new__c                 C  s   | j | jft| j S rM   )r   r  r4  rq  rr  r   r5   r5   r6   rd    s    

zDerivative.canonicalc           	        sL  sg S t tdkr*td  gS t tt}g }fddt  d fdd	ttD ]2}t|D ]$}||rx|||f qxqltttt	dd	 D ttt
||ffd
dd}g }fdd	|D D ]D\}|r.|d d kr.|d d  |7  < q||g qdd	 |D S )a,  
        Sort (variable, count) pairs into canonical order while
        retaining order of variables that do not commute during
        differentiation:

        * symbols and functions commute with each other
        * derivatives commute with each other
        * a derivative does not commute with anything it contains
        * any other object is not allowed to commute if it has
          free symbols in common with another object

        Examples
        ========

        >>> from sympy import Derivative, Function, symbols
        >>> vsort = Derivative._sort_variable_count
        >>> x, y, z = symbols('x y z')
        >>> f, g, h = symbols('f g h', cls=Function)

        Contiguous items are collapsed into one pair:

        >>> vsort([(x, 1), (x, 1)])
        [(x, 2)]
        >>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)])
        [(y, 2), (f(x), 2)]

        Ordering is canonical.

        >>> def vsort0(*v):
        ...     # docstring helper to
        ...     # change vi -> (vi, 0), sort, and return vi vals
        ...     return [i[0] for i in vsort([(i, 0) for i in v])]

        >>> vsort0(y, x)
        [x, y]
        >>> vsort0(g(y), g(x), f(y))
        [f(y), g(x), g(y)]

        Symbols are sorted as far to the left as possible but never
        move to the left of a derivative having the same symbol in
        its variables; the same applies to AppliedUndef which are
        always sorted after Symbols:

        >>> dfx = f(x).diff(x)
        >>> assert vsort0(dfx, y) == [y, dfx]
        >>> assert vsort0(dfx, x) == [dfx, x]
        r   r   c                   s    |  d S Nr   r5   r   vcr5   r6   rP     rQ   z1Derivative._sort_variable_count.<locals>.<lambda>Fc                   s   |  kr|S | j rdS t| trBt fdd| jD r>dS dS |sTt| trTdS  j rd | jkS t tr|  iS | j j@ S )NFc                 3  s   | ]} |d dV  qdS )T)wrtNr5   )rH   rJ  )_blockr   r5   r6   r     s   zBDerivative._sort_variable_count.<locals>._block.<locals>.<genexpr>T)r/  rm   r4  r   _wrt_variablesr   ru   rx   )dr   r  )r7  r  )r   r6   r    s"    


z/Derivative._sort_variable_count.<locals>._blockc                 S  s   g | ]\}}|qS r5   r5   )rH   r   r  r5   r5   r6   rK      s     z3Derivative._sort_variable_count.<locals>.<listcomp>c                   s    |  S rM   r5   r  )Or   r5   r6   rP   !  rQ   keyc                   s   g | ]} | qS r5   r5   r   r  r5   r6   rK   $  s     r   c                 S  s   g | ]}t | qS r5   )r
   r   r5   r5   r6   rK   )  s     )F)r   rY   r
   r[   r  r   dictr  r   r'   r(   )	r\   r  VEr   jr5  rz  r  r5   )r7  r  r  r   r  r6   rq    s,    1(zDerivative._sort_variable_countc                 C  s   | j jS rM   r  r   r=   r5   r5   r6   r   +  s    zDerivative._eval_is_commutativec                 C  s   || j krR| j|}t|tr:|j|jf| j|j  S | j|f| jddiS t| j}|	|df | j| jf|ddiS )Nr   Tr   F)
r  r  r   rm   r4  r   rr  rw  r   r   )r>   r   Zdedvrr  r5   r5   r6   r   .  s    


zDerivative._eval_derivativec                 K  s\   | j }|ddr|jf |}d|d< | j|f| j|}|| krX|trX|jf |}|S )NdeepTr   )r  rg   r`  r   rr  r   r4  )r>   hintsr  rvr5   r5   r6   r`  B  s    zDerivative.doitz0c                   sb   t  jdkst  jdkr$tdt jd  fdd}tt||	tj
jtj
jS )z
        Evaluate the derivative at z numerically.

        When we can represent derivatives at a point, this should be folded
        into the normal evalf. For now, we need a special method.
        r   z%partials and higher order derivativesr   c                   s<    j tj| tjjd}|ttjj}|	tjjS )Nr   )
r  r   r   r   r   mpr   r   r-   r   )r   Zf0r>   r#  r5   r6   rD   X  s    z)Derivative.doit_numerically.<locals>.eval)rY   ru   rw  r  r   r   r   r   r   r   r  r   )r>   r  rD   r5   r  r6   doit_numericallyL  s    
zDerivative.doit_numericallyc                 C  s
   | j d S r  _argsr=   r5   r5   r6   r  `  s    zDerivative.exprc                 C  s   dd | j D S )Nc                 S  s   g | ]}|d  qS r   r5   r   r5   r5   r6   rK   h  s     z-Derivative._wrt_variables.<locals>.<listcomp>)rr  r=   r5   r5   r6   r  d  s    zDerivative._wrt_variablesc                 C  s>   g }| j D ]*\}}|js$ttd||g|  q
t|S )Nz
                Cannot give expansion for symbolic count. If you just
                want a list of all variables of differentiation, use
                _wrt_variables.)rr  
is_Integerro   r+   extendrZ   )r>   r  r   rx  r5   r5   r6   rw  j  s    zDerivative.variablesc                 C  s   | j dd  S )Nr   r  r=   r5   r5   r6   rr  y  s    zDerivative.variable_countc                 C  s   t dd | jD dS )Nc                 S  s   g | ]\}}|qS r5   r5   )rH   rI   rx  r5   r5   r6   rK     s     z/Derivative.derivative_count.<locals>.<listcomp>r   )sumrr  r=   r5   r5   r6   derivative_count}  s    zDerivative.derivative_countc                 C  s(   | j j}| jD ]\}}||j q|S rM   )r  ru   rr  rO  )r>   retrI   rx  r5   r5   r6   ru     s    zDerivative.free_symbolsc                 C  s   | j d jS r  )r0   rE   r=   r5   r5   r6   rE     s    zDerivative.kindc                   s  | j kr| j| jf fdd| jD  }|| krB| S t ddsttrdt|  S t	d}t| 
|i| S jrj| jkr| jjkr S dd }tttj}ttt| j}|||rt f||   jS t| j} fdd|D }	|d	 kr&t|	 S |	d	 |d	 krd
d | j D fdd| j D }
|d	 
j|
@ } 
j}
j}|| |@ rt|  S dd t|	dd  |dd  D }tdd |D rt| jddD ]X}tdt|	D ]B}|	| \}}||kr||| d	 krt|      S qq|	dd  }| j }| j}g }t|D ]N\}\}}|jsft	d| }|
|| |i}||f||< |||f qf|r| }tt|f| ft|  S t|	 S )Nc                   s    g | ]\}}||  fqS r5   )r   re  r   r5   r6   rK     s   z)Derivative._eval_subs.<locals>.<listcomp>r   Fr  c                   s   t  fdd D S )Nc                 3  s"   | ]} | | kd kV  qdS )TNr5   r   r4   br5   r6   r     s     z9Derivative._eval_subs.<locals>._subset.<locals>.<genexpr>)rE  r  r5   r  r6   _subset  s    z&Derivative._eval_subs.<locals>._subsetc                   s   g | ]}|  qS r5   r   )rH   r   r   r5   r6   rK     s     r   c                 S  s   i | ]}|j s|t qS r5   )r/  r  rH   vir5   r5   r6   rK    s     z)Derivative._eval_subs.<locals>.<dictcomp>c                   s   h | ]}  ||qS r5   rv   r  )symsr5   r6   	<setcomp>  s     z(Derivative._eval_subs.<locals>.<setcomp>c                 s  s"   | ]\\}}\}}||fV  qd S rM   r5   )rH   r   rI   r  r5   r5   r6   r     s     z(Derivative._eval_subs.<locals>.<genexpr>r   c                 s  s   | ]\}}||kV  qd S rM   r5   )rH   r   r  r5   r5   r6   r     s     T)	recursiver-  )r  r   r  rr  r   rS   rm   rM  r3  r  rx   is_Derivativerd  r.   r  reversedr0  rW   r   r0   ru   r  r   r   r[   rY   r1  r   r   r   r4  )r>   r   r   r  r  r  Zold_varsZ	self_varsr0   Znewargsr  	forbiddenZnfreeZofreeZviterr4   r   r  rI   r  ZoldvZnewer   cir5   )r   r   r  r6   r     sh    




$zDerivative._eval_subsr   c                 c  s4   | j }| jj|||dD ]}| j|f| V  qd S )N)r   r"  )rw  r  lseriesr   )r>   r   r   r"  dxr*  r5   r5   r6   _eval_lseries  s    zDerivative._eval_lseriesc                   sX   j j|||d}| }j  fddt| D }|rP|||  t| S )Nr  c                   s   g | ]}j |f  qS r5   )r   r   r  r>   r5   r6   rK     s     z,Derivative._eval_nseries.<locals>.<listcomp>)r  r!  r  rw  r   	make_argsr  r   )r>   r   r   r   r"  r   r(  r  r5   r  r6   r    s    zDerivative._eval_nseriesNc                 C  s<   | j |}tj}|D ] }t|f| j }|dkr q8q|S r  )r  r  r   r  r   rw  )r>   r   r   r"  Z
series_genr  Zleading_termr5   r5   r6   r9    s    z Derivative._eval_as_leading_termr   c                 C  s   ddl m} || |||S )a   Expresses a Derivative instance as a finite difference.

        Parameters
        ==========

        points : sequence or coefficient, optional
            If sequence: discrete values (length >= order+1) of the
            independent variable used for generating the finite
            difference weights.
            If it is a coefficient, it will be used as the step-size
            for generating an equidistant sequence of length order+1
            centered around ``x0``. Default: 1 (step-size 1)

        x0 : number or Symbol, optional
            the value of the independent variable (``wrt``) at which the
            derivative is to be approximated. Default: same as ``wrt``.

        wrt : Symbol, optional
            "with respect to" the variable for which the (partial)
            derivative is to be approximated for. If not provided it
            is required that the derivative is ordinary. Default: ``None``.


        Examples
        ========

        >>> from sympy import symbols, Function, exp, sqrt, Symbol
        >>> x, h = symbols('x h')
        >>> f = Function('f')
        >>> f(x).diff(x).as_finite_difference()
        -f(x - 1/2) + f(x + 1/2)

        The default step size and number of points are 1 and
        ``order + 1`` respectively. We can change the step size by
        passing a symbol as a parameter:

        >>> f(x).diff(x).as_finite_difference(h)
        -f(-h/2 + x)/h + f(h/2 + x)/h

        We can also specify the discretized values to be used in a
        sequence:

        >>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h])
        -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)

        The algorithm is not restricted to use equidistant spacing, nor
        do we need to make the approximation around ``x0``, but we can get
        an expression estimating the derivative at an offset:

        >>> e, sq2 = exp(1), sqrt(2)
        >>> xl = [x-h, x+h, x+e*h]
        >>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2)  # doctest: +ELLIPSIS
        2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/...

        To approximate ``Derivative`` around ``x0`` using a non-equidistant
        spacing step, the algorithm supports assignment of undefined
        functions to ``points``:

        >>> dx = Function('dx')
        >>> f(x).diff(x).as_finite_difference(points=dx(x), x0=x-h)
        -f(-h + x - dx(-h + x)/2)/dx(-h + x) + f(-h + x + dx(-h + x)/2)/dx(-h + x)

        Partial derivatives are also supported:

        >>> y = Symbol('y')
        >>> d2fdxdy=f(x,y).diff(x,y)
        >>> d2fdxdy.as_finite_difference(wrt=x)
        -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)

        We can apply ``as_finite_difference`` to ``Derivative`` instances in
        compound expressions using ``replace``:

        >>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative,
        ...     lambda arg: arg.as_finite_difference())
        42**(-f(x - 1/2) + f(x + 1/2)) + 1


        See also
        ========

        sympy.calculus.finite_diff.apply_finite_diff
        sympy.calculus.finite_diff.differentiate_finite
        sympy.calculus.finite_diff.finite_diff_weights

        r   )_as_finite_diff)Zsympy.calculus.finite_diffr  )r>   ZpointsZx0r  r  r5   r5   r6   as_finite_difference  s    VzDerivative.as_finite_differencec                 C  s   t jS rM   )r   r  )r\   r  r5   r5   r6   rp  `  s    z$Derivative._get_zero_with_shape_likec                 C  s   | ||S rM   )Z_eval_derivative_n_times)r\   r  r   rx  r5   r5   r6   ru  d  s    z,Derivative._dispatch_eval_derivative_n_times)r   )r   )Nr   )r   NN)r9   r:   r;   rB   r  r   r   r   rd  rn   rq  r   r   r`  r   r  r  r  r  rw  rr  r  ru   rE   r   r  r  r9  r  rp  ru  r5   r5   r5   r6   r4    sN    3
! w

_








c

	
	
Y
r4  c                   s   ddl m} ddlm} ddlm} |||tttf t	|  sTt
 fdd|D rpddlm} || f||S t| f||S )Nr   rh  rf  )rb  c                 3  s6   | ].}t |tttfr$t |d   nt | V  qdS r   N)rm   rZ   r   r
   r   Zarray_typesr5   r6   r   r  s     z'_derivative_dispatch.<locals>.<genexpr>)ArrayDerivative)rs  ri  ro  rg  rm  rb  r   rZ   r
   rm   r   Z$sympy.tensor.array.array_derivativesr  r4  )r  rw  rp   ri  rg  rb  r  r5   r  r6   r0  m  s     r0  c                   @  s   e Zd ZdZdZdd Zedd Zedd Z	ed	d
 Z
edd Zedd ZeZedd Zdd Zdd Zedd Zdd ZdS )Lambdaa  
    Lambda(x, expr) represents a lambda function similar to Python's
    'lambda x: expr'. A function of several variables is written as
    Lambda((x, y, ...), expr).

    Examples
    ========

    A simple example:

    >>> from sympy import Lambda
    >>> from sympy.abc import x
    >>> f = Lambda(x, x**2)
    >>> f(4)
    16

    For multivariate functions, use:

    >>> from sympy.abc import y, z, t
    >>> f2 = Lambda((x, y, z, t), x + y**z + t**z)
    >>> f2(1, 2, 3, 4)
    73

    It is also possible to unpack tuple arguments:

    >>> f = Lambda(((x, y), z), x + y + z)
    >>> f((1, 2), 3)
    6

    A handy shortcut for lots of arguments:

    >>> p = x, y, z
    >>> f = Lambda(p, x + y*z)
    >>> f(*p)
    x + y*z

    Tc                 C  s   t |r,t|ttfs,tdddd t|}t |r8|n|f}t|}| | t|dkrn|d |krntj	S t
| |t|S )Nz
                Using a non-tuple iterable as the first argument to Lambda
                is deprecated. Use Lambda(tuple(args), expr) instead.
                z1.5zdeprecated-non-tuple-lambdaZdeprecated_since_versionZactive_deprecations_targetr   r   )r%   rm   rZ   r
   r    r   _check_signaturerY   r   ZIdentityFunctionr   r   )r\   rU   r  sigr5   r5   r6   r     s    
zLambda.__new__c                   s6   t   fdd t|ts*td|  | d S )Nc                   sT   | D ]J}|j r.|kr"td| | qt|trB | qtd| qd S )NzDuplicate symbol %sz:Lambda signature should be only tuples and symbols, not %s)rt  r@   addrm   r
   )r0   r4   rcheckr  r5   r6   r    s    

z'Lambda._check_signature.<locals>.rcheckz)Lambda signature should be a tuple not %s)rl   rm   r
   r@   )r\   r  r5   r  r6   r    s
    
zLambda._check_signaturec                 C  s
   | j d S )z@The expected form of the arguments to be unpacked into variablesr   r  r=   r5   r5   r6   rU     s    zLambda.signaturec                 C  s
   | j d S )z The return value of the functionr   r  r=   r5   r5   r6   r    s    zLambda.exprc                   s    fdd t  | jS )zAThe variables used in the internal representation of the functionc                 3  s.   t | tr$| D ]} |E d H  qn| V  d S rM   )rm   r
   )r0   r   
_variablesr5   r6   r    s    
z$Lambda.variables.<locals>._variables)rZ   rU   r=   r5   r  r6   rw    s    zLambda.variablesc                 C  s   ddl m} |t| jS )Nr   ry   )r{   rz   rY   rU   r}   r5   r5   r6   ra     s    zLambda.nargsc                 C  s   | j jt| j S rM   )r  ru   rl   rw  r=   r5   r5   r6   ru     s    zLambda.free_symbolsc                 G  sb   t |}|| jkrHd}t|| t| jd dt| jd dk |d | | j|}| j|S )NzD%(name)s takes exactly %(args)s argument%(plural)s (%(given)s given)r   r   r   )r   r0   r   r   )rY   ra   rC   r   _match_signaturerU   r  rx   )r>   r0   r   r   r  r5   r5   r6   __call__  s    

zLambda.__call__c                   s    i  fdd  || S )Nc                   sj   t | |D ]Z\}}|jr"||< q
t|tr
t|ttfrJt|t| krZtd|| f  || q
d S )NzCan't match %s and %s)r  rt  rm   r
   rZ   rY   rC   )Zparsr0   parr   rmatchZ	symargmapr5   r6   r    s    

z'Lambda._match_signature.<locals>.rmatchr5   )r>   r  r0   r5   r  r6   r    s    	
zLambda._match_signaturec                 C  s   | j | jkS )z<Return ``True`` if this ``Lambda`` is an identity function. )rU   r  r=   r5   r5   r6   is_identity  s    zLambda.is_identityc                 C  s$   |  | jd | jd jt|dS )Nr   r   r   )r   r0   r   r-   )r>   r   r5   r5   r6   r     s    zLambda._eval_evalfN)r9   r:   r;   rB   r   r   rn   r  r   rU   r  rw  ra   bound_symbolsru   r  r  r  r   r5   r5   r5   r6   r  x  s*   %







r  c                      s   e Zd ZdZdd Zdd Zdd Zd&d	d
ZeZe	dd Z
e
Ze	dd Ze	dd Ze	dd Ze	dd Zdd Zdd Z fddZdd Zdd Zdd  Zd'd"d#Zd(d$d%Z  ZS ))r3  a	  
    Represents unevaluated substitutions of an expression.

    ``Subs(expr, x, x0)`` represents the expression resulting
    from substituting x with x0 in expr.

    Parameters
    ==========

    expr : Expr
        An expression.

    x : tuple, variable
        A variable or list of distinct variables.

    x0 : tuple or list of tuples
        A point or list of evaluation points
        corresponding to those variables.

    Examples
    ========

    >>> from sympy import Subs, Function, sin, cos
    >>> from sympy.abc import x, y, z
    >>> f = Function('f')

    Subs are created when a particular substitution cannot be made. The
    x in the derivative cannot be replaced with 0 because 0 is not a
    valid variables of differentiation:

    >>> f(x).diff(x).subs(x, 0)
    Subs(Derivative(f(x), x), x, 0)

    Once f is known, the derivative and evaluation at 0 can be done:

    >>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0)
    True

    Subs can also be created directly with one or more variables:

    >>> Subs(f(x)*sin(y) + z, (x, y), (0, 1))
    Subs(z + f(x)*sin(y), (x, y), (0, 1))
    >>> _.doit()
    z + f(0)*sin(1)

    Notes
    =====

    ``Subs`` objects are generally useful to represent unevaluated derivatives
    calculated at a point.

    The variables may be expressions, but they are subjected to the limitations
    of subs(), so it is usually a good practice to use only symbols for
    variables, since in that case there can be no ambiguity.

    There's no automatic expansion - use the method .doit() to effect all
    possible substitutions of the object and also of objects inside the
    expression.

    When evaluating derivatives at a point that is not a symbol, a Subs object
    is returned. One is also able to calculate derivatives of Subs objects - in
    this case the expression is always expanded (for the unevaluated form, use
    Derivative()).

    In order to allow expressions to combine before doit is done, a
    representation of the Subs expression is used internally to make
    expressions that are superficially different compare the same:

    >>> a, b = Subs(x, x, 0), Subs(y, y, 0)
    >>> a + b
    2*Subs(x, x, 0)

    This can lead to unexpected consequences when using methods
    like `has` that are cached:

    >>> s = Subs(x, x, 0)
    >>> s.has(x), s.has(y)
    (True, False)
    >>> ss = s.subs(x, y)
    >>> ss.has(x), ss.has(y)
    (True, False)
    >>> s, ss
    (Subs(x, x, 0), Subs(y, y, 0))
    c                   sz  t tsgt trPdd t D }d|}ttd| tt tr`ng ttkrtdst	S t
trj j jnt	dtttd}dd	lm} G d
d d|  fddfdd|D fddtD }	tfdd|	D rRd7 qqRqt| t }
t|	|
_|
S )Nc                 S  s    g | ]\}}|d krt |qS r   )rk   )rH   r   r   r5   r5   r6   rK   s  s      z Subs.__new__.<locals>.<listcomp>r;  zU
                The following expressions appear more than once: %s
                zCNumber of point values must be the same as the number of variables.rI   r  r   )
StrPrinterc                   @  s   e Zd Zdd ZdS )z&Subs.__new__.<locals>.CustomStrPrinterc                 S  s   t |t |j S rM   )rk   r.  )r>   r  r5   r5   r6   _print_Dummy  s    z3Subs.__new__.<locals>.CustomStrPrinter._print_DummyN)r9   r:   r;   r  r5   r5   r5   r6   CustomStrPrinter  s   r  c                   s    |}| | S rM   )Zdoprint)r  settingsrJ   )r  r5   r6   mystr  s    zSubs.__new__.<locals>.mystrc                   s   i | ]}|t  | qS r5   )rM  rH   rJ   )r  prer5   r6   rK    s      z Subs.__new__.<locals>.<dictcomp>c                   s   g | ]\}}| | fqS r5   r5   rH   r   rJ   )s_ptsr5   r6   rK     s   c                 3  sB   | ]:\}}| j ko8|ko8t|  |kV  qd S rM   )ru   rM  index)rH   rI   r  )r  r  pointr  rw  r5   r6   r     s
   
zSubs.__new__.<locals>.<genexpr>)r&   r
   r#   r.   rW   r<  rj   r+   rY   r   rm   r3  rw  r  r  sortedrl   r   Zsympy.printing.strr  r  r   r   r   rx   r  _expr)r\   r  rw  r  rR  Zrepeatedr{  Zptsr  repsr   r5   )r  r  r  r  r  r  rw  r6   r   m  sJ    






zSubs.__new__c                 C  s   | j jS rM   r  r=   r5   r5   r6   r     s    zSubs._eval_is_commutativec                 K  s6  | j \}}}tt||D ]L\}\}}||kr|d | ||d d   }|d | ||d d   }q|sr| jS t|trg }t|D ]6\}}t|tr|||| }q|||| f qt|ts|	 }t|trg }	t
 }
|j d }|D ]F\}}|
|||
ijkr0||r>|||}q|	||f q|	}g }t
 }
|j}|j}|jD ]b\}}t|tr||kr|||f}n2|
|||
jkr|||f}n|||f q`||}|D ]}||}qn
||}n|j	f |tt||}|ddr2|| kr2|j	f |}|S )Nr   r   r  T)r0   r1  r  r  rm   r4  r`   r   r   r`  r  rx   ru   r   rr  rM  r   r   rg   )r>   r  r)  r   rJ   r   r  r&  ZundoneZundone2r7  r   r  r  r}  r  r  r  r5   r5   r6   r`    sV    



z	Subs.doitNc                 K  s   |   j|f|S rM   )r`  r   )r>   r   r   r5   r5   r6   r     s    z
Subs.evalfc                 C  s
   | j d S )zThe variables to be evaluatedr   r  r=   r5   r5   r6   rw    s    zSubs.variablesc                 C  s
   | j d S )z1The expression on which the substitution operatesr   r  r=   r5   r5   r6   r    s    z	Subs.exprc                 C  s
   | j d S )z8The values for which the variables are to be substitutedrd   r  r=   r5   r5   r6   r    s    z
Subs.pointc                 C  s   | j jt| j t| jjB S rM   )r  ru   rl   rw  r  r=   r5   r5   r6   ru    	  s    
zSubs.free_symbolsc              
   C  sL   t dddd tt, | jjt| j t| jjB W  5 Q R  S Q R X d 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-symbolsr  )r    r"   r!   r  expr_free_symbolsrl   rw  r  r=   r5   r5   r6   r  	  s    

zSubs.expr_free_symbolsc                 C  s   t |tsdS |  | kS r   )rm   r3  _hashable_contentrW  r5   r5   r6   rY  	  s    
zSubs.__eq__c                 C  s
   | |k S rM   r5   rW  r5   r5   r6   rZ  	  s    zSubs.__ne__c                   s
   t   S rM   )r   rV  r=   r   r5   r6   rV  	  s    zSubs.__hash__c                   s4    j  jftt fddt j jD  S )Nc                   s$   g | ]\}} j |s||fqS r5   )r  r   r  r=   r5   r6   rK   	  s    z*Subs._hashable_content.<locals>.<listcomp>)r  rx   Zcanonical_variablesrZ   r   r  rw  r  r=   r5   r=   r6   r  	  s
    zSubs._hashable_contentc                   s  t | j}| jkrt  hkrHt fdd| jD sH|  iS | j}t|t	| jD ]}|| 
 ||< qd| | j| j|S  fdd| jD }|t | jkr| | j| jf | g S | j
 } fdd| jD }| |||S )Nc                 3  s   | ]}|  V  qd S rM   r   r   )r   r5   r6   r   )	  s    z"Subs._eval_subs.<locals>.<genexpr>c                   s   g | ]}|  qS r5   r   r   r   r5   r6   rK   3	  s     z#Subs._eval_subs.<locals>.<listcomp>c                   s   g | ]}|  qS r5   r   r   r   r5   r6   rK   7	  s     )r   r  rw  r   r   r0   rx   r  r[   rY   r   r   r  )r>   r   r   ptr   r  r   r  r5   r   r6   r   "	  s     

zSubs._eval_subsc                   s   | j  | j| jf \}}t fddt||D } j}dd |D }dd |D } tt||}|j| }	|	|B }
|
t	|8 }
|
dd |
|@ D O }
|
j@ r|t
 | j| j 7 }|S )Nc                 3  s4   | ],\}}| t  |f   V  qd S rM   )r   r3  r`  r  fr   Zvpr5   r6   r   >	  s   z(Subs._eval_derivative.<locals>.<genexpr>c                 S  s   h | ]}t |jd kr|qS r  )rY   ru   r   r5   r5   r6   r  E	  s      z(Subs._eval_derivative.<locals>.<setcomp>c                 S  s   h | ]
}t  qS r5   r  r   r5   r5   r6   r  G	  s     c                 S  s   h | ]}|j D ]}|qqS r5   )ru   )rH   r  r   r5   r5   r6   r  O	  s       )r  rw  r  r   Zfromiterr  ru   rx   r  rl   r3  r   r`  )r>   r   r  PvalZefreeZcompoundZdumsZmaskedZifreer}  r5   r  r6   r   :	  s     

zSubs._eval_derivativer   c                   s|   | j kr" j |} j| }n|} jj|||d}| }t| }	t fdd|	D  }
|rx|
|	||7 }
|
S )Nr  c                   s&   g | ]} j |f jd d  qS r  )r   r0   r   r=   r5   r6   rK   _	  s     z&Subs._eval_nseries.<locals>.<listcomp>)
r  r  rw  r  r!  r  r   r  r  r   )r>   r   r   r   r"  ZaposrX  r   r(  Ztermsr  r5   r=   r6   r  U	  s    
zSubs._eval_nseriesc                 C  sF   || j kr,| j |}| j| }| j|S || jkr:| S | j|S rM   )r  r  rw  r  r  )r>   r   r   r"  ZiposZxvarr5   r5   r6   r9  d	  s    


zSubs._eval_as_leading_term)N)r   )Nr   )r9   r:   r;   rB   r   r   r`  r   r   r   rw  r  r  r  ru   r  rY  rZ  rV  r  r   r   r  r9  r   r5   r5   r   r6   r3    s2   T><






r3  c                 O  s2   t | dr| j||S |dd t| f||S )a  
    Differentiate f with respect to symbols.

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

    This is just a wrapper to unify .diff() and the Derivative class; its
    interface is similar to that of integrate().  You can use the same
    shortcuts for multiple variables as with Derivative.  For example,
    diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative
    of f(x).

    You can pass evaluate=False to get an unevaluated Derivative class.  Note
    that if there are 0 symbols (such as diff(f(x), x, 0), then the result will
    be the function (the zeroth derivative), even if evaluate=False.

    Examples
    ========

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

    >>> diff(sin(x), x)
    cos(x)
    >>> diff(f(x), x, x, x)
    Derivative(f(x), (x, 3))
    >>> diff(f(x), x, 3)
    Derivative(f(x), (x, 3))
    >>> diff(sin(x)*cos(y), x, 2, y, 2)
    sin(x)*cos(y)

    >>> type(diff(sin(x), x))
    cos
    >>> type(diff(sin(x), x, evaluate=False))
    <class 'sympy.core.function.Derivative'>
    >>> type(diff(sin(x), x, 0))
    sin
    >>> type(diff(sin(x), x, 0, evaluate=False))
    sin

    >>> diff(sin(x))
    cos(x)
    >>> diff(sin(x*y))
    Traceback (most recent call last):
    ...
    ValueError: specify differentiation variables to differentiate sin(x*y)

    Note that ``diff(sin(x))`` syntax is meant only for convenience
    in interactive sessions and should be avoided in library code.

    References
    ==========

    .. [1] https://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html

    See Also
    ========

    Derivative
    idiff: computes the derivative implicitly

    r   r   T)ri   r   
setdefaultr0  )r  symbolsrp   r5   r5   r6   r   q	  s    @
r   Tc	           
      K  sJ   ||	d< ||	d< ||	d< ||	d< ||	d< ||	d< t | jf ||d|	S )a*  
    Expand an expression using methods given as hints.

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

    Hints evaluated unless explicitly set to False are:  ``basic``, ``log``,
    ``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following
    hints are supported but not applied unless set to True:  ``complex``,
    ``func``, and ``trig``.  In addition, the following meta-hints are
    supported by some or all of the other hints:  ``frac``, ``numer``,
    ``denom``, ``modulus``, and ``force``.  ``deep`` is supported by all
    hints.  Additionally, subclasses of Expr may define their own hints or
    meta-hints.

    The ``basic`` hint is used for any special rewriting of an object that
    should be done automatically (along with the other hints like ``mul``)
    when expand is called. This is a catch-all hint to handle any sort of
    expansion that may not be described by the existing hint names. To use
    this hint an object should override the ``_eval_expand_basic`` method.
    Objects may also define their own expand methods, which are not run by
    default.  See the API section below.

    If ``deep`` is set to ``True`` (the default), things like arguments of
    functions are recursively expanded.  Use ``deep=False`` to only expand on
    the top level.

    If the ``force`` hint is used, assumptions about variables will be ignored
    in making the expansion.

    Hints
    =====

    These hints are run by default

    mul
    ---

    Distributes multiplication over addition:

    >>> from sympy import cos, exp, sin
    >>> from sympy.abc import x, y, z
    >>> (y*(x + z)).expand(mul=True)
    x*y + y*z

    multinomial
    -----------

    Expand (x + y + ...)**n where n is a positive integer.

    >>> ((x + y + z)**2).expand(multinomial=True)
    x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2

    power_exp
    ---------

    Expand addition in exponents into multiplied bases.

    >>> exp(x + y).expand(power_exp=True)
    exp(x)*exp(y)
    >>> (2**(x + y)).expand(power_exp=True)
    2**x*2**y

    power_base
    ----------

    Split powers of multiplied bases.

    This only happens by default if assumptions allow, or if the
    ``force`` meta-hint is used:

    >>> ((x*y)**z).expand(power_base=True)
    (x*y)**z
    >>> ((x*y)**z).expand(power_base=True, force=True)
    x**z*y**z
    >>> ((2*y)**z).expand(power_base=True)
    2**z*y**z

    Note that in some cases where this expansion always holds, SymPy performs
    it automatically:

    >>> (x*y)**2
    x**2*y**2

    log
    ---

    Pull out power of an argument as a coefficient and split logs products
    into sums of logs.

    Note that these only work if the arguments of the log function have the
    proper assumptions--the arguments must be positive and the exponents must
    be real--or else the ``force`` hint must be True:

    >>> from sympy import log, symbols
    >>> log(x**2*y).expand(log=True)
    log(x**2*y)
    >>> log(x**2*y).expand(log=True, force=True)
    2*log(x) + log(y)
    >>> x, y = symbols('x,y', positive=True)
    >>> log(x**2*y).expand(log=True)
    2*log(x) + log(y)

    basic
    -----

    This hint is intended primarily as a way for custom subclasses to enable
    expansion by default.

    These hints are not run by default:

    complex
    -------

    Split an expression into real and imaginary parts.

    >>> x, y = symbols('x,y')
    >>> (x + y).expand(complex=True)
    re(x) + re(y) + I*im(x) + I*im(y)
    >>> cos(x).expand(complex=True)
    -I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))

    Note that this is just a wrapper around ``as_real_imag()``.  Most objects
    that wish to redefine ``_eval_expand_complex()`` should consider
    redefining ``as_real_imag()`` instead.

    func
    ----

    Expand other functions.

    >>> from sympy import gamma
    >>> gamma(x + 1).expand(func=True)
    x*gamma(x)

    trig
    ----

    Do trigonometric expansions.

    >>> cos(x + y).expand(trig=True)
    -sin(x)*sin(y) + cos(x)*cos(y)
    >>> sin(2*x).expand(trig=True)
    2*sin(x)*cos(x)

    Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)``
    and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x)
    = 1`.  The current implementation uses the form obtained from Chebyshev
    polynomials, but this may change.  See `this MathWorld article
    <https://mathworld.wolfram.com/Multiple-AngleFormulas.html>`_ for more
    information.

    Notes
    =====

    - You can shut off unwanted methods::

        >>> (exp(x + y)*(x + y)).expand()
        x*exp(x)*exp(y) + y*exp(x)*exp(y)
        >>> (exp(x + y)*(x + y)).expand(power_exp=False)
        x*exp(x + y) + y*exp(x + y)
        >>> (exp(x + y)*(x + y)).expand(mul=False)
        (x + y)*exp(x)*exp(y)

    - Use deep=False to only expand on the top level::

        >>> exp(x + exp(x + y)).expand()
        exp(x)*exp(exp(x)*exp(y))
        >>> exp(x + exp(x + y)).expand(deep=False)
        exp(x)*exp(exp(x + y))

    - Hints are applied in an arbitrary, but consistent order (in the current
      implementation, they are applied in alphabetical order, except
      multinomial comes before mul, but this may change).  Because of this,
      some hints may prevent expansion by other hints if they are applied
      first. For example, ``mul`` may distribute multiplications and prevent
      ``log`` and ``power_base`` from expanding them. Also, if ``mul`` is
      applied before ``multinomial`, the expression might not be fully
      distributed. The solution is to use the various ``expand_hint`` helper
      functions or to use ``hint=False`` to this function to finely control
      which hints are applied. Here are some examples::

        >>> from sympy import expand, expand_mul, expand_power_base
        >>> x, y, z = symbols('x,y,z', positive=True)

        >>> expand(log(x*(y + z)))
        log(x) + log(y + z)

      Here, we see that ``log`` was applied before ``mul``.  To get the mul
      expanded form, either of the following will work::

        >>> expand_mul(log(x*(y + z)))
        log(x*y + x*z)
        >>> expand(log(x*(y + z)), log=False)
        log(x*y + x*z)

      A similar thing can happen with the ``power_base`` hint::

        >>> expand((x*(y + z))**x)
        (x*y + x*z)**x

      To get the ``power_base`` expanded form, either of the following will
      work::

        >>> expand((x*(y + z))**x, mul=False)
        x**x*(y + z)**x
        >>> expand_power_base((x*(y + z))**x)
        x**x*(y + z)**x

        >>> expand((x + y)*y/x)
        y + y**2/x

      The parts of a rational expression can be targeted::

        >>> expand((x + y)*y/x/(x + 1), frac=True)
        (x*y + y**2)/(x**2 + x)
        >>> expand((x + y)*y/x/(x + 1), numer=True)
        (x*y + y**2)/(x*(x + 1))
        >>> expand((x + y)*y/x/(x + 1), denom=True)
        y*(x + y)/(x**2 + x)

    - The ``modulus`` meta-hint can be used to reduce the coefficients of an
      expression post-expansion::

        >>> expand((3*x + 1)**2)
        9*x**2 + 6*x + 1
        >>> expand((3*x + 1)**2, modulus=5)
        4*x**2 + x + 1

    - Either ``expand()`` the function or ``.expand()`` the method can be
      used.  Both are equivalent::

        >>> expand((x + 1)**2)
        x**2 + 2*x + 1
        >>> ((x + 1)**2).expand()
        x**2 + 2*x + 1

    API
    ===

    Objects can define their own expand hints by defining
    ``_eval_expand_hint()``.  The function should take the form::

        def _eval_expand_hint(self, **hints):
            # Only apply the method to the top-level expression
            ...

    See also the example below.  Objects should define ``_eval_expand_hint()``
    methods only if ``hint`` applies to that specific object.  The generic
    ``_eval_expand_hint()`` method defined in Expr will handle the no-op case.

    Each hint should be responsible for expanding that hint only.
    Furthermore, the expansion should be applied to the top-level expression
    only.  ``expand()`` takes care of the recursion that happens when
    ``deep=True``.

    You should only call ``_eval_expand_hint()`` methods directly if you are
    100% sure that the object has the method, as otherwise you are liable to
    get unexpected ``AttributeError``s.  Note, again, that you do not need to
    recursively apply the hint to args of your object: this is handled
    automatically by ``expand()``.  ``_eval_expand_hint()`` should
    generally not be used at all outside of an ``_eval_expand_hint()`` method.
    If you want to apply a specific expansion from within another method, use
    the public ``expand()`` function, method, or ``expand_hint()`` functions.

    In order for expand to work, objects must be rebuildable by their args,
    i.e., ``obj.func(*obj.args) == obj`` must hold.

    Expand methods are passed ``**hints`` so that expand hints may use
    'metahints'--hints that control how different expand methods are applied.
    For example, the ``force=True`` hint described above that causes
    ``expand(log=True)`` to ignore assumptions is such a metahint.  The
    ``deep`` meta-hint is handled exclusively by ``expand()`` and is not
    passed to ``_eval_expand_hint()`` methods.

    Note that expansion hints should generally be methods that perform some
    kind of 'expansion'.  For hints that simply rewrite an expression, use the
    .rewrite() API.

    Examples
    ========

    >>> from sympy import Expr, sympify
    >>> class MyClass(Expr):
    ...     def __new__(cls, *args):
    ...         args = sympify(args)
    ...         return Expr.__new__(cls, *args)
    ...
    ...     def _eval_expand_double(self, *, force=False, **hints):
    ...         '''
    ...         Doubles the args of MyClass.
    ...
    ...         If there more than four args, doubling is not performed,
    ...         unless force=True is also used (False by default).
    ...         '''
    ...         if not force and len(self.args) > 4:
    ...             return self
    ...         return self.func(*(self.args + self.args))
    ...
    >>> a = MyClass(1, 2, MyClass(3, 4))
    >>> a
    MyClass(1, 2, MyClass(3, 4))
    >>> a.expand(double=True)
    MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4))
    >>> a.expand(double=True, deep=False)
    MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))

    >>> b = MyClass(1, 2, 3, 4, 5)
    >>> b.expand(double=True)
    MyClass(1, 2, 3, 4, 5)
    >>> b.expand(double=True, force=True)
    MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

    See Also
    ========

    expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig,
    expand_power_base, expand_power_exp, expand_func, sympy.simplify.hyperexpand.hyperexpand

    
power_base	power_expmulr   multinomialbasic)r  modulusr   r  )
r)  r  r  r  r  r  r   r  r  r  r5   r5   r6   r  	  s      Er  Fc                 C  s6   | d krd S d }|| kr2| t t|  }} |sq2q| S rM   )
expand_mulexpand_multinomial)r  r  wasr5   r5   r6   _mexpand  s    r  c              	   C  s   t | j|dddddddS )aY  
    Wrapper around expand that only uses the mul hint.  See the expand
    docstring for more information.

    Examples
    ========

    >>> from sympy import symbols, expand_mul, exp, log
    >>> x, y = symbols('x,y', positive=True)
    >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2))
    x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)

    TFr  r  r  r  r  r  r   r  r  r  r5   r5   r6   r    s       r  c              	   C  s   t | j|dddddddS )aV  
    Wrapper around expand that only uses the multinomial hint.  See the expand
    docstring for more information.

    Examples
    ========

    >>> from sympy import symbols, expand_multinomial, exp
    >>> x, y = symbols('x y', positive=True)
    >>> expand_multinomial((x + exp(x + 1))**2)
    x**2 + 2*x*exp(x + 1) + exp(2*x + 2)

    FTr  r  r  r5   r5   r6   r  '  s       r  c                   sX   ddl m |dkr8 fdd}| fdd|} t| j dddddd|d		S )
aL  
    Wrapper around expand that only uses the log hint.  See the expand
    docstring for more information.

    Examples
    ========

    >>> from sympy import symbols, expand_log, exp, log
    >>> x, y = symbols('x,y', positive=True)
    >>> expand_log(exp(x+y)*(x+y)*log(x*y**2))
    (x + y)*(log(x) + 2*log(y))*exp(x + y)

    r   r   Fc                   s0   t t|  dd}|| kr,|S | S )NT)r  forcefactor)r  
expand_logrx  )r   x1r  r  r   r5   r6   _handleI  s    zexpand_log.<locals>._handlec                   s    | j ot fdd|  D S )Nc                 3  s*   | ]"}t  fd dt|D V  qdS )c                 3  s$   | ]}t | o|jd  jV  qdS r  )rm   r0   is_Rationalr   r  r5   r6   r   P  s   z9expand_log.<locals>.<lambda>.<locals>.<genexpr>.<genexpr>N)r   r   r  )rH   r  r  r5   r6   r   P  s   z/expand_log.<locals>.<lambda>.<locals>.<genexpr>)r1   rE  Zas_numer_denomr   r  r5   r6   rP   P  s   zexpand_log.<locals>.<lambda>T)	r  r   r  r  r  r  r  r  r  )Z&sympy.functions.elementary.exponentialr   rv  r   r  )r  r  r  r  r  r5   r  r6   r  9  s    
    r  c              
   C  s   t | j|ddddddddS )a  
    Wrapper around expand that only uses the func hint.  See the expand
    docstring for more information.

    Examples
    ========

    >>> from sympy import expand_func, gamma
    >>> from sympy.abc import x
    >>> expand_func(gamma(x + 2))
    x*(x + 1)*gamma(x)

    TF)r  r   r  r   r  r  r  r  r  r  r5   r5   r6   expand_funcY  s        r  c              
   C  s   t | j|ddddddddS )a,  
    Wrapper around expand that only uses the trig hint.  See the expand
    docstring for more information.

    Examples
    ========

    >>> from sympy import expand_trig, sin
    >>> from sympy.abc import x, y
    >>> expand_trig(sin(x+y)*(x+y))
    (x + y)*(sin(x)*cos(y) + sin(y)*cos(x))

    TF)r  Ztrigr  r   r  r  r  r  r  r  r5   r5   r6   expand_trigk  s        r  c              
   C  s   t | j|ddddddddS )a  
    Wrapper around expand that only uses the complex hint.  See the expand
    docstring for more information.

    Examples
    ========

    >>> from sympy import expand_complex, exp, sqrt, I
    >>> from sympy.abc import z
    >>> expand_complex(exp(z))
    I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z))
    >>> expand_complex(sqrt(I))
    sqrt(2)/2 + sqrt(2)*I/2

    See Also
    ========

    sympy.core.expr.Expr.as_real_imag
    TFr  complexr  r   r  r  r  r  r  r  r5   r5   r6   expand_complex}  s        r  c              
   C  s   t | j|dddddd|dS )a  
    Wrapper around expand that only uses the power_base hint.

    A wrapper to expand(power_base=True) which separates a power with a base
    that is a Mul into a product of powers, without performing any other
    expansions, provided that assumptions about the power's base and exponent
    allow.

    deep=False (default is True) will only apply to the top-level expression.

    force=True (default is False) will cause the expansion to ignore
    assumptions about the base and exponent. When False, the expansion will
    only happen if the base is non-negative or the exponent is an integer.

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

    >>> (x*y)**2
    x**2*y**2

    >>> (2*x)**y
    (2*x)**y
    >>> expand_power_base(_)
    2**y*x**y

    >>> expand_power_base((x*y)**z)
    (x*y)**z
    >>> expand_power_base((x*y)**z, force=True)
    x**z*y**z
    >>> expand_power_base(sin((x*y)**z), deep=False)
    sin((x*y)**z)
    >>> expand_power_base(sin((x*y)**z), force=True)
    sin(x**z*y**z)

    >>> expand_power_base((2*sin(x))**y + (2*cos(x))**y)
    2**y*sin(x)**y + 2**y*cos(x)**y

    >>> expand_power_base((2*exp(y))**x)
    2**x*exp(y)**x

    >>> expand_power_base((2*cos(x))**y)
    2**y*cos(x)**y

    Notice that sums are left untouched. If this is not the desired behavior,
    apply full ``expand()`` to the expression:

    >>> expand_power_base(((x+y)*z)**2)
    z**2*(x + y)**2
    >>> (((x+y)*z)**2).expand()
    x**2*z**2 + 2*x*y*z**2 + y**2*z**2

    >>> expand_power_base((2*y)**(1+z))
    2**(z + 1)*y**(z + 1)
    >>> ((2*y)**(1+z)).expand()
    2*2**z*y**(z + 1)

    The power that is unexpanded can be expanded safely when
    ``y != 0``, otherwise different values might be obtained for the expression:

    >>> prev = _

    If we indicate that ``y`` is positive but then replace it with
    a value of 0 after expansion, the expression becomes 0:

    >>> p = Symbol('p', positive=True)
    >>> prev.subs(y, p).expand().subs(p, 0)
    0

    But if ``z = -1`` the expression would not be zero:

    >>> prev.subs(y, 0).subs(z, -1)
    1

    See Also
    ========

    expand

    FT)r  r   r  r  r  r  r  r  r  )r  r  r  r5   r5   r6   expand_power_base  s    P   r  c              
   C  s   t | j|ddddddddS )aK  
    Wrapper around expand that only uses the power_exp hint.

    See the expand docstring for more information.

    Examples
    ========

    >>> from sympy import expand_power_exp, Symbol
    >>> from sympy.abc import x, y
    >>> expand_power_exp(3**(y + 2))
    9*3**y
    >>> expand_power_exp(x**(y + 2))
    x**(y + 2)

    If ``x = 0`` the value of the expression depends on the
    value of ``y``; if the expression were expanded the result
    would be 0. So expansion is only done if ``x != 0``:

    >>> expand_power_exp(Symbol('x', zero=False)**(y + 2))
    x**2*x**y
    FTr  r  r  r5   r5   r6   expand_power_exp  s        r  c                   s  ddl m} ddlm} ddlm} ddlm} ddlm	} t
| } t| tr| jsg }| g}td}	td	}
td
}td}td}|r| }|jr|tjk	r|jdk r||	 |jdkr||
 qnx|js|jrt|r||	 |jd tjkr| d }n| }||\}}|jr^||
 |dk rP||	 || qn4|tjk	rN|js||| ||
 || qn|js|jrNt|j}d}t |D ]\\}}t|r|d7 }||  |dkr|| n|| |dkr|| q|t!|kr2||	 qt|d r|||  q|j"r||j#tjkr|||
 ||j$ q|tj%kr|| q|j"r|j$tj%kr|| ||j# q|jst|t&r t|j'j() }||t!|jd   nz|jrz|j"s<|j*s<t|t+s<t||s<t||rzt|j't,r`td|j'j()  }nt|j'j() }|| |j-s|.|j qn.t| t/r fdd| 0 D }nt1| rև fdd| D }nt| ||fr*g }| jD ]}|t2|dd qtt3| dd) }|| nt| t4s<g }nt| t4sRt5dnng }| g}|r| }|jr\tt6|j() }|j7r||t!|jd   n
|| |.|j q\|sֈ rtj8S dS t9| } r|S |j:rt;|S t<dd t9=|D S )a  
    Return a representation (integer or expression) of the operations in expr.

    Parameters
    ==========

    expr : Expr
        If expr is an iterable, the sum of the op counts of the
        items will be returned.

    visual : bool, optional
        If ``False`` (default) then the sum of the coefficients of the
        visual expression will be returned.
        If ``True`` then the number of each type of operation is shown
        with the core class types (or their virtual equivalent) multiplied by the
        number of times they occur.

    Examples
    ========

    >>> from sympy.abc import a, b, x, y
    >>> from sympy import sin, count_ops

    Although there is not a SUB object, minus signs are interpreted as
    either negations or subtractions:

    >>> (x - y).count_ops(visual=True)
    SUB
    >>> (-x).count_ops(visual=True)
    NEG

    Here, there are two Adds and a Pow:

    >>> (1 + a + b**2).count_ops(visual=True)
    2*ADD + POW

    In the following, an Add, Mul, Pow and two functions:

    >>> (sin(x)*x + sin(x)**2).count_ops(visual=True)
    ADD + MUL + POW + 2*SIN

    for a total of 5:

    >>> (sin(x)*x + sin(x)**2).count_ops(visual=False)
    5

    Note that "what you type" is not always what you get. The expression
    1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather
    than two DIVs:

    >>> (1/x/y).count_ops(visual=True)
    DIV + MUL

    The visual option can be used to demonstrate the difference in
    operations for expressions in different forms. Here, the Horner
    representation is compared with the expanded form of a polynomial:

    >>> eq=x*(1 + x*(2 + x*(3 + x)))
    >>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True)
    -MUL + 3*POW

    The count_ops function also handles iterables:

    >>> count_ops([x, sin(x), None, True, x + 2], visual=False)
    2
    >>> count_ops([x, sin(x), None, True, x + 2], visual=True)
    ADD + SIN
    >>> count_ops({x: sin(x), x + 2: y + 1}, visual=True)
    2*ADD + SIN

    r   )
Relationalr   )Sum)Integral)BooleanFunction)fractionNEGDIVSUBADDEXPZFUNC_c                   s(   g | ] \}}t | d t | d  qS visual	count_opsrI  r  r5   r6   rK     s   

zcount_ops.<locals>.<listcomp>c                   s   g | ]}t | d qS r  r  r   r  r5   r6   rK     s     Tr  )shortzInvalid type of exprc                 s  s"   | ]}t |jpd gd V  qdS )r   r   N)r~   r0   r   r5   r5   r6   r     s     zcount_ops.<locals>.<genexpr>)>Z
relationalr  Zsympy.concrete.summationsr  Zsympy.integrals.integralsr  Zsympy.logic.boolalgr  Zsympy.simplify.radsimpr  r   rm   r   is_RelationalrM  re   r  r   r   rJ   r   r$  r1   r/   r7   r0   ZNegativeOneZas_two_termsr  r   Z	is_MatAddr   r1  rY   is_Powr   baseZExp1r   r   r9   upperr   r4  r   r/  r  r   rW   r%   r  r,   r   ro   r   Z
is_Booleanr  r   r2   r~   r  r  )r  r  r  r  r  r  r  Zopsr0   r  r  r  r   r  r4   r   r  ZaargsZnegsr   r%  r(  r   r5   r  r6   r    s    H





















	






r     c           
        s  ddl m} |dt| |r4| fddS t| tdrt| ttfr|rjfdd|  D }nfd	d|  D }t| trt	| |S | j
| S n$t| tr| j
fd
d| jD  S t	| fdd| D S t| }|jrt|S |jr(|}|jr$t|}n |S |jr4|S |jrZfdd|jD }|j
| S ddlm} |fdd||D }ddlm  s fdd| D }	|t|	}|}s|dd |	D }n|t fdddd }|tfdddd S )aC  Make all Rationals in expr Floats except those in exponents
    (unless the exponents flag is set to True) and those in undefined
    functions. When processing dictionaries, do not modify the keys
    unless ``dkeys=True``.

    Examples
    ========

    >>> from sympy import nfloat, cos, pi, sqrt
    >>> from sympy.abc import x, y
    >>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y))
    x**4 + 0.5*x + sqrt(y) + 1.5
    >>> nfloat(x**4 + sqrt(y), exponent=True)
    x**4.0 + y**0.5

    Container types are not modified:

    >>> type(nfloat((1, 2))) is tuple
    True
    r   )
MatrixBase)r   exponentdkeysc                   s   t | f S rM   nfloat)r)  kwr5   r6   rP     rQ   znfloat.<locals>.<lambda>)excludec                   s"   g | ]}t  fd d|D qS )c                 3  s   | ]}t |f V  qd S rM   r  r   r  r5   r6   r     s     z$nfloat.<locals>.<listcomp>.<genexpr>)rZ   r   r  r5   r6   rK     s   znfloat.<locals>.<listcomp>c                   s    g | ]\}}|t |f fqS r5   r  rI  r  r5   r6   rK     s     c                   s   g | ]}t |f qS r5   r  r   r  r5   r6   rK   
  s     c                   s   g | ]}t |f qS r5   r  r   r  r5   r6   rK     s     c                 3  s   | ]}t |f V  qd S rM   r  r   r  r5   r6   r     s     znfloat.<locals>.<genexpr>)RootOfc                   s   i | ]}||  qS r5   r  )rH   ror  r5   r6   rK  $  s      znfloat.<locals>.<dictcomp>r   Powc                   s   g | ]}| |j t fqS r5   )r
  r  r  r  r5   r6   rK   (  s     c                 S  s   i | ]\}}|j |j qS r5   )r   )rH   rJ   r  r5   r5   r6   rK  ,  s      c                   s    | j t| jS rM   )r
  r   r   r   )r  r   r5   r6   rP   1  rQ   c                 S  s   | j o| jjS rM   )r	  r   r  r   r5   r5   r6   rP   2  rQ   c                   s   | j t| j  S rM   )r   r  r0   r   )r  r   r5   r6   rP   5  rQ   c                 S  s   t | tot | t S rM   )rm   r   r   r   r5   r5   r6   rP   6  rQ   )Zsympy.matrices.matricesr  rm   Z	applyfuncr%   rk   r  r   rW   r   r   r   r0   r   r2   r   r>  r   Zis_Atomr  Zsympy.polys.rootoftoolsr  rx   Zatomspowerr  r   )
r  r   r  r  r  r0   r  Zargs_nfloatr  r  r5   )r  r  r  r   r6   r    s^    







r  )r  rM  )TNTTTTTT)F)T)T)TFF)T)T)T)TF)T)F)r  FF)mrB   
__future__r   typingr   collections.abcr   r  r   r  r   r   cacher	   
containersr
   r   Z
decoratorsr   r   r   r  r   r   Zlogicr   r   r   r   r  r   r  r   r   r   
operationsr   rV   r   rulesr   Z	singletonr   r   r   Zsortingr   r   Zsympy.utilities.exceptionsr    r!   r"   Zsympy.utilities.iterablesr#   r$   r%   r&   r'   r(   Zsympy.utilities.lambdifyr)   Zsympy.utilities.miscr*   r+   r,   r   Zmpmath.libmp.libmpfr-   rT   collectionsr.   r7   	Exceptionr8   rj   r<   ro   r@   rC   r_   r   r`   r   r   r   r?  rP  r   r[  r4  r0  r  r3  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  rM  r5   r5   r5   r6   <module>   s     "~e   9'CO      z !  [F        
  O



 



U

 ]
X