
    ga                        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 dd	lmZ dd
lmZ ddlmZ d dlmZ d dlmZmZmZmZ  G d de      Z G d de      Z G d de      Z G d d      Z y)    )annotations)
attrgetter)defaultdict)sympy_deprecation_warning   )_sympifysympify)Basic)cacheit)ordered)	fuzzy_and)global_parameters)sift)
Dispatcher#ambiguity_register_error_ignore_dupstr_signatureRaiseNotImplementedErrorc                       e Zd ZU dZdZded<   dZded<   eddd	d
       Ze	d fd	       Z
dddZe	d        ZddZd Zd Ze	d        Zd Z xZS )AssocOpa   Associative operations, can separate noncommutative and
    commutative parts.

    (a op b) op c == a op (b op c) == a op b op c.

    Base class for Add and Mul.

    This is an abstract base class, concrete derived classes must define
    the attribute `identity`.

    .. deprecated:: 1.7

       Using arguments that aren't subclasses of :class:`~.Expr` in core
       operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
       deprecated. See :ref:`non-expr-args-deprecated` for details.

    Parameters
    ==========

    *args :
        Arguments which are operated

    evaluate : bool, optional
        Evaluate the operation. If not passed, refer to ``global_parameters.evaluate``.
    is_commutativeztuple[str, ...]	__slots__Nztype[Basic] | None
_args_typeT)evaluater   c          	        |rt        t        t        |            }| j                  }|yddlm t        fd|D              rt        d| j                  z        |D ]B  }t        ||      rt        d| j                   dt        |      j                  ddd	d
       D |t        j                  }|s$| j                  |      }| j                  |      }|S |D cg c]  }|| j                   us| }}t#        |      dk(  r| j                   S t#        |      dk(  r|d   S | j%                  |      \  }}	}
|	 }| j                  ||	z   |      }| j                  |      }|
ddlm}  ||g|
 S |S c c}w )Nr   )
Relationalc              3  6   K   | ]  }t        |        y wN)
isinstance).0argr   s     J/var/www/openai/venv/lib/python3.12/site-packages/sympy/core/operations.py	<genexpr>z"AssocOp.__new__.<locals>.<genexpr>?   s     ?$3:c:.$s   zRelational cannot be used in %sz

Using non-Expr arguments in z< is deprecated (in this case, one of
the arguments has type z).

If you really did intend to use a multiplication or addition operation with
this object, use the * or + operator instead.

                        z1.7znon-expr-args-deprecated   )deprecated_since_versionactive_deprecations_target
stacklevelr   )Order)listmap	_sympify_r   
relationalr   any	TypeError__name__r   r   typer   r   
_from_args _exec_constructor_postprocessorsidentitylenflattensympy.series.orderr(   )clsr   r   argstypr!   objac_partnc_partorder_symbolsr   r(   r   s                @r"   __new__zAssocOp.__new__4   s    It,-D nn?.?$?? ACLL PQQ !#s+- \\N +S	**- . 273M#$ " (11H..&C66s;CJ94a1CLL#849t9><<t9>7N),T):&$nnVg-~>2237$0-}--
 :s    E84E8c                    t        |      dk(  r| j                  S t        |      dk(  r|d   S t        |   | g| }|t	        d |D              }||_        |S )zCreate new instance with already-processed args.
        If the args are not in canonical order, then a non-canonical
        result will be returned, so use with caution. The order of
        args may change if the sign of the args is changed.r   r   c              3  4   K   | ]  }|j                     y wr   r   )r    r;   s     r"   r#   z%AssocOp._from_args.<locals>.<genexpr>y   s     &FAq'7'7s   )r4   r3   superr?   r   r   )r7   r8   r   r:   	__class__s       r"   r1   zAssocOp._from_argsl   sd     t9><<Y!^7Ngoc)D)!&&F&FFN+
    )reevalc               d    |r| j                   du rd}n| j                   }| j                  ||      S )a  Create new instance of own class with args exactly as provided by
        caller but returning the self class identity if args is empty.

        Examples
        ========

           This is handy when we want to optimize things, e.g.

               >>> from sympy import Mul, S
               >>> from sympy.abc import x, y
               >>> e = Mul(3, x, y)
               >>> e.args
               (3, x, y)
               >>> Mul(*e.args[1:])
               x*y
               >>> e._new_rawargs(*e.args[1:])  # the same as above, but faster
               x*y

           Note: use this with caution. There is no checking of arguments at
           all. This is best used when you are rebuilding an Add or Mul after
           simply removing one or more args. If, for example, modifications,
           result in extra 1s being inserted they will show up in the result:

               >>> m = (x*y)._new_rawargs(S.One, x); m
               1*x
               >>> m == x
               False
               >>> m.is_Mul
               True

           Another issue to be aware of is that the commutativity of the result
           is based on the commutativity of self. If you are rebuilding the
           terms that came from a commutative object then there will be no
           problem, but if self was non-commutative then what you are
           rebuilding may now be commutative.

           Although this routine tries to do as little as possible with the
           input, getting the commutativity right is important, so this level
           of safety is enforced: commutativity will always be recomputed if
           self is non-commutative and kwarg `reeval=False` has not been
           passed.
        FN)r   r1   )selfrE   r8   kwargsr   s        r"   _new_rawargszAssocOp._new_rawargs}   s6    V d))U2!N!00Nt^44rD   c                    g }|rN|j                         }|j                  | u r|j                  |j                         n|j	                  |       |rN|j                          g |dfS )zReturn seq so that none of the elements are of type `cls`. This is
        the vanilla routine that will be used if a class derived from AssocOp
        does not define its own flatten routine.N)poprC   extendr8   appendreverse)r7   seqnew_seqos       r"   r5   zAssocOp.flatten   s_     	A{{c!

166"q!  	 7D  rD   c                x   ddl m} ddlm} t	        | |      rt	        |      sy|i }| k(  r|S | j                  |      }||S ddl m ddlm t        | j                  fdd	      \  }}|s/t        t        |            }| j                  rt        |d
       }n | j                  | }	j                   }
|
r|	j                   |
z
  ry| j#                  |	      }|sGj                  sj$                  r/|} ||      r| }|j'                         j'                         kD  ry | j                  | }|j)                  ||      S d}t+               }|vrZ|j-                         t/        t        | j1                                    }| j                  r#j                  rt/        t        |d             }| j2                  f|z   }t5        |      D ]P  }t5        |      D ]@  }|j)                  ||      }|| j7                  |      j)                  |      }|<|c c S  R |dk(  r}| j$                  rj8                  rbj:                  j<                  rKddlm } j:                  dkD  r/ |jB                  jB                  j:                  dz
  z  gddin1 |djB                  z  jB                  j:                  dz   z  gddi|dz  }| j                  rÉjE                         \  }}tG        |      dkD  r4ddlm$} |dkD  r |||dz
  |z  gddin || |dz   |z  gddi|dz  }ddl%m&} }t+               }t5        |      D ]B  }|jO                        \  }}|j                   |z
  }
|
s)|jQ                  |
        ||
      D |k7  r|dz  }W	 y|vrZy)a^  
        Matches Add/Mul "pattern" to an expression "expr".

        repl_dict ... a dictionary of (wild: expression) pairs, that get
                      returned with the results

        This function is the main workhorse for Add/Mul.

        Examples
        ========

        >>> from sympy import symbols, Wild, sin
        >>> a = Wild("a")
        >>> b = Wild("b")
        >>> c = Wild("c")
        >>> x, y, z = symbols("x y z")
        >>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z)
        {a_: x, b_: y, c_: z}

        In the example above, "a+sin(b)*c" is the pattern, and "x+sin(y)*z" is
        the expression.

        The repl_dict contains parts that were already matched. For example
        here:

        >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x})
        {a_: x, b_: y, c_: z}

        the only function of the repl_dict is to return it in the
        result, e.g. if you omit it:

        >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z)
        {b_: y, c_: z}

        the "a: x" is not returned in the result, but otherwise it is
        equivalent.

        r   )_coeff_isneg)ExprN)WildFunction)Wildc                P    | j                        xr j                  |        S r   )has)prV   rU   exprs    r"   <lambda>z.AssocOp._matches_commutative.<locals>.<lambda>   s#    EE$%9dhhqk/9rD   Tbinaryc                n    | j                   r(| j                  d   j                  r| j                  d   S dS Nr   is_Mulr8   	is_Numberxs    r"   r[   z.AssocOp._matches_commutative.<locals>.<lambda>  0    !"affQi.A.AAFF1I rD   )keyr   c                n    | j                   r(| j                  d   j                  r| j                  d   S dS r_   r`   rc   s    r"   r[   z.AssocOp._matches_commutative.<locals>.<lambda>#  re   rD   Mulr   FAdd)collect))functionrS   rZ   rT   r   _matches_simplerU   symbolrV   r   r8   r)   r   is_AddsortedrI   free_symbols_combine_inversera   	count_opsmatchessetaddtuple	make_argsr3   reversedxreplaceis_Powexp
is_Integermulri   baseas_coeff_Mulabsrk   sympy.simplify.radsimprl   as_coeff_mulupdate)rG   rZ   	repl_dictoldrS   rT   d	wild_part
exact_partexactfreenewexprcheck
newpatternisawr8   	expr_listlast_opwd1d2ri   cerk   rl   wasdidrV   rU   s    `                           @@r"   _matches_commutativezAssocOp._matches_commutative   s   N 	+dD!*T4*@I 4<  y1=H 	+  $TYY 1:!	: WY/0I{{ #9 3 	 &D%%z2E$$D++d2 ++D%8GDKK4;;&"FE??$t~~'77***I6J%%gy99 e#oGGDM!567D{{t{{ VD /   (4/I#I.!),A7I6B~!]]2.66tR@>#%I - / Av;;{{txx':':,88a<#&DII14M(N#_Y^#_D#&499dii$((Q,6O(P#a[`#aDQ [[,,.DAq1vz,q5#&QUAI#G#GD#&!a!eQY#H%#HDQ  ?C%C%i0 ~~d31 ~~3JJt,#*4#6D 1 s{Q w #ov 	rD   c                V     d         \   j                    fd}|S )zHelper for .has() that checks for containment of
        subexpressions within an expr by using sets of args
        of similar nodes, e.g. x + 1 in x + y + 1 checks
        to see that {x, 1} & {x, y, 1} == {x, 1}
        c                T    t        | j                  d d      \  }}t        |      |fS )Nc                    | j                   du S )NTr   )r!   s    r"   r[   z8AssocOp._has_matcher.<locals>._ncsplit.<locals>.<lambda>d  s    C..$6rD   Tr\   )r   r8   rv   )rZ   cpartncparts      r"   _ncsplitz&AssocOp._has_matcher.<locals>._ncsplit_  s-     !6tEME6u:v%%rD   c                    t        |       rq| k(  ry |       \  }}|z  k(  rXsyt              t        |      k  r>t        t        |      t              z
  dz         D ]  }|||t              z    k(  s y y)NTr   F)r   r4   range)	rZ   _c_ncr   r   r   r7   ncrG   s	       r"   is_inz#AssocOp._has_matcher.<locals>.is_inj  s    $$4<"4.CFq=#RCH,!&s3x#b''9A'=!>A"1QR[1R7'+ "? rD   rC   )rG   r   r   r   r7   r   s   ` @@@@r"   _has_matcherzAssocOp._has_matcherY  s1    	& 2nn	 	 rD   c                   ddl m} ddlm} ddlm} ddlm} t        | ||f      r| j                  ||      \  }}|| j                  u st        |t              r|j                  s|| j                  u rt        |t              s|| j                  ur|j                  |      n| j                  }g }t        | j                  j!                  |            }	|	D ]8  }
|
j#                  |      }||j%                  |
       (|j%                  |       :  | j                  |g| S g }| j&                  D ]8  }
|
j#                  |      }||j%                  |
       (|j%                  |       :  | j                  | S )ab  
        Evaluate the parts of self that are numbers; if the whole thing
        was a number with no functions it would have been evaluated, but
        it wasn't so we must judiciously extract the numbers and reconstruct
        the object. This is *not* simply replacing numbers with evaluated
        numbers. Numbers should be handled in the largest pure-number
        expression as possible. So the code below separates ``self`` into
        number and non-number parts and evaluates the number parts and
        walks the args of the non-number part recursively (doing the same
        thing).
        r   rj   rh   )Symbol)AppliedUndef)rw   rk   r   ri   ro   r   rm   r   r   as_independentr3   r   is_Function_evalfrx   funcry   _eval_evalfrM   r8   )rG   precrk   ri   r   r   rd   tailr8   	tail_argsr;   newas               r"   r   zAssocOp._eval_evalfy  sE    	"*dS#J'))&,?GAt DMM)q'*q}}&:dG+D '(t}}&<AHHTN$--!$))"5"5d";<	"A
 ==.D|AD) # !tyy*T** A==&D|AD!  tyy$rD   c                J    t        ||       r|j                  S t        |      fS )ao  
        Return a sequence of elements `args` such that cls(*args) == expr

        Examples
        ========

        >>> from sympy import Symbol, Mul, Add
        >>> x, y = map(Symbol, 'xy')

        >>> Mul.make_args(x*y)
        (x, y)
        >>> Add.make_args(x*y)
        (x*y,)
        >>> set(Add.make_args(x*y + y)) == set([y, x*y])
        True

        )r   r8   r	   r7   rZ   s     r"   ry   zAssocOp.make_args  s%    & dC 99DM##rD   c                    |j                  dd      r*| j                  D cg c]  } |j                  di | }}n| j                  } | j                  |ddiS c c}w )NdeepTr    )getr8   doitr   )rG   hintstermtermss       r"   r   zAssocOp.doit  sZ    99VT"48II>IDYTYY''IE>IIEtyy%/$// ?s   Ar   )NF)r/   
__module____qualname____doc__r   __annotations__r   r   r?   classmethodr1   rI   r5   r   r   r   ry   r   __classcell__r   s   @r"   r   r      s    8 "5I4%)J")%)D 5 5n    *. /5b ! !"Wr@2 h $ $.0rD   r   c                      e Zd Zy)ShortCircuitN)r/   r   r   r   rD   r"   r   r     s    rD   r   c                  H     e Zd ZdZdZ fdZedd       Zed        Z xZ	S )	LatticeOpa?  
    Join/meet operations of an algebraic lattice[1].

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

    These binary operations are associative (op(op(a, b), c) = op(a, op(b, c))),
    commutative (op(a, b) = op(b, a)) and idempotent (op(a, a) = op(a) = a).
    Common examples are AND, OR, Union, Intersection, max or min. They have an
    identity element (op(identity, a) = a) and an absorbing element
    conventionally called zero (op(zero, a) = zero).

    This is an abstract base class, concrete derived classes must declare
    attributes zero and identity. All defining properties are then respected.

    Examples
    ========

    >>> from sympy import Integer
    >>> from sympy.core.operations import LatticeOp
    >>> class my_join(LatticeOp):
    ...     zero = Integer(0)
    ...     identity = Integer(1)
    >>> my_join(2, 3) == my_join(3, 2)
    True
    >>> my_join(2, my_join(3, 4)) == my_join(2, 3, 4)
    True
    >>> my_join(0, 1, 4, 2, 3, 4)
    0
    >>> my_join(1, 2)
    2

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Lattice_%28order%29
    Tc                \   d |D        }	 t        | j                  |            }|st        | j
                        S t        |      dk(  rt        |      j                         S t        t        | .  | gt        |       }||_        |S # t        $ r t        | j                        cY S w xY w)Nc              3  2   K   | ]  }t        |        y wr   )r+   )r    r!   s     r"   r#   z$LatticeOp.__new__.<locals>.<genexpr>  s     /$3	#$s   r   )	frozenset_new_args_filterr   r	   zeror3   r4   rv   rK   rB   r   r?   r   _argset)r7   r8   options_argsr:   rC   s        r"   r?   zLatticeOp.__new__  s    /$/	%
 c22489E 3<<((Z1_u:>>## -cCGENCCCKJ  	%388$$	%s   B
 
B+*B+c              #     K   |xs | }|D ]T  }||j                   k(  rt        |      ||j                  k(  r-|j                  |k(  r|j                  E d{    Q| V y7 w)zGenerator filtering argsN)r   r   r3   r   r8   )r7   arg_sequencecall_clsnclsr!   s        r"   r   zLatticeOp._new_args_filter  sd      3Cdii"3''%T!88##	   $s   AA%A#A%c                \    t        ||       r|j                  S t        t        |      g      S )zG
        Return a set of args such that cls(*arg_set) == expr.
        )r   r   r   r	   r   s     r"   ry   zLatticeOp.make_args  s)    
 dC <<gdm_--rD   r   )
r/   r   r   r   r   r?   r   r   ry   r   r   s   @r"   r   r     s=    $L N,   . .rD   r   c                  ^    e Zd ZdZddZd ZefdZeddd       Z	ed	        Z
ed
        Zy)AssocOpDispatchera  
    Handler dispatcher for associative operators

    .. notes::
       This approach is experimental, and can be replaced or deleted in the future.
       See https://github.com/sympy/sympy/pull/19463.

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

    If arguments of different types are passed, the classes which handle the operation for each type
    are collected. Then, a class which performs the operation is selected by recursive binary dispatching.
    Dispatching relation can be registered by ``register_handlerclass`` method.

    Priority registration is unordered. You cannot make ``A*B`` and ``B*A`` refer to
    different handler classes. All logic dealing with the order of arguments must be implemented
    in the handler class.

    Examples
    ========

    >>> from sympy import Add, Expr, Symbol
    >>> from sympy.core.add import add

    >>> class NewExpr(Expr):
    ...     @property
    ...     def _add_handler(self):
    ...         return NewAdd
    >>> class NewAdd(NewExpr, Add):
    ...     pass
    >>> add.register_handlerclass((Add, NewAdd), NewAdd)

    >>> a, b = Symbol('a'), NewExpr()
    >>> add(a, b) == NewAdd(a, b)
    True

    Nc                    || _         || _        d|z  | _        t        | j                        | _        t        |      | _        y )Nz_%s_handler)namedochandlerattrr   _handlergetterr   _dispatcher)rG   r   r   s      r"   __init__zAssocOpDispatcher.__init__N  s=    	(4/()9)9:%d+rD   c                     d| j                   z  S )Nz<dispatched %s>)r   )rG   s    r"   __repr__zAssocOpDispatcher.__repr__U  s     499,,rD   c                r   t        |      dk(  s$t        dt        |      dt        |      d      t        t        |            dk(  rt        dt        |      z        | j                  j                  t        |      ||       | j                  j                  t        t        |            ||       y)	a  
        Register the handler class for two classes, in both straight and reversed order.

        Paramteters
        ===========

        classes : tuple of two types
            Classes who are compared with each other.

        typ:
            Class which is registered to represent *cls1* and *cls2*.
            Handler method of *self* must be implemented in this class.
           z+Only binary dispatch is supported, but got z	 types: <z>.r   z*Duplicate types <%s> cannot be dispatched.)on_ambiguityN)r4   RuntimeErrorr   rv   r   rw   rx   rz   )rG   classesr9   r   s       r"   register_handlerclassz'AssocOpDispatcher.register_handlerclassX  s     7|q GmG4  s7|!<}W?UU  	U7^S|LU8G#45sVrD   T)r   c                   |rt        t        t        |            }t        t        | j                  |            } | j                  |      |ddi|S )zi
        Parameters
        ==========

        *args :
            Arguments which are operated
        r   F)rx   r*   r+   r   r   dispatch)rG   r   r8   rH   handlerss        r"   __call__zAssocOpDispatcher.__call__r  sQ     Y-.DS!4!4d;< 't}}X&GuGGGrD   c                   t        |      dk(  r0|\  }t        |t              st        dj	                  |            |S t        |      D ]  \  }}t        |t              st        dj	                  |            |dk(  r|}8}| j                  j                  ||      }t        |t              rgt        dj	                  |||             S )zJ
        Select the handler class, and return its handler method.
        r   zHandler {!r} is not a type.r   z=Dispatcher for {!r} and {!r} must return a type, but got {!r})r4   r   r0   r   format	enumerater   r   )rG   r   hr   r9   handlerprev_handlers          r"   r   zAssocOpDispatcher.dispatch  s     x=ABAa&"#@#G#G#JKKH  )FAsc4("#@#G#G#LMMAv&**33L#F!'40&W^^$c7  *$ rD   c                @   d| j                   z  dg}| j                  r|j                  | j                         d}|dt        |      z  z  }|j                  |       g }t	        t
              }| j                  j                  d d d   D ]/  }| j                  j                  |   }||   j                  |       1 |j                         D ]x  \  }}dj                  d |D              }t        |t              r|j                  |       @d|z  }|d	t        |      z  d
z   z  }||j                  z  }|j                  |       z |rFd}|dt        |      z  z  }|j                  |       d
j                  |      }|j                  |       dj                  |      S )Nz,Multiply dispatched associative operator: %szcNote that support for this is experimental, see the docs for :class:`AssocOpDispatcher` for detailszRegistered handler classes
=z, c              3  8   K   | ]  }d t        |      z    yw)z<%s>N)r   )r    sigs     r"   r#   z,AssocOpDispatcher.__doc__.<locals>.<genexpr>  s      M-*<!<s   zInputs: %s
-
zAmbiguous handler classes
z

)r   r   rM   r4   r   r)   r   orderingfuncsitemsjoinr   r   r/   )	rG   docssamb_sigstyp_sigssigsrf   r9   sigs_strs	            r"   r   zAssocOpDispatcher.__doc__  sy    ;TYYFq

 88KK!*	S3q6\At$$$--dd3D""((.CSM  & 4 ")ICyy M MMH#78))As1v$$AAKKN * -As1vAKKN		(#AKKN{{4  rD   r   )r/   r   r   r   r   r   r   r   r   r   r   propertyr   rD   r"   r   r   (  sa    $J,- @c W4 '+ H H  B )! )!rD   r   N)!
__future__r   operatorr   collectionsr   sympy.utilities.exceptionsr   r	   r   r+   basicr
   cacher   sortingr   logicr   
parametersr   sympy.utilities.iterablesr   !sympy.multipledispatch.dispatcherr   r   r   r   r   	Exceptionr   r   r   r   rD   r"   <module>r     sf    "  # @ 3     ) *- -
w0e w0r	9 	U. U.pf! f!rD   