o
    #j                     @   s  d dl Zd dlZd dlmZ d dlmZmZ d dlmZ ddl	m
Z
mZ ddlmZmZmZmZmZ g Zd,d
dZd-ddZd-ddZd.ddZd/ddZd,ddZd,ddZd0ddZed0ddZdd Zd1dd Zd2d"d#Zd3d$d%Z	d3d&d'Z d4d(d)Z!d0d*d+Z"dS )5    N)_C_ops)VarDescVariable)inplace_apis_in_dygraph_only   )check_dtypecheck_variable_and_dtype)LayerHelperconvert_np_dtype_to_dtype_corein_dynamic_modein_dynamic_or_pir_modeFc                 C   s   t  rt| ||\}}|S t| dg dd tdi t }|j| jdd}|jtj	j
dd}|jdd| i||d||d	d
 |S )a	  
    Sorts the input along the given axis, and returns the corresponding index tensor for the sorted output values. The default sort algorithm is ascending, if you want the sort algorithm to be descending, you must set the :attr:`descending` as True.

    Args:
        x (Tensor): An input N-D Tensor with type bfloat16, float16, float32, float64, int16,
            int32, int64, uint8.
        axis (int, optional): Axis to compute indices along. The effective range
            is [-R, R), where R is Rank(x). when axis<0, it works the same way
            as axis+R. Default is -1.
        descending (bool, optional) : Descending is a flag, if set to true,
            algorithm will sort by descending order, else sort by
            ascending order. Default is false.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        Tensor: sorted indices(with the same shape as ``x``
        and with data type int64).

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[[5,8,9,5],
            ...                        [0,0,1,7],
            ...                        [6,9,2,4]],
            ...                       [[5,2,4,2],
            ...                        [4,7,7,9],
            ...                        [1,7,0,6]]],
            ...                      dtype='float32')
            >>> out1 = paddle.argsort(x, axis=-1)
            >>> out2 = paddle.argsort(x, axis=0)
            >>> out3 = paddle.argsort(x, axis=1)

            >>> print(out1)
            Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[[0, 3, 1, 2],
              [0, 1, 2, 3],
              [2, 3, 0, 1]],
             [[1, 3, 2, 0],
              [0, 1, 2, 3],
              [2, 0, 3, 1]]])

            >>> print(out2)
            Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[[0, 1, 1, 1],
              [0, 0, 0, 0],
              [1, 1, 1, 0]],
             [[1, 0, 0, 0],
              [1, 1, 1, 1],
              [0, 0, 0, 1]]])

            >>> print(out3)
            Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[[1, 1, 1, 2],
              [0, 0, 2, 0],
              [2, 2, 0, 1]],
             [[2, 0, 2, 0],
              [1, 1, 0, 2],
              [0, 2, 1, 1]]])
    x)float16float32float64int16int32int64uint8argsortTdtypestop_gradientr   XOutZIndicesaxis
descendingtypeinputsoutputsattrsN)r   )r   r   r   r   r	   locals"create_variable_for_type_inferencer   r   VarTypeINT64	append_op)r   r    r!   name_idshelperout r1   U/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/tensor/search.pyr   '   s.   ?	r   r   c           
      C   s   |durt |tttjjfstdt| |du rtdt	|}d}|du r,d}d}t
 r8t| ||||S tdi t }t| dg d	d
 t|dddgd i }||}	||d< ||d< ||d< ||d< |jdd| id|	gi|d d|	_|	S )ai  
    Computes the indices of the max elements of the input tensor's
    element along the provided axis.

    Args:
        x (Tensor): An input N-D Tensor with type float16, float32, float64, int16,
            int32, int64, uint8.
        axis (int, optional): Axis to compute indices along. The effective range
            is [-R, R), where R is x.ndim. when axis < 0, it works the same way
            as axis + R. Default is None, the input `x` will be into the flatten tensor, and selecting the min value index.
        keepdim (bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimentions is one fewer than x since the axis is squeezed. Default is False.
        dtype (str|np.dtype, optional): Data type of the output tensor which can
                    be int32, int64. The default value is ``int64`` , and it will
                    return the int64 indices.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        Tensor, return the tensor of int32 if set :attr:`dtype` is int32, otherwise return the tensor of int64.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[5,8,9,5],
            ...                       [0,0,1,7],
            ...                       [6,9,2,4]])
            >>> out1 = paddle.argmax(x)
            >>> print(out1.numpy())
            2
            >>> out2 = paddle.argmax(x, axis=0)
            >>> print(out2.numpy())
            [2 2 0 1]
            >>> out3 = paddle.argmax(x, axis=-1)
            >>> print(out3.numpy())
            [2 3 1]
            >>> out4 = paddle.argmax(x, axis=0, keepdim=True)
            >>> print(out4.numpy())
            [[2 2 0 1]]
    NzMThe type of 'axis'  must be int or Tensor or None in argmax, but received %s.zCthe value of 'dtype' in argmax could not be None, but received NoneFTr   argmaxr   uint16r   r   r   r   r   r   r   zpaddle.argmaxr   r   r   argminkeepdimsr    flattenZarg_maxr   r   r"   )r3   )
isinstanceintr   paddlepirOpResult	TypeErrorr#   
ValueErrorr
   r   r   r3   r	   r'   r   r   r(   r+   r   )
r   r    keepdimr   r,   	var_dtyper8   r/   r&   r0   r1   r1   r2   r3      sL   
)

r3   c           
      C   s   |durt |tttjjfstdt| |du rtdt	|}d}|du r,d}d}t
 r8t| ||||S tdi t }t| dg d	d
 t|dddgd ||}i }	||	d< ||	d< ||	d< ||	d< |jdd| id|gi|	d d|_|S )af  
    Computes the indices of the min elements of the input tensor's
    element along the provided axis.

    Args:
        x (Tensor): An input N-D Tensor with type float16, float32, float64, int16,
            int32, int64, uint8.
        axis (int, optional): Axis to compute indices along. The effective range
            is [-R, R), where R is x.ndim. when axis < 0, it works the same way
            as axis + R. Default is None, the input `x` will be into the flatten tensor, and selecting the min value index.
        keepdim (bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimentions is one fewer than x since the axis is squeezed. Default is False.
        dtype (str, optional): Data type of the output tensor which can
                    be int32, int64. The default value is 'int64', and it will
                    return the int64 indices.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        Tensor, return the tensor of `int32` if set :attr:`dtype` is `int32`, otherwise return the tensor of `int64`.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x =  paddle.to_tensor([[5,8,9,5],
            ...                        [0,0,1,7],
            ...                        [6,9,2,4]])
            >>> out1 = paddle.argmin(x)
            >>> print(out1.numpy())
            4
            >>> out2 = paddle.argmin(x, axis=0)
            >>> print(out2.numpy())
            [1 1 1 2]
            >>> out3 = paddle.argmin(x, axis=-1)
            >>> print(out3.numpy())
            [0 0 2]
            >>> out4 = paddle.argmin(x, axis=0, keepdim=True)
            >>> print(out4.numpy())
            [[1 1 1 2]]
    NzMThe type of 'axis'  must be int or Tensor or None in argmin, but received %s.zCthe value of 'dtype' in argmin could not be None, but received NoneFTr   r6   r   r4   zpaddle.argminr   r   r   r7   r    r8   Zarg_minr   r   r"   )r6   )r9   r:   r   r;   r<   r=   r>   r#   r?   r
   r   r   r6   r	   r'   r   r   r(   r+   r   )
r   r    r@   r   r,   rA   r8   r/   r0   r&   r1   r1   r2   r6      sL   
)

r6   c                 C   sx   t  r
t| ||S tdi t }t| dg dd t|dddgd || j}|jd| |dd	|id
|id |S )av  

    Returns a new tensor which indexes the ``input`` tensor along dimension ``axis`` using
    the entries in ``index`` which is a Tensor. The returned tensor has the same number
    of dimensions as the original ``x`` tensor. The dim-th dimension has the same
    size as the length of ``index``; other dimensions have the same size as in the ``x`` tensor.

    Args:
        x (Tensor): The input Tensor to be operated. The data of ``x`` can be one of float16, float32, float64, int32, int64, complex64 and complex128.
        index (Tensor): The 1-D Tensor containing the indices to index. The data type of ``index`` must be int32 or int64.
        axis (int, optional): The dimension in which we index. Default: if None, the ``axis`` is 0.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        Tensor: A Tensor with same data type as ``x``.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0],
            ...                       [5.0, 6.0, 7.0, 8.0],
            ...                       [9.0, 10.0, 11.0, 12.0]])
            >>> index = paddle.to_tensor([0, 1, 1], dtype='int32')
            >>> out_z1 = paddle.index_select(x=x, index=index)
            >>> print(out_z1.numpy())
            [[1. 2. 3. 4.]
             [5. 6. 7. 8.]
             [5. 6. 7. 8.]]
            >>> out_z2 = paddle.index_select(x=x, index=index, axis=1)
            >>> print(out_z2.numpy())
            [[ 1.  2.  2.]
             [ 5.  6.  6.]
             [ 9. 10. 10.]]
    index_selectr   r5   r   r   r   r   r   Z	complex64Z
complex128z!paddle.tensor.search.index_selectindexr   r   r   Indexr   dimr"   N)rB   )	r   r   rB   r	   r'   r   r(   r   r+   )r   rD   r    r,   r/   r0   r1   r1   r2   rB   C  s.   &
rB   c              	   C   s   g }| j }t|}t rt| }n't| dg dd tdi t }|jt	j
jjd}|jdd| id|gid |s=|S |dkrD|fS t|D ]}|tj|dg|g|d gd	 qHt|S )a  
    Return a tensor containing the indices of all non-zero elements of the `input`
    tensor. If as_tuple is True, return a tuple of 1-D tensors, one for each dimension
    in `input`, each containing the indices (in that dimension) of all non-zero elements
    of `input`. Given a n-Dimensional `input` tensor with shape [x_1, x_2, ..., x_n], If
    as_tuple is False, we can get a output tensor with shape [z, n], where `z` is the
    number of all non-zero elements in the `input` tensor. If as_tuple is True, we can get
    a 1-D tensor tuple of length `n`, and the shape of each 1-D tensor is [z, 1].

    Args:
        x (Tensor): The input tensor variable.
        as_tuple (bool, optional): Return type, Tensor or tuple of Tensor.

    Returns:
        Tensor. The data type is int64.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> x1 = paddle.to_tensor([[1.0, 0.0, 0.0],
            ...                        [0.0, 2.0, 0.0],
            ...                        [0.0, 0.0, 3.0]])
            >>> x2 = paddle.to_tensor([0.0, 1.0, 0.0, 3.0])
            >>> out_z1 = paddle.nonzero(x1)
            >>> print(out_z1)
            Tensor(shape=[3, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0, 0],
             [1, 1],
             [2, 2]])

            >>> out_z1_tuple = paddle.nonzero(x1, as_tuple=True)
            >>> for out in out_z1_tuple:
            ...     print(out)
            Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0],
             [1],
             [2]])
            Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0],
             [1],
             [2]])

            >>> out_z2 = paddle.nonzero(x2)
            >>> print(out_z2)
            Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[1],
             [3]])

            >>> out_z2_tuple = paddle.nonzero(x2, as_tuple=True)
            >>> for out in out_z2_tuple:
            ...     print(out)
            Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[1],
             [3]])

    r   )r   r   r   r5   r   r   r   boolwhere_indexr   	Conditionr   r#   r$   r%      )ZaxesZstartsZendsN)rI   )shapelenr   r   nonzeror   r	   r'   r(   r   r   r)   r*   r+   rangeappendr;   slicetuple)r   as_tupleZlist_outrN   rankoutsr/   ir1   r1   r2   rP     s6   <
rP   c           	      C   st   t  rt| ||\}}|S tdi t }|j| jdd}|jtjj	dd}|j
dd| i||d||d	d
 |S )ae  

    Sorts the input along the given axis, and returns the sorted output tensor. The default sort algorithm is ascending, if you want the sort algorithm to be descending, you must set the :attr:`descending` as True.

    Args:
        x (Tensor): An input N-D Tensor with type float32, float64, int16,
            int32, int64, uint8.
        axis (int, optional): Axis to compute indices along. The effective range
            is [-R, R), where R is Rank(x). when axis<0, it works the same way
            as axis+R. Default is -1.
        descending (bool, optional) : Descending is a flag, if set to true,
            algorithm will sort by descending order, else sort by
            ascending order. Default is false.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        Tensor: sorted tensor(with the same shape and data type as ``x``).
    Examples:

        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[[5,8,9,5],
            ...                        [0,0,1,7],
            ...                        [6,9,2,4]],
            ...                       [[5,2,4,2],
            ...                        [4,7,7,9],
            ...                        [1,7,0,6]]],
            ...                      dtype='float32')
            >>> out1 = paddle.sort(x=x, axis=-1)
            >>> out2 = paddle.sort(x=x, axis=0)
            >>> out3 = paddle.sort(x=x, axis=1)
            >>> print(out1.numpy())
            [[[5. 5. 8. 9.]
              [0. 0. 1. 7.]
              [2. 4. 6. 9.]]
             [[2. 2. 4. 5.]
              [4. 7. 7. 9.]
              [0. 1. 6. 7.]]]
            >>> print(out2.numpy())
            [[[5. 2. 4. 2.]
              [0. 0. 1. 7.]
              [1. 7. 0. 4.]]
             [[5. 8. 9. 5.]
              [4. 7. 7. 9.]
              [6. 9. 2. 6.]]]
            >>> print(out3.numpy())
            [[[0. 0. 1. 4.]
              [5. 8. 2. 5.]
              [6. 9. 9. 7.]]
             [[1. 2. 0. 2.]
              [4. 7. 4. 6.]
              [5. 7. 7. 9.]]]
    sortFr   Tr   r   r   r   r   r"   N)rY   )r   r   r   r	   r'   r(   r   r   r)   r*   r+   )	r   r    r!   r,   rW   r-   r/   r0   r.   r1   r1   r2   rY     s"   8rY   c           	      C   s   t  r
t| ||S tdi t }d| gi}i }||d< ||d< |j| jd}|jdd}|jd||g|gd|d d	|_||fS )a  
    Used to find values and indices of the modes at the optional axis.

    Args:
        x (Tensor): Tensor, an input N-D Tensor with type float32, float64, int32, int64.
        axis (int, optional): Axis to compute indices along. The effective range
            is [-R, R), where R is x.ndim. when axis < 0, it works the same way
            as axis + R. Default is -1.
        keepdim (bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimentions is one fewer than x since the axis is squeezed. Default is False.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        tuple (Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> tensor = paddle.to_tensor([[[1,2,2],[2,3,3]],[[0,5,5],[9,9,0]]], dtype=paddle.float32)
            >>> res = paddle.mode(tensor, 2)
            >>> print(res)
            (Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[2., 3.],
             [5., 9.]]), Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[2, 2],
             [2, 1]]))

    moder   r    r@   rJ   r   r   r"   TN)rZ   )	r   r   rZ   r	   r'   r(   r   r+   r   )	r   r    r@   r,   r/   r$   r&   valuesindicesr1   r1   r2   rZ   C  s"   
rZ   c                 C   s  t |rtdg|t |gjj}t |r&tdg|t |gjj}|du r4|du r4t| ddS |du s<|du r@tdt	| j
}t	|j
}t	|j
}||kr^||kr^| }|}|}	nAt|}
t|}t| }t||j}t| |j}t|
|}t||}t||}t||}	t||}t|d}t rt|||	S t| ddgd t|d	g d
d t|dg d
d tdi t }|j|jd}|jd|||	dd|gid |S )a  
    Return a Tensor of elements selected from either :attr:`x` or :attr:`y` according to corresponding elements of :attr:`condition`. Concretely,

    .. math::

        out_i =
        \begin{cases}
        x_i, & \text{if}  \ condition_i \  \text{is} \ True \\
        y_i, & \text{if}  \ condition_i \  \text{is} \ False \\
        \end{cases}.

    Notes:
        ``numpy.where(condition)`` is identical to ``paddle.nonzero(condition, as_tuple=True)``, please refer to :ref:`api_paddle_nonzero`.

    Args:
        condition (Tensor): The condition to choose x or y. When True (nonzero), yield x, otherwise yield y.
        x (Tensor|scalar, optional): A Tensor or scalar to choose when the condition is True with data type of bfloat16, float16, float32, float64, int32 or int64. Either both or neither of x and y should be given.
        y (Tensor|scalar, optional): A Tensor or scalar to choose when the condition is False with data type of bfloat16, float16, float32, float64, int32 or int64. Either both or neither of x and y should be given.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        Tensor: A Tensor with the same shape as :attr:`condition` and same data type as :attr:`x` and :attr:`y`.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([0.9383, 0.1983, 3.2, 1.2])
            >>> y = paddle.to_tensor([1.0, 1.0, 1.0, 1.0])

            >>> out = paddle.where(x>1, x, y)
            >>> print(out)
            Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
            [1.        , 1.        , 3.20000005, 1.20000005])

            >>> out = paddle.where(x>1)
            >>> print(out)
            (Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[2],
             [3]]),)
    rM   NT)rU   1either both or neither of x and y should be givenrH   	conditionwherer   )r5   r   r   r   r   r   yrJ   )rK   r   Yr   rL   )r_   )npisscalarr;   fullarrayr   r,   rP   r?   listrN   
zeros_likecastaddr   r   r_   r   r	   r'   r(   r+   )r^   r   r`   r,   condition_shapex_shapey_shapebroadcast_conditionbroadcast_xbroadcast_yzeros_like_xzeros_like_yzeros_like_condition	cast_condbroadcast_zerosr/   r0   r1   r1   r2   r_   x  sh   
,







r_   c                 C   s  t |s
t |rtd|du s|du rtdt| j}t|j}t|j}||kr8||kr8| }|}|}	n@t|}
t|}t| }t||j}t| |j}t	|
|}t	||}|
|}t	||}	t	||}t|d}t rt|||	S dS )z
    Inplace version of ``where`` API, the output Tensor will be inplaced with input ``x``.
    Please refer to :ref:`api_paddle_where`.
    r]   NrH   )rb   rc   r?   rf   rN   r;   rg   rh   r   ri   Zadd_r   r   where_)r^   r   r`   r,   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   r1   r1   r2   ru     s2   






ru   c                 C   sr   t  r	t| |S tdi t }t| dg dd t|dddgd |j| jd}|jd| |d	d
|id |S )a  
    **IndexSample Layer**

    IndexSample OP returns the element of the specified location of X,
    and the location is specified by Index.

    .. code-block:: text


                Given:

                X = [[1, 2, 3, 4, 5],
                     [6, 7, 8, 9, 10]]

                Index = [[0, 1, 3],
                         [0, 2, 4]]

                Then:

                Out = [[1, 2, 4],
                       [6, 8, 10]]

    Args:
        x (Tensor): The source input tensor with 2-D shape. Supported data type is
            int32, int64, bfloat16, float16, float32, float64, complex64, complex128.
        index (Tensor): The index input tensor with 2-D shape, first dimension should be same with X.
            Data type is int32 or int64.

    Returns:
        output (Tensor): The output is a tensor with the same shape as index.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0],
            ...                       [5.0, 6.0, 7.0, 8.0],
            ...                       [9.0, 10.0, 11.0, 12.0]], dtype='float32')
            >>> index = paddle.to_tensor([[0, 1, 2],
            ...                           [1, 2, 3],
            ...                           [0, 0, 0]], dtype='int32')
            >>> target = paddle.to_tensor([[100, 200, 300, 400],
            ...                            [500, 600, 700, 800],
            ...                            [900, 1000, 1100, 1200]], dtype='int32')
            >>> out_z1 = paddle.index_sample(x, index)
            >>> print(out_z1.numpy())
            [[1. 2. 3.]
             [6. 7. 8.]
             [9. 9. 9.]]

            >>> # Use the index of the maximum value by topk op
            >>> # get the value of the element of the corresponding index in other tensors
            >>> top_value, top_index = paddle.topk(x, k=2)
            >>> out_z2 = paddle.index_sample(target, top_index)
            >>> print(top_value.numpy())
            [[ 4.  3.]
             [ 8.  7.]
             [12. 11.]]

            >>> print(top_index.numpy())
            [[3 2]
             [3 2]
             [3 2]]

            >>> print(out_z2.numpy())
            [[ 400  300]
             [ 800  700]
             [1200 1100]]

    index_sampler   rC   z!paddle.tensor.search.index_samplerD   r   r   rJ   rE   r   rL   N)rv   )	r   r   rv   r	   r'   r   r(   r   r+   )r   rD   r/   r0   r1   r1   r2   rv     s,   I
rv   c                 C   sp   t  r	t| |S t| dg dd t|ddgd tdi t }|j| jd}|jd| |d	d
|id |S )a|  
    Returns a new 1-D tensor which indexes the input tensor according to the ``mask``
    which is a tensor with data type of bool.

    Args:
        x (Tensor): The input Tensor, the data type can be int32, int64, uint16, float16, float32, float64.
        mask (Tensor): The Tensor containing the binary mask to index with, it's data type is bool.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        A 1-D Tensor which is the same data type  as ``x``.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0],
            ...                       [5.0, 6.0, 7.0, 8.0],
            ...                       [9.0, 10.0, 11.0, 12.0]])
            >>> mask = paddle.to_tensor([[True, False, False, False],
            ...                          [True, True, False, False],
            ...                          [True, False, False, False]])
            >>> out = paddle.masked_select(x, mask)
            >>> print(out.numpy())
            [1. 5. 6. 9.]
    r   )r   r   r   r   r   r5   z paddle.tensor.search.mask_selectmaskrH   z"paddle.tensor.search.masked_selectmasked_selectrJ   )r   Maskra   rL   N)rx   )	r   r   rx   r   r	   r'   r(   r   r+   )r   rw   r,   r/   r0   r1   r1   r2   rx   w  s&   
rx   Tc                 C   s   t  r|du r	d}t| ||||\}}||fS tdi t }d| gi}	i }
t|tr2|g|	d< nd|i}
||
d< ||
d< |durF||
d	< |j| jd
}|jdd
}|j	d|	|g|gd|
d d|_
||fS )a  
    Return values and indices of the k largest or smallest at the optional axis.
    If the input is a 1-D Tensor, finds the k largest or smallest values and indices.
    If the input is a Tensor with higher rank, this operator computes the top k values and indices along the :attr:`axis`.

    Args:
        x (Tensor): Tensor, an input N-D Tensor with type float32, float64, int32, int64.
        k (int, Tensor): The number of top elements to look for along the axis.
        axis (int, optional): Axis to compute indices along. The effective range
            is [-R, R), where R is x.ndim. when axis < 0, it works the same way
            as axis + R. Default is -1.
        largest (bool, optional) : largest is a flag, if set to true,
            algorithm will sort by descending order, otherwise sort by
            ascending order. Default is True.
        sorted (bool, optional): controls whether to return the elements in sorted order, default value is True. In gpu device, it always return the sorted value.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> data_1 = paddle.to_tensor([1, 4, 5, 7])
            >>> value_1, indices_1 = paddle.topk(data_1, k=1)
            >>> print(value_1)
            Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [7])
            >>> print(indices_1)
            Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [3])

            >>> data_2 = paddle.to_tensor([[1, 4, 5, 7], [2, 6, 2, 5]])
            >>> value_2, indices_2 = paddle.topk(data_2, k=1)
            >>> print(value_2)
            Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[7],
             [6]])
            >>> print(indices_2)
            Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[3],
             [1]])

            >>> value_3, indices_3 = paddle.topk(data_2, k=1, axis=-1)
            >>> print(value_3)
            Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[7],
             [6]])
            >>> print(indices_3)
            Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[3],
             [1]])

            >>> value_4, indices_4 = paddle.topk(data_2, k=1, axis=0)
            >>> print(value_4)
            Tensor(shape=[1, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[2, 6, 5, 7]])
            >>> print(indices_4)
            Tensor(shape=[1, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[1, 1, 0, 0]])


    Nr   top_k_v2r   Kklargestsortedr    rJ   r   r   r"   T)rz   )r   r   topkr	   r'   r9   r   r(   r   r+   r   )r   r|   r    r}   r~   r,   r0   r\   r/   r$   r&   r[   r1   r1   r2   r     s2   D

r   c                 C   s@   t |dg dd | dkrtd|  t|| |||S )aj	  
    This API is used to find the index of the corresponding 1D tensor `sorted_sequence` in the innermost dimension based on the given `x`.

    Args:
        x (Tensor): An input N-D tensor value with type int32, int64, float32, float64.
        sorted_sequence (Tensor): An input 1-D tensor with type int32, int64, float32, float64. The value of the tensor monotonically increases in the innermost dimension.
        out_int32 (bool, optional): Data type of the output tensor which can be int32, int64. The default value is False, and it indicates that the output data type is int64.
        right (bool, optional): Find the upper or lower bounds of the sorted_sequence range in the innermost dimension based on the given `x`. If the value of the sorted_sequence is nan or inf, return the size of the innermost dimension.
                               The default value is False and it shows the lower bounds.
        name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor (the same sizes of the `x`), return the tensor of int32 if set :attr:`out_int32` is True, otherwise return the tensor of int64.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> sorted_sequence = paddle.to_tensor([2, 4, 8, 16], dtype='int32')
            >>> x = paddle.to_tensor([[0, 8, 4, 16], [-1, 2, 8, 4]], dtype='int32')
            >>> out1 = paddle.bucketize(x, sorted_sequence)
            >>> print(out1)
            Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0, 2, 1, 3],
             [0, 0, 2, 1]])
            >>> out2 = paddle.bucketize(x, sorted_sequence, right=True)
            >>> print(out2)
            Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0, 3, 2, 4],
             [0, 1, 3, 2]])
            >>> out3 = x.bucketize(sorted_sequence)
            >>> print(out3)
            Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0, 2, 1, 3],
             [0, 0, 2, 1]])
            >>> out4 = x.bucketize(sorted_sequence, right=True)
            >>> print(out4)
            Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0, 3, 2, 4],
             [0, 1, 3, 2]])

    SortedSequencer   r   r   r   paddle.searchsortedrM   z8sorted_sequence tensor must be 1 dimension, but got dim )r   rG   r?   searchsorted)r   sorted_sequence	out_int32rightr,   r1   r1   r2   	bucketize  s   -r   c                 C   s   t  rt| |||S t| dg dd t|dg dd tdi t }|r)dnd}|j|d}|jd| |d	d
|i||dd |S )a	  
    Find the index of the corresponding `sorted_sequence` in the innermost dimension based on the given `values`.

    Args:
        sorted_sequence (Tensor): An input N-D or 1-D tensor with type int32, int64, float32, float64. The value of the tensor monotonically increases in the innermost dimension.
        values (Tensor): An input N-D tensor value with type int32, int64, float32, float64.
        out_int32 (bool, optional): Data type of the output tensor which can be int32, int64. The default value is False, and it indicates that the output data type is int64.
        right (bool, optional): Find the upper or lower bounds of the sorted_sequence range in the innermost dimension based on the given `values`. If the value of the sorted_sequence is nan or inf, return the size of the innermost dimension.
                               The default value is False and it shows the lower bounds.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        Tensor (the same sizes of the `values`), return the tensor of int32 if set :attr:`out_int32` is True, otherwise return the tensor of int64.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> sorted_sequence = paddle.to_tensor([[1, 3, 5, 7, 9, 11],
            ...                                     [2, 4, 6, 8, 10, 12]], dtype='int32')
            >>> values = paddle.to_tensor([[3, 6, 9, 10], [3, 6, 9, 10]], dtype='int32')
            >>> out1 = paddle.searchsorted(sorted_sequence, values)
            >>> print(out1)
            Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[1, 3, 4, 5],
             [1, 2, 4, 4]])
            >>> out2 = paddle.searchsorted(sorted_sequence, values, right=True)
            >>> print(out2)
            Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[2, 3, 5, 5],
             [1, 3, 4, 5]])
            >>> sorted_sequence_1d = paddle.to_tensor([1, 3, 5, 7, 9, 11, 13])
            >>> out3 = paddle.searchsorted(sorted_sequence_1d, values)
            >>> print(out3)
            Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[1, 3, 4, 5],
             [1, 3, 4, 5]])

    r   r   r   Valuesr   r   r   rJ   )r   r   r   )r   r   r"   N)r   )r   r   r   r   r	   r'   r(   r+   )r   r[   r   r   r,   r/   Zout_typer0   r1   r1   r2   r   G  s0   ,r   c           
      C   s   t  r|durt| |||S t| |d|S tdi t }d| gi}d|i}|dur0||d< |j| jd}|jdd}	|jd||g|	gd	|d
 d|	_||	fS )aQ  
    Find values and indices of the k-th smallest at the axis.

    Args:
        x (Tensor): A N-D Tensor with type float16, float32, float64, int32, int64.
        k (int): The k for the k-th smallest number to look for along the axis.
        axis (int, optional): Axis to compute indices along. The effective range
            is [-R, R), where R is x.ndim. when axis < 0, it works the same way
            as axis + R. The default is None. And if the axis is None, it will computed as -1 by default.
        keepdim (bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimentions is one fewer than x since the axis is squeezed. Default is False.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> x = paddle.randn((2,3,2))
            >>> print(x)
            >>> # doctest: +SKIP('Different environments yield different output.')
            Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[[ 0.11855337, -0.30557564],
              [-0.09968963,  0.41220093],
              [ 1.24004936,  1.50014710]],
             [[ 0.08612321, -0.92485696],
              [-0.09276631,  1.15149164],
              [-1.46587241,  1.22873247]]])
            >>> # doctest: -SKIP
            >>> y = paddle.kthvalue(x, 2, 1)
            >>> print(y)
            >>> # doctest: +SKIP('Different environments yield different output.')
            (Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[ 0.11855337,  0.41220093],
             [-0.09276631,  1.15149164]]), Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0, 1],
             [1, 1]]))
            >>> # doctest: -SKIP
    Nr   kthvaluer   r|   r    rJ   r   r   r"   T)r   )	r   r   r   r	   r'   r(   r   r+   r   )
r   r|   r    r@   r,   r/   r$   r&   r[   r\   r1   r1   r2   r     s&   +
r   c           
      C   s   |du rd}t  rt| |||S | ||d}d|i}td
i t }|j| jd}|jdd}	|jd|||	d|d	 ||	fS )a  
    Get the TopP scores and ids according to the cumulative threshold `ps`.

    Args:
        x(Tensor): A N-D Tensor with type float32, float16 and bfloat16.
        ps(Tensor): A 1-D Tensor with type float32, float16 and bfloat16.
            it is the cumulative probalitity threshold to limit low probality input.
        threshold(Tensor): A 1-D Tensor with type float32, float16 and bfloat16.
            it is the absolute probability threshold to limit input, it will take effect simultaneously with `ps`, if not set, the default value is 0.f.
        seed(int, optional): the random seed,
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64.

    Examples:

        .. code-block:: python

            >>> # doctest: +REQUIRES(env:GPU)
            >>> import paddle

            >>> paddle.device.set_device('gpu')
            >>> paddle.seed(2023)
            >>> x = paddle.randn([2,3])
            >>> print(x)
            Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
             [[-0.32012719, -0.07942779,  0.26011357],
              [ 0.79003978, -0.39958701,  1.42184138]])
            >>> paddle.seed(2023)
            >>> ps = paddle.randn([2])
            >>> print(ps)
            Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True,
             [-0.32012719, -0.07942779])
            >>> value, index = paddle.tensor.top_p_sampling(x, ps)
            >>> print(value)
            Tensor(shape=[2, 1], dtype=float32, place=Place(gpu:0), stop_gradient=True,
             [[0.26011357],
              [1.42184138]])
            >>> print(index)
            Tensor(shape=[2, 1], dtype=int64, place=Place(gpu:0), stop_gradient=True,
             [[2],
              [2]])
    Nr   )r   ps	thresholdZrandom_seedtop_p_samplingrJ   r   )r0   r.   r"   )r   )r   r   r   r	   r'   r(   r   r+   )
r   r   r   seedr,   r$   r&   r/   r0   r.   r1   r1   r2   r     s    .r   )r   FN)NFr   N)r   N)F)NNN)N)NTTN)FFN)NFN)#numpyrb   r;   r   Zpaddle.common_ops_importr   r   Zpaddle.utils.inplace_utilsr   Zbase.data_feederr   r   Z	frameworkr	   r
   r   r   r   __all__r   r3   r6   rB   rP   rY   rZ   r_   ru   rv   rx   r   r   r   r   r   r1   r1   r1   r2   <module>   s4   

b
]
]
K
i
L
5n$
l
3
c;

IC