
    PiL                        d dl Z d dlmZ ddlmZ d dlZd dlmZm	Z	 d dl
mZ ddddZ e j        d 	          dddd
            Ze j        ddd            Zd Ze j        j         e j        d 	          ddddede j        dedede	e j        edf         dedej        de j        fd                        Zee_        e j        j        ddddede j        de	e j        edf         dedej        de j        fd            Ze j        j        ddddede j        de	e j        edf         dedej        de j        fd            Ze j        j        ddddede j        de	e j        edf         dedej        de j        fd            Ze j        j        ddddede j        de	e j        edf         dedej        de j        fd            ZdS )    N)partial   )util)CallableUnion)opbackendc                 \   J | r|d         }|dd         }|d         }	n|d         }|dd          }d t          ||          D             }g }
|D ]\  }}}}d |                                D             }||v r|                    |          nd }|!|dk    sJ |
                    |||f           cd |                                D             }||= t          j        j        j                            |          }t          |          D ]5}|
                    |t          d           f|z  |fz            ||f           6t          |
          |j        k    sJ |
}fdt          fd|D                       }| r |	|          }	| s |||          n ||||	          S )	Nr   r   c                 (    g | ]\  }\  }}}||||fS  r   ).0tensorcoordinate_axis_name
expr_coordndims        a/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/einx/op/index.py
<listcomp>z_index.<locals>.<listcomp>   s>       <F<):t 
%z48      c                 d    g | ]-}t          |t          j        j        j                  &|j        .S r   
isinstanceeinxexprstage3Axisnamer   axiss     r   r   z_index.<locals>.<listcomp>   sA     
 
 
jtyGWG\6]6]
I
 
 
r   c                 Z    g | ](}t          |t          j        j        j                  &|)S r   )r   r   r   r   r   r   s     r   r   z_index.<locals>.<listcomp>$   s/    aaaTD$)JZJ_9`9`aDaaar   c                 B    t          j        || d          d         S )NF)	broadcastr	   r   )r   transpose_broadcast)r   r   r	   expr_commons     r   	transposez_index.<locals>.transpose1   s0    '&+
 
 

 	r   c              3   8   K   | ]\  }}} ||          V  d S Nr   )r   r   r   r   r%   s       r   	<genexpr>z_index.<locals>.<genexpr>6   sG        $FF,@$		&$     r   )zipallindexappendr   r   r   Listmayberangeslicelenr   tuple)updatelayoutexpr_update_innerr$   r   r	   tensors	tensor_intensor_coordinatestensor_updatelayout2tensor_coordr   r   r   
axis_namesr   axesir%   s      ` `             @r   _indexr?   	   s    )AJ	$QrT]AJ	$QRR[ @CDVX^@_@_  F G@F  <*J
 
",.."2"2
 
 

 7Kj6X6XJ1222^b 	 <19999NNL*>
KLLLLaaZ^^%5%5aaaDT
).44T::J4[[   %++$!6!!=>(      w<<9>))))F     
     JP      D!	-1BCC 	>9()))R	-}==r   c                       fdS )Nc                 2     | fd|D             |fi |S )Nc                 &    g | ]} |          S r   r   r   xts     r   r   z.<lambda>.<locals>.<lambda>.<locals>.<listcomp>E   s!    ,,,A11Q44,,,r   r   )exprs_in
tensors_inexpr_outkwargscrE   s       r   <lambda>z<lambda>.<locals>.<lambda>D   s@    ,,,,,,,hI I:@I I r   r   rE   rJ   s   ``r   rK   rK   D   s          r   )tracec          	      l   !"# t          |           t          |          k    r/t          dt          |            dt          |                     | d         D ]G}t          |t          j        j        j                  r!|j        r|j        dk    rt          d          Ht          |           |gz   D ]L}|
                                D ]5}t          |t          j        j        j                  rt          d          6M|sJ|
                                D ]5}t          j        j                            |          rt          d          6|rud | d d	         D             }| d	         
                                D ]F}	t          |	t          j        j        j                  r |	j        |vrt          d
|	j                   Gd fdt          ||           D             }                    |          }| d         }
|r
| dd	         n	| dd          }|r| d	         }g }d}|D ]}d |
                                D             }t          |          dk    r#t          dt          |           d| d          t          |          dk    r|d         j        nd}t          |          dk    r+|d         j        r|d         j        dk    r|d         j        nd }|                    ||f           ||z  }d |

                                D             t                    |k    r"t          d| dt                               |r@d |
                                D             }t          |          dk    rt          d          d |

                                D             "t#                        "fd!!fd|D             }|r%t          j        j                            |!          nd } fd!t          j        j                            |!          }|r%t          j        j                            |!          }|r*fd!t          j        j                            |!          }d ##fd|D             }|r #|          nd }d t          ||          D             }|r|d |d fgz   }t'          |d           d	         fdd         
                                D             }d  |D             }|D ]\  }}}|
                                D ]i}	t          |	t          j        j        j                  rC|	j        |k    r8|	j        |vr/|                    |	j                   |                    |	           jt          j        j        j                            |          }n=t          j        j                            t1          j        |g          d                   }t          t4                    rt7                    t9          t:          ||||!          t          j                  |
g|z   |r|gng z   } t          j        | ||gd"#          \  }}t          |          dk    rt          |          dk    sJ |d         |d         fS )$N	Expected z input tensors, got r   r   9First expression cannot contain unnamed axes with value 1zConcatenation not allowedz1Brackets in the output expression are not allowedc                     h | ]D}|                                 D ]-}t          |t          j        j        j                  &|j        .ES r   )r*   r   r   r   r   r   r   )r   rootr   s      r   	<setcomp>zindex_stage3.<locals>.<setcomp>X   sa     
 
 



 
 $	 0 566	
I
 
 
 
r   r   z\Update expression cannot contain axes that are not in the coordinate or tensor expressions: c                     | dk    rdS | S )Nget_at	embeddingr   )ss    r   get_namezindex_stage3.<locals>.get_namef   s    ==;Hr   c                     g | ][\  }}t           j                            ||j         t	          j                            t	          j                             \S ))r   init)r   tracercall_factoryshaper   
_op_to_str)r   r   r   r	   rX   r   s      r   r   z index_stage3.<locals>.<listcomp>l   su     	 	 	 FD 	  J$/"--..$$ 	! 	
 	
	 	 	r   c                     g | ]L}t          |t          j        j        j                  &t          j        j                            |          J|MS r   )r   r   r   r   r   	is_markedr   r   s     r   r   z index_stage3.<locals>.<listcomp>   s_     "
 "
 "
$	 0 566"
 <@9;K;U;UVZ;[;["
"
 "
 "
r   zCExpected at most one coordinate axis in coordinate expression, got z in ''c                     h | ]Q}t          |t          j        j        j                  &t          j        j                            |          J|j        RS r   r   r   r   r   r   r`   r   ra   s     r   rS   zindex_stage3.<locals>.<setcomp>   s`          dDI,122  8<y7G7Q7QRV7W7W 	     r   z marked axes in tensor, got c                     h | ]Q}t          |t          j        j        j                  &t          j        j                            |          J|j        RS r   rd   ra   s     r   rS   zindex_stage3.<locals>.<setcomp>   sa     $
 $
 $
$	 0 566$
 <@9;K;U;UVZ;[;[$
I$
 $
 $
r   z,Update expression cannot contain marked axesc                 d    h | ]-}t          |t          j        j        j                  &|j        .S r   r   ra   s     r   rS   zindex_stage3.<locals>.<setcomp>   sA       :dDIDTDY3Z3Z	  r   c                 R   t          | t          j        j        j                  r}| j        vrvt          j        j                            |           sT                    | j                   t          j        j                            | 	                                          S d S d S d S r'   )
r   r   r   r   r   r   r`   addMarker__deepcopy__)r   new_marked_axis_namestensor_axis_namess    r   replacezindex_stage3.<locals>.replace   s    tTY-233	@	!222I$..t44 3 "%%di0009#**4+<+<+>+>???	@ 	@2222r   c                 Z    g | ]'}t           j        j                            |          (S r   )r   r   r   rm   )r   r   rm   s     r   r   z index_stage3.<locals>.<listcomp>   s.    ___T)11$@@___r   c                    t          | t          j        j        j                  rc| j        v r\t          j        j                            |           s:t          j        j                            |                                           S d S d S d S r'   	r   r   r   r   r   r   r`   ri   rj   )r   rk   s    r   rm   zindex_stage3.<locals>.replace   s    tTY-233	@	222I$..t44 3 9#**4+<+<+>+>???	@ 	@2222r   c                    t          | t          j        j        j                  rc| j        v r\t          j        j                            |           s:t          j        j                            |                                           S d S d S d S r'   rp   )r   marked_tensor_axis_namess    r   rm   zindex_stage3.<locals>.replace   s    4!1!677DI!999	(22488 : y'..t/@/@/B/BCCCD D9999r   c                     t           j        j                            |           } t	          j        | g          d         S )Nr   )r   r   r   
get_markedr   flatten)r   s    r   to_innerzindex_stage3.<locals>.to_inner   s1    y**400|TF##A&&r   c                 &    g | ]} |          S r   r   )r   r   rv   s     r   r   z index_stage3.<locals>.<listcomp>   s!    LLL$xx~~LLLr   c                 $    g | ]\  }\  }}|||fS r   r   )r   r   r   r   s       r   r   z index_stage3.<locals>.<listcomp>   s9       4J4-t 
z40  r   c                 6    t          | d         j                  S )Nr   )r1   r]   )rD   s    r   rK   zindex_stage3.<locals>.<lambda>   s    AaDJ r   )keyc                 ~    g | ]9}t          |t          j        j        j                  r|j        d          k    7|:S )r   r   )r   r   longests     r   r   z index_stage3.<locals>.<listcomp>   sS     
 
 
$	 0 566
 @DyGTUJ?V?V ?V?V?Vr   c                     h | ]	}|j         
S r   )r   r   s     r   rS   zindex_stage3.<locals>.<setcomp>   s    555Ddi555r   )r   r3   r4   r$   r5   r	   T)r   flatr	   ) r1   
ValueErrorr   r   r   r   r   
is_unnamedvaluelistr*   Concatenationr`   r   r)   all_to_tensorr,   setrm   sortedrh   r-   r.   rt   r   ru   strgetattrr   r?   rM   vmap_stage3)$rF   rG   rH   r3   r   r	   r   rR   r<   r   expr_tensorexprs_coordinatesexpr_updater4   
total_ndimr   marked_coordinate_axesr   r   marked_update_axis_namesexprs_coordinates_innerr5   r:   all_axes
axes_names_r$   tensors_out	exprs_outrX   r|   rr   rk   rm   rl   rv   s$       ``                       @@@@@@@r   index_stage3r   C   s    8}}J''YS]]YYJYYZZZ Z ZdDI,122 	Zt 	Z4:YZ??XYYYX(+ > >HHJJ 	> 	>D$	 0 >?? > !<===>	>  VLLNN 	V 	VDy))$// V !TUUUV 
 
 "
 
 

 RL$$&& 	 	D$	 0 566 49J;V;V E9=E E    	 	 	 	 	 	  
H55	 	 	J &&z22J1+K*0B2hqrrl #rlFJ'  
"
 "
"(("
 "
 "

 %&&**G122G G9CG G G   366L2M2MQR2R2R%a(..XY )**a//+A.9 0=STU=V=\`a=a=a #1%** 	 	 	+T2333d

   OO%%     
 #$$
22_
__D\@]@]__
 
 	
  M$
 $
#))$
 $
 $
 
 '((A--KLLL )oo//    EE@ @ @ @ @ @ `___M^___DJT$)"**;@@@PTK@ @ @ @ @ y'''::H Ei&..{GDD  
?	D 	D 	D 	D 	D 9#++Hg>>' ' ' MLLL:KLLL17A---T 8;<SU[8\8\  F  OT#4d;<<&?&?@@@D
 
 
 

((
 
 

 65H555
3: 	* 	*/ *a"(( * *tTY%5%:;;*	%999	33NN49---OOD)))* i&+11(;;i&11$,z2J2J12MNN "c "Wb!!	+
 
 
B 
BB}00V4S[MMQSTH!-*xjRdG  K {q  S^^q%8%8%88q>9Q<''r   T)csec                   t           j        j                            | |          \  } }t           j        j                            |           }t          |          dk    rmr\t           j        j                            |d         t           j        j        	                    |d         d         g          g          }nt          d          t          |d                   t                    k    r5t          dt          |d                    dt                               t          |d                   dk    r%t          dt          |d                              fd}t           j                            d t          |d                   D             t           j                            |d         d                   gz   d	 |                                D             z   ||
          d t          |d                   dz            }|d t          |d                            |t          |d                            }	}rld |d                                         D             }
d |	                                D             }|
                    |          st          d|
|z
             ||	fS )Nr   r   z2Operation string must contain an output expressionrO   z input tensors, but got z&Expected 1 output expression, but got c                    | d                                          D ]d}t          |t          j        j        j                  r>|j        dk    r3t          j        j                            |          rt          d          ed | d                                          D             }t          |          }g }| dt                             }	r
|d d         }|D ]T}d | d                                          D             }t          |          dk    rt          dt          |                     t          |          dk    rt          |d         t          j        j        j
                  rC|                    t          j        j        
                    |d         j                             |                    t          j        j                            |d         j                             |                    t          j        j                            d                     Vt          j                            t          j        j        j                            |          t#          j        |g                    gS )Nr   r   rP   c                     g | ]b}t          |t          j        j        j        t          j        j        j        f          <t          j        j                            |          `|cS r   r   r   r   stage2	NamedAxisUnnamedAxisr`   ra   s     r   r   z/parse.<locals>.after_stage2.<locals>.<listcomp>+  sj     
 
 
$!1!;TY=M=Y Z[[
 	 **400	

 
 
r   r   c                     g | ]b}t          |t          j        j        j        t          j        j        j        f          <t          j        j                            |          `|cS r   r   ra   s     r   r   z/parse.<locals>.after_stage2.<locals>.<listcomp>9  sj     & & &dTY%5%?AQA]$^__& I$..t44	&& & &r   z<Expected at most one marked axis per coordinate tensor, got )r*   r   r   r   r   r   r   r`   r   r1   r   r,   stage1r   Equationr   r.   npasarray)
exprs1exprs2r   tensor_marked_axesr   concat_thiscoord_exprsr   tensor_shapesr3   s
           r   after_stage2zparse.<locals>.after_stage2#  sy   1IMMOO 	^ 	^D4!1!=>>^J!OOI$..t44 $ !!\]]]
 
q	
 
 
 %&&Q]!3!334 	+%crc*K 	D 	DD& &"1IMMOO& & &" )**Q.. ; !788; ;   +,,114Q79I9STT &&ty'7'A'ABXYZB[B`'a'abbbb&&	(445KA5N5TUU    ""49#3#?#?#B#BCCCC I	 .44[AA2:tfCUCU 
 	
r   c                 T    g | ]%\  }}t           j                            ||          &S r   )r   r   r   )r   expr_intensor_shapes      r   r   zparse.<locals>.<listcomp>U  s>     	
 	
 	
% Iw55	
 	
 	
r   c                     g | ]L\  }}t           j                            |t          j        |          d t          j        f         dd          MS ).N)depth1depth2)r   r   r   r   r   newaxis)r   kvs      r   r   zparse.<locals>.<listcomp>Z  sY     
 
 
1 Iq"*Q--RZ"@VZ[[
 
 
r   )r   r   c                 d    h | ]-}t          |t          j        j        j                  &|j        .S r   r   r   s     r   rS   zparse.<locals>.<setcomp>e  sA     
 
 
z$	HXH]7^7^
I
 
 
r   c                 d    h | ]-}t          |t          j        j        j                  &|j        .S r   r   r   s     r   rS   zparse.<locals>.<setcomp>h  s1    ddd$JtTYM]Mb<c<cdDIdddr   zIOutput expression does not contain all axes from first input expression: )r   r   r   !_clean_description_and_parametersr   r   parse_opr1   OpArgsr   solver)   r   itemsr*   issubset)descriptionr3   r   r   
parametersr   r   exprsrF   rH   axes_inaxes_outs    ` `        r   parser     s   "glLLZ K 
		"	";	/	/B 2ww!|| 	S!$$1	 %%r!uQxj11&  BB
 QRRR
2a5zzS'''']SAZZ]]]I[I[]]^^^
2a5zzQN#be**NNOOO/
 /
 /
 /
 /
 /
b IOO	
 	
),RUM)B)B	
 	
 	
 9beAh''
(		)

 
"((**
 
 
	
 !    BqE

QE |RU|,eC1JJ.?hH 

 
"*1+//"3"3
 
 
 ed(,,..ddd)) 	(X%( (  
 Xr   c                 z    t           j                            |           }|d uot          d |D                       S )Nc              3   "   K   | ]
}|d k    V  dS )r   Nr   )r   rW   s     r   r(   z"_has_zero_shape.<locals>.<genexpr>t  s&      $;$;Q!V$;$;$;$;$;$;r   )r   r[   	get_shapeany)r   r]   s     r   _has_zero_shaper   r  s>    K!!&))E;$;$;U$;$;$;!;!;;r   c                      d d fd
S )N)r	   c                4     | gfd|D             R i |S )Nc                 &    g | ]} |          S r   r   rC   s     r   r   z.<lambda>.<locals>.<lambda>.<locals>.<listcomp>z  s!    ---qqtt---r   r   )r   r	   r6   rI   rJ   rE   s       r   rK   z<lambda>.<locals>.<lambda>y  sJ    QQN----W---N N N17N N r   r   rL   s   ``r   rK   rK   y  s+    T        r   )r	   r   r   r6   r   r3   r	   r   r   returnc                    |r)t          d |dd         D                       r|d         S t          | gd |D             R ||d|\  }}t          ||||||          \  }	}|	S )a>  Updates and/ or returns values from a tensor at the given coordinates.

    * If ``update`` is True: The first tensor receives updates, the last tensor contains the
      updates, and all other tensors represent the coordinates. If the output expression is
      not given, it is assumed to be equal to the first input expression.

    * If ``update`` is False, values are retrieved from the first tensor and the remaining tensors
      contain the coordinates.

    Using multiple coordinate expressions will yield the same output as concatenating
    the coordinate expressions along the coordinate axis first.

    Args:
        description: Description string for the operation in einx notation.
        *tensors: Tensors that the operation will be applied to.
        op: The update/gather function. If ``op`` is a string, retrieves the attribute of
            ``backend`` with the same name.
        update: Whether to update the tensor or return values from the tensor.
        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 update/ gather operation if ``graph=False``, otherwise the graph
        representation of the operation.

    Examples:
        Get values from a batch of images (different indices per image):

        >>> tensor = np.random.uniform(size=(4, 128, 128, 3))
        >>> coordinates = np.ones((4, 100, 2))
        >>> einx.get_at("b [h w] c, b p [2] -> b p c", tensor, coordinates).shape
        (4, 100, 3)

        >>> tensor = np.random.uniform(size=(4, 128, 128, 3))
        >>> coordinates_x = np.ones((4, 100), "int32")
        >>> coordinates_y = np.ones((4, 100), "int32")
        >>> einx.get_at(
        ...     "b [h w] c, b p, b p -> b p c",
        ...     tensor,
        ...     coordinates_x,
        ...     coordinates_y,
        ... ).shape
        (4, 100, 3)

        Set values in a batch of images (same indices per image):

        >>> tensor = np.random.uniform(size=(4, 128, 128, 3))
        >>> coordinates = np.ones((100, 2), "int32")
        >>> updates = np.random.uniform(size=(100, 3))
        >>> einx.set_at(
        ...     "b [h w] c, p [2], p c -> b [h w] c", tensor, coordinates, updates
        ... ).shape
        (4, 128, 128, 3)

        >>> tensor = np.random.uniform(size=(4, 128, 128, 3))
        >>> coordinates_x = np.ones((100,), "int32")
        >>> coordinates_y = np.ones((100,), "int32")
        >>> updates = np.random.uniform(size=(100, 3))
        >>> einx.set_at(
        ...     "b [h w] c, p, p, p c -> b [h w] c",
        ...     tensor,
        ...     coordinates_x,
        ...     coordinates_y,
        ...     updates,
        ... ).shape
        (4, 128, 128, 3)
    c              3   4   K   | ]}t          |          V  d S r'   )r   r   r   s     r   r(   zindex.<locals>.<genexpr>  s*      HH&of--HHHHHHr   r   Nr   c                 L    g | ]!}t           j                            |          "S r   )r   r[   r   r   s     r   r   zindex.<locals>.<listcomp>  s(    	>	>	>F$+


'
'	>	>	>r   )r3   r   )r   r3   r	   )r   r   r   )
r   r   r3   r	   r   r6   r   rF   rH   r   s
             r   r+   r+   w  s    n  #HHGABBKHHHHH qz	>	>g	>	>	>  	 
  Hh $'867  FH Mr   c                ,    t          | g|R dd||d|S )zNSpecialization of :func:`einx.index` with ``op="get_at"`` and ``update=False``rU   Fr   r3   r	   r   r+   r   r	   r   r6   r   s        r   rU   rU     sA      "*5's V`  r   c                ,    t          | g|R dd||d|S )zMSpecialization of :func:`einx.index` with ``op="set_at"`` and ``update=True``set_atTr   r   r   s        r   r   r     A      "*4c U_  r   c                ,    t          | g|R dd||d|S )zMSpecialization of :func:`einx.index` with ``op="add_at"`` and ``update=True``add_atTr   r   r   s        r   r   r     r   r   c                ,    t          | g|R dd||d|S )zRSpecialization of :func:`einx.index` with ``op="subtract_at"`` and ``update=True``subtract_atTr   r   r   s        r   r   r     sB      "/gSV Zd  r   )r   	functoolsr    r   numpyr   typingr   r   numpy.typingnptr?   jitr   	lru_cacher   r   traceback_utilfilterr   TensorboolBackend	ArrayLiker+   rU   r   r   r   r   r   r   <module>r      s                    " " " " " " " "       IMVZ 7 7 7 7 7t 
   
 @DT A( A( A( A( 
A(H 37 b b b b bJ< < <
 	    /3^ ^ ^^k^ 	^ 	^
 4<d*+^ 
^ -^ 
[^ ^ ^  ^B   /3	
 
 

k
 4<d*+
 
	

 -
 
[
 
 
 
  /3	
 
 

k
 4<d*+
 
	

 -
 
[
 
 
 
  /3	
 
 

k
 4<d*+
 
	

 -
 
[
 
 
 
  /3	
 
 

k
 4<d*+
 
	

 -
 
[
 
 
 
 
 
r   