o
    Qeȱ                     @   s@  d dl mZ d dlZd dlZddlmZ ddlmZm	Z	m
Z
 ddlmZ ddlmZmZmZ ddlmZ d d	lmZ d d
lmZ d dlmZ d dlmZmZ ddlmZ g Zd/ddZd0ddZd0ddZd1ddZd2ddZd/ddZ d/ddZ!d3d d!Z"d"d# Z#d4d$d%Z$d5d'd(Z%d6d)d*Z&			d6d+d,Z'd7d-d.Z(dS )8    )print_functionN   )LayerHelper)check_variable_and_dtype
check_typecheck_dtype)layers)corein_dygraph_mode_non_static_mode)_in_legacy_dygraph)convert_np_dtype_to_dtype_)Variable)VarDesc)_C_ops_legacy_C_ops   )logical_notFc                 C   s   t  rt| ||\}}|S t rt| d|d|\}}|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 )aI  
    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 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)
            #[[[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)
            #[[[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)
            #[[[1 1 1 2]
            #  [0 0 2 0]
            #  [2 2 0 1]]
            # [[2 0 2 0]
            #  [1 1 0 2]
            #  [0 2 1 1]]]
    axis
descendingxfloat32float64Zint16int32int64Zuint8argsortTdtypestop_gradientr    XOutZIndicesr   r   typeinputsoutputsattrsN)r   )r
   r   r   r   r   r   r   locals"create_variable_for_type_inferencer   r   VarTypeINT64	append_op)r   r   r   name_idshelperout r5   DD:\Projects\ConvertPro\env\Lib\site-packages\paddle/tensor/search.pyr   #   s:   <


r   r   c           
      C   s  |durt |ttfstdt| |du rtdt|}d}|du r)d}d}t r5t	| ||||S t
 rGt| d|d|d	|d
|	}|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 )a  
    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 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) # 2
            out2 = paddle.argmax(x, axis=0)
            print(out2) 
            # [2, 2, 0, 1]
            out3 = paddle.argmax(x, axis=-1)
            print(out3) 
            # [2, 3, 1]
            out4 = paddle.argmax(x, axis=0, keepdim=True)
            print(out4)
            # [[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   r   r   keepdimsflattenargmaxr   r   zpaddle.argmaxr   r   argminarg_maxr"   r$   r&   )r9   )
isinstanceintr   	TypeErrorr'   
ValueErrorr   r
   r   r9   r   r   r;   r   r+   r   r   r,   r/   r    
r   r   keepdimr   r0   Z	var_dtyper8   r4   r3   r*   r5   r5   r6   r9   }   sR   (

r9   c           
      C   s  |durt |ttfstdt| |du rtdt|}d}|du r)d}d}t r5t	| ||||S t
 rGt| d|d|d	|d
|	}|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 )a  
    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 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) # 4
            out2 = paddle.argmin(x, axis=0)
            print(out2) 
            # [1, 1, 1, 2]
            out3 = paddle.argmin(x, axis=-1)
            print(out3) 
            # [0, 0, 2]
            out4 = paddle.argmin(x, axis=0, keepdim=True)
            print(out4)
            # [[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   r   r   r7   r8   r:   r   r   zpaddle.argminr   r   arg_minr"   r$   r&   )r:   )r<   r=   r   r>   r'   r?   r   r
   r   r:   r   r   rB   r   r+   r   r   r,   r/   r    r@   r5   r5   r6   r:      sR   (

r:   c                 C   s   t  r
t| ||S t rt| |d|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 )a  

    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 float32, float64, int32, int64.
        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)
            #[[1. 2. 3. 4.]
            # [5. 6. 7. 8.]
            # [5. 6. 7. 8.]]
            out_z2 = paddle.index_select(x=x, index=index, axis=1)
            #[[ 1.  2.  2.]
            # [ 5.  6.  6.]
            # [ 9. 10. 10.]]
    dimindex_selectr   r   r   r   r   z!paddle.tensor.search.index_selectindexr   r   r"   Indexr$   r&   N)rD   )r
   r   rD   r   r   r   r+   r   r,   r   r/   )r   rF   r   r0   r3   r4   r5   r5   r6   rD   !  s(   $rD   c              	   C   s   g }| j }t|}t rt| }n(t rt| }ntd	i t	 }|j
tjjjd}|jdd| id|gid |s>|S |dkrGt|gS t|D ]}|tj|dg|g|d gd qKt|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): 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)
            #[[0 0]
            # [1 1]
            # [2 2]]
            out_z1_tuple = paddle.nonzero(x1, as_tuple=True)
            for out in out_z1_tuple:
                print(out)
            #[[0]
            # [1]
            # [2]]
            #[[0]
            # [1]
            # [2]]
            out_z2 = paddle.nonzero(x2)
            print(out_z2)
            #[[1]
            # [3]]
            out_z2_tuple = paddle.nonzero(x2, as_tuple=True)
            for out in out_z2_tuple:
                print(out)
            #[[1]
            # [3]]

    where_indexr   	Conditionr$   r'   r(   r)   r   )ZaxesZstartsZendsN)rI   )shapelenr
   r   rI   paddlein_dynamic_moder   r   r+   r,   r	   r   r-   r.   r/   tuplerangeappendslice)r   as_tupleZlist_outrM   Zrankoutsr3   ir5   r5   r6   nonzero]  s0   4
rX   c           	      C   s   t  rt| ||\}}|S t rt| d|d|\}}|S 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 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)
            #[[[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)
            #[[[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)
            #[[[0. 0. 1. 4.]
            #  [5. 8. 2. 5.]
            #  [6. 9. 9. 7.]]
            # [[1. 2. 0. 2.]
            #  [4. 7. 4. 6.]
            #  [5. 7. 7. 9.]]]
    r   r   sortFr   Tr!   r   r"   r#   r%   r&   N)rY   )r
   r   r   r   r   r   r+   r,   r   r   r-   r.   r/   )	r   r   r   r0   rV   r1   r3   r4   r2   r5   r5   r6   rY     s2   8

rY   c           	      C   s   t  r
t| ||S t rt| d|d|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=CUDAPlace(0), stop_gradient=True,
           #   [[2., 3.],
           #    [5., 9.]]), Tensor(shape=[2, 2], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
           #   [[1, 1],
           #    [1, 0]]))
           
    r   rA   moder"   rJ   r   r#   r&   TN)rZ   )r
   r   rZ   r   r   r   r+   r,   r   r/   r    )	r   r   rA   r0   r3   r(   r*   valuesindicesr5   r5   r6   rZ      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	 s^t
| ddgd t
|d	g d
d t
|dg d
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 rt|||	S 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_tensor_search_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 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 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)
            #out: [1.0, 1.0, 3.2, 1.2]
            
            out = paddle.where(x>1)
            print(out)
            #out: (Tensor(shape=[2, 1], dtype=int64, place=CPUPlace, stop_gradient=True,
            #            [[2],
            #             [3]]),)
    r   NT)rU   z1either both or neither of x and y should be given	conditionboolwherer   rE   yrJ   )rK   r"   Yr$   rL   )r_   )npZisscalarrO   fullarrayr   r0   rX   r?   rP   r   listrM   Z
zeros_likecastaddr
   r   r_   r   r   r   r+   r,   r/   )r]   r   r`   r0   Zcondition_shapeZx_shapeZy_shapeZbroadcast_conditionZbroadcast_xZbroadcast_yZzeros_like_xZzeros_like_yZzeros_like_conditionZ	cast_condZbroadcast_zerosr3   r4   r5   r5   r6   r_   8  sh   
+






r_   c                 C   s   t  r	t| |S 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 )at  
    **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, float32, float64.
        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)
            #[[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)
            #[[ 4.  3.]
            # [ 8.  7.]
            # [12. 11.]]

            print(top_index)
            #[[3 2]
            # [3 2]
            # [3 2]]

            print(out_z2)
            #[[ 400  300]
            # [ 800  700]
            # [1200 1100]]

    index_sampler   rE   z!paddle.tensor.search.index_samplerF   r   r   rJ   rG   r$   rL   N)rh   )r
   r   rh   r   r   r   r+   r   r,   r   r/   )r   rF   r3   r4   r5   r5   r6   rh     s(   Irh   c                 C   s   t  r	t| |S t rt| |S tdi t }t| dg dd t|ddgd |j| j	d}|j
d| |d	d
|id |S )a2  
    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, 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)
            #[1.0 5.0 6.0 9.0]
    masked_selectr   rE   z paddle.tensor.search.mask_selectmaskr^   z"paddle.tensor.search.masked_selectrJ   )r"   Maskra   rL   N)ri   )r
   r   ri   r   r   r   r+   r   r,   r   r/   )r   rj   r0   r3   r4   r5   r5   r6   ri     s&   
ri   Tc                 C   s.  t  r|dkr	d}t| ||||\}}||fS t rG|du r2t| dt|d|d|\}}||fS t| dt|d|d|d|	\}}||fS tdi t }d| gi}	i }
t	|t
ra|g|	d	< nd|i}
||
d< ||
d< |duru||
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) # [7]
            print(indices_1) # [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) # [[7], [6]]
            print(indices_2) # [[3], [1]]

            value_3, indices_3 = paddle.topk(data_2, k=1, axis=-1)
            print(value_3) # [[7], [6]]
            print(indices_3) # [[3], [1]]

            value_4, indices_4 = paddle.topk(data_2, k=1, axis=0)
            print(value_4) # [[2, 6, 5, 7]]
            print(indices_4) # [[1, 1, 0, 0]]


    Nr   klargestsortedr   top_k_v2r"   KrJ   r   r#   r&   T)ro   )r
   r   Ztop_kr   r   ro   r=   r   r+   r<   r   r,   r   r/   r    )r   rl   r   rm   rn   r0   r4   r\   r3   r(   r*   r[   r5   r5   r6   topk5  sJ   0

rq   c                 C   s@   t |dg dd | dkrtd|  t|| |||S )u	  
    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=CPUPlace, 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=CPUPlace, 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=CPUPlace, 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=CPUPlace, stop_gradient=True,
            #        [[0, 3, 2, 4],
            #         [0, 1, 3, 2]])
            
    SortedSequencerE   paddle.searchsortedr   z8sorted_sequence tensor must be 1 dimension, but got dim )r   rC   r?   searchsorted)r   sorted_sequence	out_int32rightr0   r5   r5   r6   	bucketize  s   -rx   c                 C   s   t  rt| |||S t rt| |d|d|S t| dg dd t|dg dd tdi t }|r6dnd	}|j|d
}|j	d| |dd|i||dd |S )uX	  
    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=CUDAPlace(0), 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=CUDAPlace(0), 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=CUDAPlace(0), stop_gradient=True,
            #        [[1, 3, 4, 5],
            #         [1, 3, 4, 5]])
            
    rv   rw   rr   rE   rs   Valuesrt   r   r   rJ   )rr   ry   r$   )rv   rw   r&   N)rt   )
r
   r   rt   r   r   r   r   r+   r,   r/   )ru   r[   rv   rw   r0   r3   Zout_typer4   r5   r5   r6   rt     s6   .
rt   c           
   	   C   s   t  r1|durt rt| d|d|d|S t| |||S t r)t| d|d|S t| |d|S tdi t }d| gi}d|i}|durJ||d< |j| jd}|jd	d}	|j	d||g|	gd
|d d|	_
||	fS )a  
    Find values and indices of the k-th smallest at the axis.

    Args:
        x(Tensor): A N-D Tensor with type 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))
            # Tensor(shape=[2, 3, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
            #       [[[ 0.22954939, -0.01296274],
            #         [ 1.17135799, -0.34493217],
            #         [-0.19550551, -0.17573971]],
            #
            #        [[ 0.15104349, -0.93965352],
            #         [ 0.14745511,  0.98209465],
            #         [ 0.10732264, -0.55859774]]])           
            y = paddle.kthvalue(x, 2, 1)    
            # (Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
            # [[ 0.22954939, -0.17573971],
            #  [ 0.14745511, -0.55859774]]), Tensor(shape=[2, 2], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
            #  [[0, 2],
            #  [1, 2]]))
    Nrl   r   rA   r   kthvaluer"   rJ   r   r#   r&   T)rz   )r   r   r   rz   r   r   r+   r,   r   r/   r    )
r   rl   r   rA   r0   r3   r(   r*   r[   r\   r5   r5   r6   rz     s4   &
rz   )r   FN)NFr   N)r   N)F)NNN)N)NTTN)FFN)NFN))
__future__r   numpyrb   rO   Z	frameworkr   Zfluid.data_feederr   r   r   Zfluidr   r	   r
   r   Zfluid.frameworkr   Zpaddle.common_ops_importr   r   r   r   r   Zlogicr   __all__r   r9   r:   rD   rX   rY   rZ   r_   rh   ri   rq   rx   rt   rz   r5   r5   r5   r6   <module>   s>   

Z
R
R
<
Q
R
8k
`
2
Z9
M