
    wg=G              !      	   U 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
Z
d dlmZ  ed      Zerej                  Zej                   Zd d	lmZ d d
lmZ d dlmZ  eedd      Zeej2                  Zi e
j4                  ej6                  e
j8                  ej:                  e
j<                  ej>                  e
j@                  ejB                  e
jD                  ejF                  e
jH                  ejH                  e
jJ                  ejJ                  e
jL                  ejL                  e
jN                  ejN                  e
jP                  ejP                  e
jR                  ejT                  e
jV                  ejV                  e
jX                  ejZ                  e
j\                  ej\                  e
j^                  ej`                  e
jb                  ejd                  e
jf                  ejf                  i e
jh                  ejj                  e
jl                  ejl                  e
jn                  ejp                  e
jr                  ejr                  e
jt                  ejv                  e
jx                  ejz                  e
j|                  ej~                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  j                  j                  d e
j                   eej6                        e
j                   eej:                        e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                   eddd g      iZl G d de      Zmi Zndeod<   ddZpddZqddddddZry)    )annotations)Any)import_module)Printer)is_sequenceN)partialaesara)nlinalg)Elemwise)
DimShuffletrue_dividec                 .    t         j                  dd      S Nr      )aetcomplex     ^/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/printing/aesaracode.py<lambda>r   E   s    S[[15E r   )FFr   c                       e Zd ZdZdZ fdZddZddZd Zd Z	d Z
d	 Zd
 Zd ZexZZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZddZ xZS )AesaraPrintera   Code printer which creates Aesara symbolic expression graphs.

    Parameters
    ==========

    cache : dict
        Cache dictionary to use. If None (default) will use
        the global cache. To create a printer which does not depend on or alter
        global state pass an empty dictionary. Note: the dictionary is not
        copied on initialization of the printer and will be updated in-place,
        so using the same dict object when creating multiple printers or making
        multiple calls to :func:`.aesara_code` or :func:`.aesara_function` means
        the cache is shared between all these applications.

    Attributes
    ==========

    cache : dict
        A cache of Aesara variables which have been created for SymPy
        symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or
        :class:`sympy.matrices.expressions.MatrixSymbol`). This is used to
        ensure that all references to a given symbol in an expression (or
        multiple expressions) are printed as the same Aesara variable, which is
        created only once. Symbols are differentiated only by name and type. The
        format of the cache's contents should be considered opaque to the user.
    _aesarac                R    |j                  di       | _        t        |   |i | y )Ncache)popr   super__init__)selfargskwargs	__class__s      r   r   zAesaraPrinter.__init__m   s'    ZZ,
$)&)r   c                R    ||j                   }|t        |      |j                  ||fS )z Get the cache key for a SymPy object.

        Parameters
        ==========

        s : sympy.core.basic.Basic
            SymPy object to get key for.

        name : str
            Name of object, if it does not have a ``name`` attribute.
        )nametyper    )r   sr$   dtypebroadcastables        r   _get_keyzAesaraPrinter._get_keyq   s+     <66Dd1gqvvum<<r   c                    ||j                   }|d}|d}| j                  ||||      }|| j                  v r| j                  |   S t        j	                  |||      }|| j                  |<   |S )zw
        Get the Aesara variable for a SymPy symbol from the cache, or create it
        if it does not exist.
        floatXr   r'   r(   )r$   r'   shape)r$   r)   r   r   tensor)r   r&   r$   r'   r(   keyvalues          r   _get_or_createzAesaraPrinter._get_or_create   s}     <66D=E MmmAt5mN$**::c?"

E
G

3r   c                    |j                  di       j                  |      }|j                  di       j                  |      }| j                  |||      S )Ndtypesbroadcastablesr,   getr1   )r   r&   r!   r'   bcs        r   _print_SymbolzAesaraPrinter._print_Symbol   sQ    

8R(,,Q/ZZ("-11!4""1E"DDr   c                   t        t        |            dz   t        |j                  d         z   }|j                  di       j                  |      }|j                  di       j                  |      }| j	                  ||||      S )N_r   r3   r4   )r$   r'   r(   )strr%   r    r6   r1   )r   r&   r!   r$   r'   r7   s         r   _print_AppliedUndefz!AesaraPrinter._print_AppliedUndef   sv    47|c!Cq	N2

8R(,,Q/ZZ("-11!4""14uB"OOr   c                    t         t        |         }|j                  D cg c]  } | j                  |fi | }} || S c c}w N)mappingr%   r    _print)r   exprr!   opargchildrens         r   _print_BasiczAesaraPrinter._print_Basic   sG    T$Z :>))D3KDKK.v.DD8} Es   Ac                4    t        |j                               S r>   )floatevalf)r   nr!   s      r   _print_NumberzAesaraPrinter._print_Number   s    QWWYr   c                l    |j                  di       j                  |      }| j                  ||d      S )Nr3   NNr,   r5   )r   Xr!   r'   s       r   _print_MatrixSymbolz!AesaraPrinter._print_MatrixSymbol   s5    

8R(,,Q/""1E"NNr   c                    t        t        d      st        d      t        j                  |j	                         D cg c]#  }|D cg c]  } | j
                  |fi | c}% c}}      S c c}w c c}}w )N
stacklistsz>Matrix translation not yet supported in this version of Aesara)hasattrr   NotImplementedErrorrP   tolistr@   )r   rM   r!   LrC   s        r   _print_DenseMatrixz AesaraPrinter._print_DenseMatrix   sp    sL)%OQ Q ~~XXZ
 455C[T[[''5
  	5
s   	A3
A.!A3
.A3
c                    |j                   D cg c]  } | j                  |fi | }}|d   }|dd  D ]  }t        j                  ||      } |S c c}w r   )r    r@   r   dot)r   rA   r!   rC   rD   resultchilds          r   _print_MatMulzAesaraPrinter._print_MatMul   sb    :>))D3KDKK.v.DD!ab\ 	,EWWVU+F	,	 Es   Ac                   |j                   D cg c]  } | j                  |fi | }}d}t        |d   t              r6|d   dkD  r.t	        |d         D ]  }t
        j                  ||d         } |S t        d      c c}w )Nr   r   z^Only non-negative integer
           powers of matrices can be handled by Aesara at the moment)r    r@   
isinstanceintranger   rW   rR   )r   rA   r!   rC   rD   rX   is          r   _print_MatPowzAesaraPrinter._print_MatPow   s    :>))D3KDKK.v.DDhqk3'HQK!O8A;' 6!56
  & 'H I I Es   Bc                     | j                   |j                  fi |} | j                   t        |j                   fi |} | j                   t        |j                   fi |}|||f   S r>   )r@   parentslicerowslicecolslice)r   rA   r!   rb   rd   re   s         r   _print_MatrixSlicez AesaraPrinter._print_MatrixSlice   sg    T[[3F34;;udmm4??4;;udmm4??h())r   c                f   |j                   j                  \  }}t        |      D cg c];  }t        |      D cg c]$  } | j                  |j                   ||f   fi |& c}= }}}t	        j
                  dg|D cg c]  }t	        j
                  dg|  c} S c c}w c c}}w c c}w r   )blocksr-   r^   r@   r   join)	r   rA   r!   nrowsncolsrcrh   rows	            r   _print_BlockMatrixz AesaraPrinter._print_BlockMatrix   s    {{((u "'u/ "'u/ 4;;t{{1a40;F; / / / xxB&A3SXXa.#.ABB/ / Bs   B()B##B( B.
#B(c           
         t        |j                  |j                  |j                  fD cg c]1  }t	        |t
        j                        r | j                  |fi |n|3 c} S c c}w r>   )rc   startstopstepr\   sympyBasicr@   )r   rA   r!   r_   s       r   _print_slicezAesaraPrinter._print_slice   sj    "&**dii!CE &a5 #t{{1//;<= E F 	F Es   6A%c                     y)Ng-DT!	@r   r   rA   r!   s      r   	_print_PizAesaraPrinter._print_Pi   s     r   c                   dd l }|j                  d   j                  \  }} | j                  |fi |} | j                  |fi |}t        |j                        dk(  r!t        j                  |||j                        S  | j                  t        j                  |j                  dd   fi |}t        j                  |||      S r   )	numpyr    r@   lenr   switchnanrt   	Piecewise)	r   rA   r!   npecondp_condp_ep_remainings	            r   _print_PiecewisezAesaraPrinter._print_Piecewise   s    ))A,##4 T,V,dkk!&v& tyy>Q::fc26622 "dkk%//499QR="ALVLzz&#{33r   c                    t         | j                  |j                  fi | | j                  |j                  fi |      S r>   )r   r@   pqrx   s      r   _print_RationalzAesaraPrinter._print_Rational   s<    ;4;;tvv88&4;;tvv88: 	:r   c                    |j                   S r>   )r   rx   s      r   _print_IntegerzAesaraPrinter._print_Integer   s    vvr   c                n     | j                   t        j                  |j                  d   dz         fi |S r   )r@   rt   gammar    rx   s      r   _print_factorialzAesaraPrinter._print_factorial   s.    t{{5;;tyy|a'78CFCCr   c                    ddl m}  | j                  |j                  fi |}|j                  D ]2  } | j                  |fi |} |||t
        j                  |            }4 |S )Nr   )Rop)aesara.gradientr   r@   rA   	variablesr   	ones_like)r   derivr!   r   rvvars         r   _print_DerivativezAesaraPrinter._print_Derivative  sd    'T[[.v.?? 	2C$++c,V,CRcmmC01B	2 	r   c                    |S r>   r   )r   rA   s     r   emptyPrinterzAesaraPrinter.emptyPrinter
  s    r   c                :    |i }|i }| j                  |||      S )a9   Convert a SymPy expression to a Aesara graph variable.

        The ``dtypes`` and ``broadcastables`` arguments are used to specify the
        data type, dimension, and broadcasting behavior of the Aesara variables
        corresponding to the free symbols in ``expr``. Each is a mapping from
        SymPy symbols to the value of the corresponding argument to
        ``aesara.tensor.var.TensorVariable``.

        See the corresponding `documentation page`__ for more information on
        broadcasting in Aesara.


        .. __: https://aesara.readthedocs.io/en/latest/reference/tensor/shapes.html#broadcasting

        Parameters
        ==========

        expr : sympy.core.expr.Expr
            SymPy expression to print.

        dtypes : dict
            Mapping from SymPy symbols to Aesara datatypes to use when creating
            new Aesara variables for those symbols. Corresponds to the ``dtype``
            argument to ``aesara.tensor.var.TensorVariable``. Defaults to ``'floatX'``
            for symbols not included in the mapping.

        broadcastables : dict
            Mapping from SymPy symbols to the value of the ``broadcastable``
            argument to ``aesara.tensor.var.TensorVariable`` to use when creating Aesara
            variables for those symbols. Defaults to the empty tuple for symbols
            not included in the mapping (resulting in a scalar).

        Returns
        =======

        aesara.graph.basic.Variable
            A variable corresponding to the expression's value in a Aesara
            symbolic expression graph.

        )r3   r4   )r@   )r   rA   r3   r4   s       r   doprintzAesaraPrinter.doprint  s/    R >F!N{{4~{NNr   NNNrL   )__name__
__module____qualname____doc__printmethodr   r)   r1   r8   r<   rE   rJ   rN   rU   _print_ImmutableMatrix_print_ImmutableDenseMatrixrZ   r`   rf   ro   rv   ry   r   r   r   r   r   r   r   __classcell__)r"   s   @r   r   r   P   s    4 K*=$.E
P
 O <NM8	*CF
!4":D.Or   r   zdict[Any, Any]global_cachec                p    t         st        d      |t        } t        |i       j                  | fi |S )a~  
    Convert a SymPy expression into a Aesara graph variable.

    Parameters
    ==========

    expr : sympy.core.expr.Expr
        SymPy expression object to convert.

    cache : dict
        Cached Aesara variables (see :class:`AesaraPrinter.cache
        <AesaraPrinter>`). Defaults to the module-level global cache.

    dtypes : dict
        Passed to :meth:`.AesaraPrinter.doprint`.

    broadcastables : dict
        Passed to :meth:`.AesaraPrinter.doprint`.

    Returns
    =======

    aesara.graph.basic.Variable
        A variable corresponding to the expression's value in a Aesara symbolic
        expression graph.

    z"aesara is required for aesara_code)r   settings)r	   ImportErrorr   r   r   )rA   r   r!   s      r   aesara_coder   A  s<    8 >??}:=ur2::4J6JJr   c           	         |t         j                  | d|z        S |It        |j                               }|j	                         D ci c]  \  }}|d|z  d||z
  z  z    c}}S ||S i S c c}}w )a6  
    Get value of ``broadcastables`` argument to :func:`.aesara_code` from
    keyword arguments to :func:`.aesara_function`.

    Included for backwards compatibility.

    Parameters
    ==========

    inputs
        Sequence of input symbols.

    dim : int
        Common number of dimensions for all inputs. Overrides other arguments
        if given.

    dims : dict
        Mapping from input symbols to number of dimensions. Overrides
        ``broadcastables`` argument if given.

    broadcastables : dict
        Explicit value of ``broadcastables`` argument to
        :meth:`.AesaraPrinter.doprint`. If not None function will return this value unchanged.

    Returns
    =======
    dict
        Dictionary mapping elements of ``inputs`` to their "broadcastable"
        values (tuple of ``bool``\ s).
    F)T)dictfromkeysmaxvaluesitems)inputsdimdimsr4   maxdimr&   ds          r   dim_handlingr   f  s    > }}VX^44T[[]# 


1 x!|g!444
 	

 !I
s   
A-r   r   r4   c                  t         st        d      |j                  di       }|j                  di       }t        | |||      }t	        t
        |||      }	t        t        |	|             }
t        t        |	|            }|D cg c]G  }t        |t         j                  j                  j                        r|nt        j                  |      I }}t        |      dk(  r|d   }t        j                  |
|fi |j                   D cg c]$  }t        |j"                  j$                        dk(  & c}|rt'              s	_        S fd}|_        j,                  |_        |_        |S c c}w c c}w )	ao  
    Create a Aesara function from SymPy expressions.

    The inputs and outputs are converted to Aesara variables using
    :func:`.aesara_code` and then passed to ``aesara.function``.

    Parameters
    ==========

    inputs
        Sequence of symbols which constitute the inputs of the function.

    outputs
        Sequence of expressions which constitute the outputs(s) of the
        function. The free symbols of each expression must be a subset of
        ``inputs``.

    scalar : bool
        Convert 0-dimensional arrays in output to scalars. This will return a
        Python wrapper function around the Aesara function object.

    cache : dict
        Cached Aesara variables (see :class:`AesaraPrinter.cache
        <AesaraPrinter>`). Defaults to the module-level global cache.

    dtypes : dict
        Passed to :meth:`.AesaraPrinter.doprint`.

    broadcastables : dict
        Passed to :meth:`.AesaraPrinter.doprint`.

    dims : dict
        Alternative to ``broadcastables`` argument. Mapping from elements of
        ``inputs`` to integers indicating the dimension of their associated
        arrays/tensors. Overrides ``broadcastables`` argument if given.

    dim : int
        Another alternative to the ``broadcastables`` argument. Common number of
        dimensions to use for all arrays/tensors.
        ``aesara_function([x, y], [...], dim=2)`` is equivalent to using
        ``broadcastables={x: (False, False), y: (False, False)}``.

    Returns
    =======
    callable
        A callable object which takes values of ``inputs`` as positional
        arguments and returns an output array for each of the expressions
        in ``outputs``. If ``outputs`` is a single expression the function will
        return a Numpy array, if it is a list of multiple expressions the
        function will return a list of arrays. See description of the ``squeeze``
        argument above for the behavior when a single output is passed in a list.
        The returned object will either be an instance of
        ``aesara.compile.function.types.Function`` or a Python wrapper
        function around one. In both cases, the returned value will have a
        ``aesara_function`` attribute which points to the return value of
        ``aesara.function``.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> from sympy.printing.aesaracode import aesara_function

    A simple function with one input and one output:

    >>> f1 = aesara_function([x], [x**2 - 1], scalar=True)
    >>> f1(3)
    8.0

    A function with multiple inputs and one output:

    >>> f2 = aesara_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True)
    >>> f2(3, 4, 2)
    5.0

    A function with multiple inputs and multiple outputs:

    >>> f3 = aesara_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True)
    >>> f3(2, 3)
    [13.0, -5.0]

    See also
    ========

    dim_handling

    z&Aesara is required for aesara_functionr   r3   r   )r   r3   r4   r   r   c                      |  }t        |      r(t        |      D cg c]  \  }}|   r|d   n| c}}S |d   S c c}}w )Nr   )r   	enumerate)r    outr_   ofuncis_0ds       r   wrapperz aesara_function.<locals>.wrapper  sM    Dk s9B3HAU1XAbE1,HHr7N Is   ?)r	   r   r   r   r   r   listmapr\   graphbasicVariabler   as_tensor_variabler|   functionoutputsvariabler(   anyaesara_function__wrapped__r   )r   r   scalarr   r   r4   r!   r   r3   codetinputstoutputsoutputr   r   r   r   s                  @@r   r   r     sk   r BCC JJw#EZZ"%F!Cd>N
 ;eF"02D3tV$%GCg&'H }E  Frx*VV\\-?-?-H-HIsOeOeflOmm  FH  F
8}A; ??7H77D9=FAS))*a/FE U# GllGO"GN9 F Gs   AE7)E<r>   r   r   )s
__future__r   typingr   sympy.externalr   sympy.printing.printerr   sympy.utilities.iterablesr   rt   	functoolsr   r	   r   aesr.   r   aesara.tensorr
   aesara.tensor.elemwiser   r   getattrr   true_divAddaddMulmulAbsabssignsgnceilingceilfloorlogexpsqrtcosacosarccossinasinarcsintanatanarctanatan2arctan2coshacosharccoshsinhasinharcsinhtanhatanharctanhrerealimimagrC   angleerfr   loggammagammalnPowpowEqeqStrictGreaterThangtStrictLessThanltLessThanleGreaterThangeAndbitwise_andOr
bitwise_orNotinvertXorbitwise_xorMaxmaximumMinminimum	conjugateconjcorenumbersImaginaryUnitMatAddHadamardProductTracetraceDeterminantdetInversematrix_inverse	Transposer?   r   r   __annotations__r   r   r   r   r   r   <module>r.     s7   "  ( * 1   
x	 	
--C
--C%/1
 #}d3Kll2IIsww2IIsww2 IIsww2 JJ	2
 MM3882 KK2 IIsww2 IIsww2 JJ2 IIsww2 JJ

2 IIsww2 JJ

2 IIsww2 JJ

2  KK!2" JJ#2$ KK%2& JJ'2( KK)2* JJ+2, KK-2. HHchh/20 HHchh122 IIsyy324 IIsww526 KK728 NNCKK92: IIsww;2< HHcff=2> ##SVV?2@   #&&A2B NNCFFC2D svvE2F IIsHHcnnIIszzIIsIIs{{IIs{{OOSXXJJ,,.ELL(377+!!8CGG#4KKMM711OOZA?c2GjkOG kO\  "n !"KJ,^GtDGr   