
    `iF                        d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZ  G d de	          Z
 G d de
          Z e            Z	  G d d	e
          Z e            Z	 efd
Zd ZddZddZddZddZddZddZddZdS )    N)	from_data)joinc                   ,    e Zd ZdZd ZddZd Zd	 Zd
S )AxisConcatenatorzTranslates slice objects to concatenation along an axis.

    For detailed documentation on usage, see :func:`cupy.r_`.
    This implementation is partially borrowed from NumPy's one.

    c                     ||z
  }|dk     r||dz   z  }t          t          |                    }|}|d |         ||d          z   |||         z   }|                    |          S )Nr      )listrange	transpose)	selfobjndimndmintrans1dk2defaxesk1axess	            k/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupy/_indexing/generate.py_output_objzAxisConcatenator._output_obj   sv    T\Q;;rAvGuU||$$ss|gbccl*BrEN}}T"""    r   Fr   c                 >    || _         || _        || _        || _        d S N)axisr   matrixr   )r   r   r   r   r   s        r   __init__zAxisConcatenator.__init__    s"    	


r   c                    | j         }| j        }g }g }g }t          t                    rt          t          t
                    sft                    D ] \  }}t          |t                    rt          t          |t                    r|dk    rt          d          t          t          |          t          j        v r,t          j        ||          }	|                    |           nqt          j        |d|          }	|dk    r?t          j        |d          j        }
|dk    r|
|k     r|                     |	|
||          }	|                    |	           |                    |	           "t          j        g |fd	|D             R  }|#|D ] }||                             |          ||<   !t'          j        t          |          | j        
          S )Nr   z+special directives must be the first entry.)r   F)copyr   r   r   r   c                      g | ]
}|         S  r"   ).0kkeys     r   
<listcomp>z0AxisConcatenator.__getitem__.<locals>.<listcomp>F   s    2K2K2Ka3q62K2K2Kr   )r   )r   r   
isinstancestrNotImplementedErrortuple	enumerateslice
ValueErrortypenumpy
ScalarTyper   arrayappendr   r   result_typeastyper   concatenater   )r   r%   r   r   objsarraysscalarsir$   newobjr   final_dtypes    `          r   __getitem__zAxisConcatenator.__getitem__&   s   ,
c3 	&%%#u%% 	&CcNN 	  	 DAq!U## &))As## &66$EG G G))aE,,,"%888q!!!!"eDDD199$?15999>D"}}!%!1!1&$w!O!Of%%%KK'LL2K2K2K2K72K2K2KLLL" 6 6q'..55Qd$)<<<<r   c                     dS )Nr   r"   )r   s    r   __len__zAxisConcatenator.__len__M   s    qr   N)r   Fr   r   )__name__
__module____qualname____doc__r   r   r<   r>   r"   r   r   r   r      s`         # # #   %= %= %=N    r   r   c                        e Zd Z fdZ xZS )CClassc                 ^    t          t          |                               ddd           d S )Nr      r   )r   r   )superrD   r   r   	__class__s    r   r   zCClass.__init__S   s.    fd$$Rq!$<<<<<r   r?   r@   rA   r   __classcell__rI   s   @r   rD   rD   Q   s8        = = = = = = = = =r   rD   c                        e Zd Z fdZ xZS )RClassc                 V    t          t          |                                            d S r   )rG   rN   r   rH   s    r   r   zRClass.__init__t   s%    fd$$&&&&&r   rJ   rL   s   @r   rN   rN   r   s8        ' ' ' ' ' ' ' ' 'r   rN   c                 6   t          |           } t          |           }d|z  }t          j        |f| z   |          }t	          |           D ]K\  }}t          j        ||                              |d|         |fz   ||dz   d         z             ||<   L|S )a  Returns an array representing the indices of a grid.

    Computes an array where the subarrays contain index values 0,1,...
    varying only along the corresponding axis.

    Args:
        dimensions: The shape of the grid.
        dtype: Data type specifier. It is int by default.

    Returns:
        ndarray:
        The array of grid indices,
        ``grid.shape = (len(dimensions),) + tuple(dimensions)``.

    Examples
    --------
    >>> grid = cupy.indices((2, 3))
    >>> grid.shape
    (2, 2, 3)
    >>> grid[0]        # row indices
    array([[0, 0, 0],
           [1, 1, 1]])
    >>> grid[1]        # column indices
    array([[0, 1, 2],
           [0, 1, 2]])

    .. seealso:: :func:`numpy.indices`

    r   dtypeNr   )r*   lencupyemptyr+   arangereshape)
dimensionsrS   Nshaperesr9   dims          r   indicesr^      s    < z""JJA1HE
*aTJ&e
4
4
4CJ'' 
 
3S...66"1"Iq1uvv.
 
A Jr   c                     g }t          |           }t          |           D ]\  }}t          j        |          }|j        dk    rt          d          |j        dk    r|                    t          j	                  }t          j        |j        t          j                  r|                                \  }|                    d|z  |j        fz   d||z
  dz
  z  z             }|                    |           t#          |          S )a  Construct an open mesh from multiple sequences.

    This function takes N 1-D sequences and returns N outputs with N
    dimensions each, such that the shape is 1 in all but one dimension
    and the dimension with the non-unit shape value cycles through all
    N dimensions.

    Using `ix_` one can quickly construct index arrays that will index
    the cross product. ``a[cupy.ix_([1,3],[2,5])]`` returns the array
    ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.

    Args:
        *args: 1-D sequences

    Returns:
        tuple of ndarrays:
        N arrays with N dimensions each, with N the number of input sequences.
        Together these arrays form an open mesh.

    Examples
    --------
    >>> a = cupy.arange(10).reshape(2, 5)
    >>> a
    array([[0, 1, 2, 3, 4],
           [5, 6, 7, 8, 9]])
    >>> ixgrid = cupy.ix_([0,1], [2,4])
    >>> ixgrid
    (array([[0],
           [1]]), array([[2, 4]]))

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`numpy.ix_`

    r   z!Cross index must be 1 dimensionalr   rQ   )rT   r+   r   asarrayr   r-   sizer4   r/   intprU   
issubdtyperS   bool_nonzerorX   r2   r*   )argsoutndr$   news        r   ix_rj      s    N C	TBD// 
 
3$$8q==@AAA8q==**UZ((C?39dj11 	!;;==DCkk$(ch[0426A:3FFGG

3::r   wrapCc                 P   t          |          }t          |           |k    r"t          d                    |                    |D ]K}t          |t          j                  s/t          d                    t          |                              Lt          |t                    r|f|z  }t          j
        t          j        |          t          j        t          j                  j        k    rt          d          d}dg|z  }|dn|                                }|dk    r+t%          |dz
  dd          D ]}|||dz            z  }|||<   n<|d	k    r't%          d|          D ]}|||dz
           z  }|||<   nt          d
          t          j        |  } t          j        | d         j        t          j                  }	t-          ||| |          D ]K\  }}
}}t          |t          j                  st          d          t          j        |t          j        d          s>t          d                    |j        t          j                    j                            |                    t          j        d          }|dk    r?t          j        t          j        ||k    |dk                         rt          d          nN|dk    rt          j        |d|dz
            }n.|dk    r||z  }n"t          d                    |                    |	|
|z  z  }	M|	S )a"  
    Converts a tuple of index arrays into an array of flat indices, applying
    boundary modes to the multi-index.

    Args:
        multi_index (tuple of cupy.ndarray) : A tuple of integer arrays, one
            array for each dimension.
        dims (tuple of ints): The shape of array into which the indices from
            ``multi_index`` apply.
        mode ('raise', 'wrap' or 'clip'), optional: Specifies how out-of-bounds
            indices are handled.  Can specify either one mode or a tuple of
            modes, one mode per index:

            - *'raise'* -- raise an error
            - *'wrap'* -- wrap around (default)
            - *'clip'* -- clip to the range

            In 'clip' mode, a negative index which would normally wrap will
            clip to 0 instead.
        order ('C' or 'F'), optional: Determines whether the multi-index should
            be viewed as indexing in row-major (C-style) or column-major
            (Fortran-style) order.

    Returns:
        raveled_indices (cupy.ndarray): An array of indices into the flattened
        version of an array of dimensions ``dims``.

    .. warning::

        This function may synchronize the device when ``mode == 'raise'``.

    Notes
    -----
    Note that the default `mode` (``'wrap'``) is different than in NumPy. This
    is done to avoid potential device synchronization.

    Examples
    --------
    >>> cupy.ravel_multi_index(cupy.asarray([[3,6,6],[4,5,1]]), (7,6))
    array([22, 41, 37])
    >>> cupy.ravel_multi_index(cupy.asarray([[3,6,6],[4,5,1]]), (7,6),
    ...                        order='F')
    array([31, 41, 13])
    >>> cupy.ravel_multi_index(cupy.asarray([[3,6,6],[4,5,1]]), (4,6),
    ...                        mode='clip')
    array([22, 23, 19])
    >>> cupy.ravel_multi_index(cupy.asarray([[3,6,6],[4,5,1]]), (4,4),
    ...                        mode=('clip', 'wrap'))
    array([12, 13, 13])
    >>> cupy.ravel_multi_index(cupy.asarray((3,1,4,1)), (6,7,8,9))
    array(1621)

    .. seealso:: :func:`numpy.ravel_multi_index`, :func:`unravel_index`
    z5parameter multi_index must be a sequence of length {}z-{} object cannot be interpreted as an integerzQinvalid dims: array size defined by dims is larger than the maximum possible sizer   Nrl   rF   r   Forder not understoodr   rR   z+elements of multi_index must be cupy arrays	same_kindzgmulti_index entries could not be cast from dtype('{}') to dtype('{}') according to the rule 'same_kind'Fr    raisez"invalid entry in coordinates arraycliprk   zUnrecognized mode: {})rT   r-   formatr'   numbersIntegral	TypeErrorr.   r(   	functoolsreduceoperatormulrU   iinfoint64maxupperr
   broadcast_arrayszerosr[   zipndarraycan_castrS   r4   any
logical_orrr   )multi_indexdimsmodeorderr   dsravel_stridesr9   raveled_indicesstrideidx_modes                r   ravel_multi_indexr      sS   p t99D
;4t& & 	&   !W-.. 	?FFGG   	
 $ x$d++dj.D.D.HHH : ; ; 	; 	
AC$JM=CCekkmmE||taxR(( 	! 	!ADQKA M!	! 
#q$ 	! 	!ADQKA M!	! /000'5KjQ!5TZHHHO!$T=+t!L!L ( (63#t|,, 	KIJJJ}S$*k:: 	4DDJFItz||1E3 E34 4 4 jj%j00Gxq#'::;; G !EFFFGf__)CAE**CCf__'CC4;;EBBCCC6C<'r   c                 r   |dn|                                 }|dk    rt          |          }n|dk    rnt          d          t          j        | t          j        d          s>t          d                    | j        t          j                    j                            | dk     	                                rt          d          g }|D ]}|
                    | |z             | |z  }  | dk    	                                rt          d          |dk    rt          |          }t          |          S )	a  Converts array of flat indices into a tuple of coordinate arrays.

    Args:
        indices (cupy.ndarray): An integer array whose elements are indices
            into the flattened version of an array of dimensions :obj:`dims`.
        dims (tuple of ints): The shape of the array to use for unraveling
            indices.
        order ('C' or 'F'): Determines whether the indices should be viewed as
            indexing in row-major (C-style) or column-major (Fortran-style)
            order.

    Returns:
        tuple of ndarrays:
        Each array in the tuple has the same shape as the indices array.

    Examples
    --------
    >>> cupy.unravel_index(cupy.array([22, 41, 37]), (7, 6))
    (array([3, 6, 6]), array([4, 5, 1]))
    >>> cupy.unravel_index(cupy.array([31, 41, 13]), (7, 6), order='F')
    (array([3, 6, 6]), array([4, 5, 1]))

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`numpy.unravel_index`, :func:`ravel_multi_index`

    Nrl   rn   ro   rp   zlIterator operand 0 dtype could not be cast from dtype('{}') to dtype('{}') according to the rule 'same_kind'r   zinvalid entry in index array)r~   reversedr-   rU   r   r|   rv   rs   rS   r   r2   r*   )r^   r   r   unraveled_coordsr]   s        r   unravel_indexr   j  sG   < =CCekkmmE||~~	#/000=$*k:: 4228&tz||133 334 4 	4 	! 97888 ! !#...S.! 97888||#$455!"""r   c                     t          j        | | ft           j                  } |||                                          S )a<  
    Return the indices to access (n, n) arrays, given a masking function.

    Assume `mask_func` is a function that, for a square array a of
    size ``(n, n)`` with a possible offset argument `k`, when called
    as ``mask_func(a, k)`` returns a new array with zeros in certain
    locations (functions like :func:`~cupy.triu` or :func:`~cupy.tril` do
    precisely this). Then this function returns the indices where the non-zero
    values would be located.

    Args:
        n (int): The returned indices will be valid to access arrays
            of shape (n, n).
        mask_func (callable): A function whose call signature is
            similar to that of :func:`~cupy.triu`, :func:`~tril`.  That is,
            ``mask_func(x, k)`` returns a boolean array, shaped like
            `x`.  `k` is an optional argument to the function.
        k (scalar): An optional argument which is passed through to
            `mask_func`. Functions like :func:`~cupy.triu`, :func:`~cupy.tril`
            take a second argument that is interpreted as an offset.

    Returns:
        tuple of arrays: The `n` arrays of indices corresponding to
        the locations where ``mask_func(np.ones((n, n)), k)`` is
        True.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`numpy.mask_indices`
    rR   )rU   onesint8re   )n	mask_funcr$   as       r   mask_indicesr     s;    B 		1a&	***A9Q??""$$$r   c                     t          j        | ||t                    t          fdt          j        j        t                    D                       S )a  Returns the indices of the lower triangular matrix.
    Here, the first group of elements contains row coordinates
    of all indices and the second group of elements
    contains column coordinates.

    Parameters
    ----------
    n : int
        The row dimension of the arrays for which the returned
        indices will be valid.
    k : int, optional
        Diagonal above which to zero elements. `k = 0`
        (the default) is the main diagonal, `k < 0` is
        below it and `k > 0` is above.
    m : int, optional
        The column dimension of the arrays for which the
        returned arrays will be valid. By default, `m = n`.

    Returns
    -------
    y : tuple of ndarrays
        The indices for the triangle. The returned tuple
        contains two arrays, each with the indices along
        one dimension of the array.

    See Also
    --------
    numpy.tril_indices

    r$   rS   c              3   X   K   | ]$}t          j        |j                           V  %d S r   rU   broadcast_tor[   r#   indstri_s     r   	<genexpr>ztril_indices.<locals>.<genexpr>  S       B B "444T: B B B B B Br   rR   rU   triboolr*   r^   r[   intr   r$   mr   s      @r   tril_indicesr     sq    @ 8AqAT***D B B B B!\$*C@@@B B B B B Br   c                     | j         dk    rt          d          t          | j        d         || j        d                   S )a6  Returns the indices for the lower-triangle of arr.

    Parameters
    ----------
    arr : cupy.ndarray
          The indices are valid for square arrays
          whose dimensions are the same as arr.
    k : int, optional
        Diagonal offset.

    See Also
    --------
    numpy.tril_indices_from

    rF   input array must be 2-dr   r$   r   )r   r-   r   r[   arrr$   s     r   tril_indices_fromr     s?    " x1}}2333	"cim<<<<r   c                     t          j        | ||dz
  t                     t          fdt          j        j        t                    D                       S )a  Returns the indices of the upper triangular matrix.
    Here, the first group of elements contains row coordinates
    of all indices and the second group of elements
    contains column coordinates.

    Parameters
    ----------
    n : int
        The size of the arrays for which the returned indices will
        be valid.
    k : int, optional
        Refers to the diagonal offset. By default, `k = 0` i.e.
        the main dialogal. The positive value of `k`
        denotes the diagonals above the main diagonal, while the negative
        value includes the diagonals below the main diagonal.
    m : int, optional
        The column dimension of the arrays for which the
        returned arrays will be valid. By default, `m = n`.

    Returns
    -------
    y : tuple of ndarrays
        The indices for the triangle. The returned tuple
        contains two arrays, each with the indices along
        one dimension of the array.

    See Also
    --------
    numpy.triu_indices

    r   r   c              3   X   K   | ]$}t          j        |j                           V  %d S r   r   r   s     r   r   ztriu_indices.<locals>.<genexpr>1  r   r   rR   r   r   s      @r   triu_indicesr     sx    B HQQU$////D B B B B!\$*C@@@B B B B B Br   c                     | j         dk    rt          d          t          | j        d         || j        d                   S )a  Returns indices for the upper-triangle of arr.

    Parameters
    ----------
    arr : cupy.ndarray
          The indices are valid for square arrays.
    k : int, optional
        Diagonal offset (see 'triu_indices` for details).

    Returns
    -------
    triu_indices_from : tuple of ndarrays
        Indices for the upper-triangle of `arr`.

    See Also
    --------
    numpy.triu_indices_from

    rF   r   r   r   r   )r   r-   r   r[   r   s     r   triu_indices_fromr   5  s?    * x1}}2333	"cim<<<<r   )rk   rl   )rl   )r   )r   N)rw   rt   ry   r/   rU   cupy._creationr   cupy._manipulationr   objectr   rD   c_rN   r_r   r^   rj   r   r   r   r   r   r   r   r"   r   r   <module>r      s           $ $ $ $ $ $ # # # # # #@ @ @ @ @v @ @ @F= = = = = = = = VXX4' ' ' ' ' ' ' ' VXX: " & & & &R4 4 4nq q q qh:# :# :# :#z"% "% "% "%V#B #B #B #BL= = = =,$B $B $B $BN= = = = = =r   