
    wgJ                    	   U 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
 ddlZddlmZ dd	lmZ dd
lmZ ddgiZ ed      Zerkej(                  Zej,                  ZddlmZ i ej6                  ej8                  ej:                  ej<                  ej>                  ej@                  ejB                  ejD                  ejF                  ejH                  ejJ                  ejJ                  ejL                  ejL                  ejN                  ejN                  ejP                  ejP                  ejR                  ejR                  ejT                  ejV                  ejX                  ejX                  ejZ                  ej\                  ej^                  ej^                  ej`                  ejb                  ejd                  ejf                  ejh                  ejh                  i ejj                  ejl                  ejn                  ejn                  ejp                  ejr                  ejt                  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                  j                  j                  d ej                  ej                  ej8                        ej                  ej                  ej<                        ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  dddg      iZk G d de      Zli Zmdend<   ddZoddZp ed      dddddd       Zqy)z
.. deprecated:: 1.8

  ``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
  Aesara. Use ``sympy.printing.aesaracode`` instead. See
  :ref:`theanocode-deprecated` for more information.

    )annotations)Any)import_module)Printer)is_sequenceN)partial)doctest_depends_on)sympy_deprecation_warning)theano_functiontheano)linalgc                 .    t         j                  dd      S Nr      )ttcomplex     ^/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/printing/theanocode.py<lambda>r   I   s    RZZ!_ 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 ZddZ xZS )TheanoPrintera   Code printer which creates Theano 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:`.theano_code` or :func:`.theano_function` means
        the cache is shared between all these applications.

    Attributes
    ==========

    cache : dict
        A cache of Theano 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 Theano 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.
    _theanoc                R    |j                  di       | _        t        |   |i | y )Ncache)popr   super__init__)selfargskwargs	__class__s      r   r   zTheanoPrinter.__init__q   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TheanoPrinter._get_keyu   s+     <66Dd1gqvvum<<r   c                    ||j                   }|d}|d}| j                  ||||      }|| j                  v r| j                  |   S t        j	                  |||      }|| j                  |<   |S )zw
        Get the Theano variable for a SymPy symbol from the cache, or create it
        if it does not exist.
        floatXr   r'   r(   r$   r'   r(   )r$   r)   r   r   tensor)r   r&   r$   r'   r(   keyvalues          r   _get_or_createzTheanoPrinter._get_or_create   s}     <66D=E MmmAt5mN$**::c?"		t5	N

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TheanoPrinter._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-   )strr%   r    r6   r1   )r   r&   r!   r$   r'   r7   s         r   _print_AppliedUndefz!TheanoPrinter._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TheanoPrinter._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TheanoPrinter._print_Number   s    QWWYr   c                l    |j                  di       j                  |      }| j                  ||d      S )Nr3   NNr,   r5   )r   Xr!   r'   s       r   _print_MatrixSymbolz!TheanoPrinter._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 Theano)hasattrr   NotImplementedErrorrP   tolistr@   )r   rM   r!   LrC   s        r   _print_DenseMatrixz TheanoPrinter._print_DenseMatrix   sp    r<(%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TheanoPrinter._print_MatMul   sb    :>))D3KDKK.v.DD!ab\ 	+EVVFE*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 Theano at the moment)r    r@   
isinstanceintranger   rW   rR   )r   rA   r!   rC   rD   rX   is          r   _print_MatPowzTheanoPrinter._print_MatPow   s    :>))D3KDKK.v.DDhqk3'HQK!O8A;' 545
  & '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 TheanoPrinter._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   )blocksshaper^   r@   r   join)	r   rA   r!   nrowsncolsrcrh   rows	            r   _print_BlockMatrixz TheanoPrinter._print_BlockMatrix   s    {{((u "'u/ "'u/ 4;;t{{1a40;F; / / / wwq@?BGGA,,?@@/ / @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TheanoPrinter._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TheanoPrinter._print_Pi   s     r   c                ,    t         j                  d      S )Nr   )tsexpry   s      r   _print_Exp1zTheanoPrinter._print_Exp1   s    vvay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nanru   	Piecewise)	r   rA   r!   npecondp_condp_ep_remainings	            r   _print_PiecewisezTheanoPrinter._print_Piecewise   s    ))A,##4 T,V,dkk!&v& tyy>Q99VS"&&11 "dkk%//499QR="ALVLyyk22r   c                    t         j                   | j                  |j                  fi | | j                  |j                  fi |      S r>   )r   true_divr@   pqry   s      r   _print_RationalzTheanoPrinter._print_Rational   s@    {{;4;;tvv88&4;;tvv88: 	:r   c                    |j                   S r>   )r   ry   s      r   _print_IntegerzTheanoPrinter._print_Integer  s    vvr   c                n     | j                   t        j                  |j                  d   dz         fi |S r   )r@   ru   gammar    ry   s      r   _print_factorialzTheanoPrinter._print_factorial  s.    t{{5;;tyy|a'78CFCCr   c                     | j                   |j                  fi |}|j                  D ]?  } | j                   |fi |}t        j	                  ||t        j                  |            }A |S r>   )r@   rA   	variablesr   Rop	ones_like)r   derivr!   rvvars        r   _print_DerivativezTheanoPrinter._print_Derivative  se    T[[.v.?? 	4C$++c,V,CCc!23B	4 	r   c                    |S r>   r   )r   rA   s     r   emptyPrinterzTheanoPrinter.emptyPrinter  s    r   c                :    |i }|i }| j                  |||      S )a   Convert a SymPy expression to a Theano graph variable.

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

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

        .. __: http://deeplearning.net/software/theano/tutorial/broadcasting.html

        Parameters
        ==========

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

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

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

        Returns
        =======

        theano.gof.graph.Variable
            A variable corresponding to the expression's value in a Theano
            symbolic expression graph.

        )r3   r4   )r@   )r   rA   r3   r4   s       r   doprintzTheanoPrinter.doprint  s/    P >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   rp   rw   rz   r~   r   r   r   r   r   r   r   __classcell__)r"   s   @r   r   r   T   s    4 K*=$.E
P
 O <NM8	*AF
!3":D-Or   r   zdict[Any, Any]global_cachec                    t        ddd       t        st        d      |t        } t	        |i       j
                  | fi |S )aZ  
    Convert a SymPy expression into a Theano graph variable.

    .. deprecated:: 1.8

      ``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
      Aesara. Use ``sympy.printing.aesaracode`` instead. See
      :ref:`theanocode-deprecated` for more information.

    Parameters
    ==========

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

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

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

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

    Returns
    =======

    theano.gof.graph.Variable
        A variable corresponding to the expression's value in a Theano symbolic
        expression graph.

    z
        sympy.printing.theanocode is deprecated. Theano has been renamed to
        Aesara. Use sympy.printing.aesaracode instead.1.8theanocode-deprecateddeprecated_since_versionactive_deprecations_targetz"theano is required for theano_code)r   settings)r
   r   ImportErrorr   r   r   )rA   r   r!   s      r   theano_coder   E  sT    D 	: "'6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:`.theano_code` from
    keyword arguments to :func:`.theano_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:`.TheanoPrinter.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   w  s    > }}VX^44T[[]# 

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

 !I
s   
A-)r   )modulesr   r   r4   c                  t        ddd       t        st        d      |j                  di       }|j                  di       }t	        | |||      }t        t        |||	      }	t        t        |	|             }
t        t        |	|            }|D cg c]3  }t        |t        j                        r|nt        j                  |      5 }}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 )aN  
    Create a Theano function from SymPy expressions.

    .. deprecated:: 1.8

      ``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
      Aesara. Use ``sympy.printing.aesaracode`` instead. See
      :ref:`theanocode-deprecated` for more information.

    The inputs and outputs are converted to Theano variables using
    :func:`.theano_code` and then passed to ``theano.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 Theano function object.

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

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

    broadcastables : dict
        Passed to :meth:`.TheanoPrinter.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.
        ``theano_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
        ``theano.compile.function_module.Function`` or a Python wrapper
        function around one. In both cases, the returned value will have a
        ``theano_function`` attribute which points to the return value of
        ``theano.function``.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> from sympy.printing.theanocode import theano_function

    A simple function with one input and one output:

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

    A function with multiple inputs and one output:

    >>> f2 = theano_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 = theano_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True)
    >>> f3(2, 3)
    [13.0, -5.0]

    See also
    ========

    dim_handling

    zz
        sympy.printing.theanocode is deprecated. Theano has been renamed to Aesara. Use sympy.printing.aesaracode insteadr   r   r   z&theano is required for theano_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 theano_function.<locals>.wrapper.  sM    Dk s9B3HAU1XAbE1,HHr7N Is   ?)r
   r   r   r   r   r   r   listmapr\   Variabler   as_tensor_variabler   functionoutputsvariabler(   anyr   __wrapped__r   )r   r   scalarr   r   r4   r!   r   r3   codetinputstoutputsoutputr   r   r   r   s                  @@r   r   r     sl   @ 	}!&6	8 BCC JJw#EZZ"%F!Cd>N
 ;eF"02D3tV$%GCg&'H pxxek*VV__=2CXCXY_C``xHx
8}A; ??7H77D9=FAS))*a/FE U# GllGO"GN9 y Gs   8E1)E6r>   r   r   )rr   
__future__r   typingr   sympy.externalr   sympy.printing.printerr   sympy.utilities.iterablesr   ru   	functoolsr   sympy.utilities.decoratorr	   sympy.utilities.exceptionsr
   __doctest_requires__r   r   r|   r.   r   theano.sandboxr   tlinalgAddaddMulmulAbsabs_signsgnceilingceilfloorlogr}   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and_Oror_MaxmaximumMinminimum	conjugateconjcorenumbersImaginaryUnitMatAddElemwiseHadamardProductTracetraceDeterminantdetInversematrix_inverse	Transpose
DimShuffler?   r   r   __annotations__r   r   r   r   r   r   <module>r3     s7   #  ( * 1   8 @ -xj9  
x	  
	B	B00IIrvv0IIrvv0 IIrww0 JJ	0
 MM2770 KK0 IIrvv0 IIrvv0 JJ0 IIrvv0 JJ		0 IIrvv0 JJ		0 IIrvv0 JJ		0  KK!0" JJ#0$ KK%0& JJ'0( KK)0* JJ+0, KK-0. HHbgg/00 HHbgg102 IIrxx304 IIrvv506 KK708 NNBJJ90: IIrvv;0< HHbee=0> ##RUU?0@   "%%A0B NNBEEC0D ruuE0F IIrwwHHbffIIrzzIIrzzOORWWJJ,,.DLL"++bff-!!2;;rvv#6KKMM711OOR]]>Aq6B_0GfkOG kO\  "n !/Kd,^ K(StDS )Sr   