o
    Ei/                     @   s  d dl Z ddlmZ d dlZd dlmZ d dlmZm	Z	 d dl
mZ eZe jdd ddEd	d
Ze jdFddZe jje jdd d			dGdede jde	eef de	edf de	e jedf dedejde jfddZee_e jj			dGdede jde	edf de	e jedf dedejde jfddZdd Ze jj			dGdede jde	edf de	e jedf dedejde jfddZdd  Ze jj			dGdede jde	edf de	e jedf dedejde jfd!d"Zd#d$ Ze jj			dGdede jde	edf de	e jedf dedejde jfd%d&Z d'd( Z!e jj			dGdede jde	edf de	e jedf dedejde jfd)d*Z"d+d, Z#e jj			dGdede jde	edf de	e jedf dedejde jfd-d.Z$d/d0 Z%e jj			dGdede jde	edf de	e jedf dedejde jfd1d2Zd3d4 Z&e jj			dGdede jde	edf de	e jedf dedejde jfd5d6Z'd7d8 Z(e jj		dHdede jde	edf de	e jedf dejde jfd9d:Z)d;d< Z*e jj		dHdede jde	edf de	e jedf dejde jfd=d>Z+d?d@ Z,e jj		dHdede jde	edf de	e jedf dejde jfdAdBZ-dCdD Z.dS )I    N   )util)partial)CallableUnionc                       d fdd	S )Nc                    s    | |||dS )N)op )expr_in	tensor_inexpr_outr   backendctr	   K/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/einx/op/reduce.py<lambda>   s    <lambda>.<locals>.<lambda>Nr	   r   r   r	   r   r   r          r   )tracec           	      C   sb   | |fD ]}|  D ]}t|tjjjrtdq
qtj| g|g|g||d\}}|d |d fS )NzConcatenation not allowed)r   r   )all
isinstanceeinxexprstage3Concatenation
ValueErrorvmap_with_axis_stage3)	r
   r   r   r   r   rootr   tensors_out	exprs_outr	   r	   r   reduce_stage3   s   
r#   Tc           	         s  t jj| |\} }t jj| }t|dkrVt jjt j	|d d |gdd |
 D  |ddd }tdd | D sDtd	fd
d}t jj||}||fS d ur^tdt|d dkrqtdt|d  t|d dkrtdt|d  t jjt j	|d d |gt j	|d d g dd |
 D  |ddd d \}}tdd | D sdd | D  t jj| fdd}||fS )Nr   r   c                 S   4   g | ]\}}t jj|t|d tjf dddqS .N)depth1depth2r   r   Equationnpasarraynewaxis.0kvr	   r	   r   
<listcomp>&       "zparse.<locals>.<listcomp>T)csecse_in_markersc                 s   s     | ]}t |tjjjV  qd S r   )r   r   r   r   Markerr.   r   r	   r	   r   	<genexpr>.   s    zparse.<locals>.<genexpr>z No axes are marked for reductionc                    s.   t | tjjjr rtjjd dgS g S d S )Nr   )r   r   r   r   r5   Axisr   )keepdimsr	   r   replace2   s
   zparse.<locals>.replacez(keepdims cannot be given when using '->'z%Expected 1 input expression, but got z&Expected 1 output expression, but got c                 S   r$   r%   r(   r-   r	   r	   r   r1   G   r2      c                 s   s    | ]
}t jj|V  qd S r   )r   r   r   	is_markedr6   r	   r	   r   r7   Q   s    c                 S   s"   h | ]}t |tjjjr|jqS r	   r   r   r   r   r8   name)r.   axisr	   r	   r   	<setcomp>R   s
    zparse.<locals>.<setcomp>c                    s   t | tjjjo| j vS r   r>   r9   )axes_names_outr	   r   r   W   s    
zparse.<locals>.<lambda>)r   r   r   !_clean_description_and_parametersr   stage1parse_oplensolver)   items_anyr   r   r   r;   mark)	descriptiontensor_shaper:   r3   
parametersr   r
   r;   r   r	   )rB   r:   r   parse   sb   
"	
rN   c                    r   )Nc                    s    | |fi |S r   r	   )rK   tensorr   kwargsr   r	   r   r   `   s
    r   r   r	   r   r	   r   r   r   `   r   rK   rO   r   r:   r   r3   rM   returnc           	      K   s>   t | tj|f||d|\}}t|||||d\}}|S )a	  Applies a reduction operation on the given tensors.

    The operation reduces all marked axes in the input to a single scalar. It supports
    the following shorthand notation:

    * When no brackets are found, brackets are placed implicitly around all axes that do not
      appear in the output.

      Example: ``a b c -> a c`` resolves to ``a [b] c -> a c``.

    * When no output is given, it is determined implicitly by removing marked subexpressions
      from the input.

      Example: ``a [b] c`` resolves to ``a [b] c -> a c``.

    Args:
        description: Description string for the operation in einx notation.
        tensor: Input tensor or tensor factory matching the description string.
        op: Backend reduction operation. Is called with ``op(tensor, axis=...)``. If ``op`` is
            a string, retrieves the attribute of ``backend`` with the same name.
        keepdims: Whether to replace marked expressions with 1s instead of dropping them. Must
            be None when ``description`` already contains an output expression. Defaults to None.
        backend: Backend to use for all operations. If None, determines the backend from the
            input tensors. Defaults to None.
        cse: Whether to apply common subexpression elimination to the expressions. Defaults
            to True.
        graph: Whether to return the graph representation of the operation instead of
            computing the result. Defaults to False.
        **parameters: Additional parameters that specify values for single axes, e.g. ``a=4``.

    Returns:
        The result of the reduction operation if ``graph=False``, otherwise the graph
        representation of the operation.

    Examples:
        Compute mean along rows of a matrix:

        >>> x = np.random.uniform(size=(16, 20))
        >>> einx.mean("a b -> b", x).shape
        (20,)
        >>> einx.mean("[a] b -> b", x).shape
        (20,)
        >>> einx.mean("[a] b", x).shape
        (20,)

        Compute sum along rows of a matrix and broadcast to the original shape:

        >>> x = np.random.uniform(size=(16, 20))
        >>> einx.sum("[a] b -> a b", x).shape
        (16, 20,)

        Sum pooling with kernel size 2:

        >>> x = np.random.uniform(size=(4, 16, 16, 3))
        >>> einx.sum("b (s [s2])... c", x, s2=2).shape
        (4, 8, 8, 3)

        Compute variance per channel over an image:

        >>> x = np.random.uniform(size=(256, 256, 3))
        >>> einx.var("[...] c", x).shape
        (3,)
    )r:   r3   )r   r   )rN   r   tracer	get_shaper#   )	rK   rO   r   r:   r   r3   rM   r
   r   r	   r	   r   reduce^   s   N
rT   c                 K      t | |fd|||d|S )z7Specialization of :func:`einx.reduce` with ``op="sum"``sumr   r:   r   r3   rT   rK   rO   r:   r   r3   rM   r	   r	   r   rV         
rV   c                  O      t | ddi|S )Nr   rV   r#   argsrP   r	   r	   r   
sum_stage3      r_   c                 K   rU   )z8Specialization of :func:`einx.reduce` with ``op="mean"``meanrW   rX   rY   r	   r	   r   ra      rZ   ra   c                  O   r[   )Nr   ra   r\   r]   r	   r	   r   mean_stage3   r`   rb   c                 K   rU   )z7Specialization of :func:`einx.reduce` with ``op="var"``varrW   rX   rY   r	   r	   r   rc      rZ   rc   c                  O   r[   )Nr   rc   r\   r]   r	   r	   r   
var_stage3   r`   rd   c                 K   rU   )z7Specialization of :func:`einx.reduce` with ``op="std"``stdrW   rX   rY   r	   r	   r   re      rZ   re   c                  O   r[   )Nr   re   r\   r]   r	   r	   r   
std_stage3   r`   rf   c                 K   rU   )z8Specialization of :func:`einx.reduce` with ``op="prod"``prodrW   rX   rY   r	   r	   r   rg     rZ   rg   c                  O   r[   )Nr   rg   r\   r]   r	   r	   r   prod_stage3  r`   rh   c                 K   rU   )zASpecialization of :func:`einx.reduce` with ``op="count_nonzero"``count_nonzerorW   rX   rY   r	   r	   r   ri     s   
ri   c                  O   r[   )Nr   ri   r\   r]   r	   r	   r   count_nonzero_stage3*  r`   rj   c                 K   rU   )z7Specialization of :func:`einx.reduce` with ``op="any"``anyrW   rX   rY   r	   r	   r   rk   .  rZ   rk   c                  O   r[   )Nr   rk   r\   r]   r	   r	   r   
any_stage3=  r`   rl   c                 K   rU   )z7Specialization of :func:`einx.reduce` with ``op="all"``r   rW   rX   rY   r	   r	   r   r   A  rZ   r   c                  O   r[   )Nr   r   r\   r]   r	   r	   r   
all_stage3P  r`   rm   c                 K      t | |fd||d|S )z7Specialization of :func:`einx.reduce` with ``op="max"``maxr   r:   r   rX   rK   rO   r:   r   rM   r	   r	   r   ro   T     	ro   c                  O   r[   )Nr   ro   r\   r]   r	   r	   r   
max_stage3`  r`   rs   c                 K   rn   )z7Specialization of :func:`einx.reduce` with ``op="min"``minrp   rX   rq   r	   r	   r   rt   d  rr   rt   c                  O   r[   )Nr   rt   r\   r]   r	   r	   r   
min_stage3p  r`   ru   c                 K   rn   )z=Specialization of :func:`einx.reduce` with ``op="logsumexp"``	logsumexprp   rX   rq   r	   r	   r   rv   t  s   	rv   c                  O   r[   )Nr   rv   r\   r]   r	   r	   r   logsumexp_stage3  r`   rw   r   )NT)NNT)NN)/r    r   numpyr*   	functoolsr   typingr   r   numpy.typingnptrk   rI   jitr#   	lru_cacherN   traceback_utilfilterstrTensorboolBackend	ArrayLikerT   rV   r_   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rl   r   rm   ro   rs   rt   ru   rv   rw   r	   r	   r	   r   <module>   s   B	

O










