
    |j                       U d dl mZ d dlZd dlmZmZ d dlmZmZ d dl	Z	d dl	m
Z
 d dlmZmZ d dlmZmZmZ dd	l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 erd dlm Z  d dl	m!Z! d dl"m#Z# ed         Z$de%d<   g Z& eddgddg          	 	 	 dMddddNd&            Z' edgdgd'          	 	 	 	 dOddd(dPd-            Z(	 	 	 	 dQdRd/Z)dSdTd0Z*e	 	 	 dUdVd6            Z+e	 	 	 	 dWdXd8            Z+	 	 	 	 dYd:Z+e	 	 	 	 dWd1d;dZd=            Z,e	 	 	 	 dWd[d?            Z, eddgddgd3d@g          	 	 	 	 dYdd;dA            Z,	 	 	 	 	 d\d]dHZ- eddgddg          	 	 	 	 d^dd;d_dJ            Z.	 	 	 d`dadLZ/dS )b    )annotationsN)TYPE_CHECKINGLiteral)	TypeAliasoverload)_C_ops)in_dynamic_modein_dynamic_or_pir_mode)ParamAliasDecoratorparam_two_aliasparam_two_alias_one_default   )
check_typecheck_variable_and_dtype)Variable)LayerHelperconvert_np_dtype_to_dtype_core   )cast)_get_reduce_axis_with_tensor)Sequence)Tensor)	DTypeLike)linearhigherlowermidpointnearestr   _InterpolationxinputaxisdimF)dtypeoutr   int | Sequence[int] | Nonekeepdimboolname
str | Noner%   DTypeLike | Noner&   Tensor | Nonereturnc                  |Ut          |t          j        j        t          j        f          st          |          }| j        |k    rt          | |          } t                      rt          j
        | |||          S t          ||           \  }}t          | dg dd           t          |dt          t          t           t"          fd           t          |t          t           f          r#|D ] }t          |dt          t"          fd           !t%          di t'                      }|||d	}	|                    | j                  }
|                    d
d| id|
i|	           |
S )aX  
    Computes the mean of the input tensor's elements along ``axis``.

    Args:
        x (Tensor): The input Tensor with data type bool, bfloat16, float16, float32,
            float64, int32, int64, complex64, complex128.
            alias: ``input``
        axis (int|list|tuple|None, optional): The axis along which to perform mean
            calculations. ``axis`` should be int, list(int) or tuple(int). If
            ``axis`` is a list/tuple of dimension(s), mean is calculated along
            all element(s) of ``axis`` . ``axis`` or element(s) of ``axis``
            should be in range [-D, D), where D is the dimensions of ``x`` . If
            ``axis`` or element(s) of ``axis`` is less than 0, it works the
            same way as :math:`axis + D` . If ``axis`` is None, mean is
            calculated over all elements of ``x``. Default is None.
            alias: ``dim``
        keepdim (bool, optional): Whether to reserve the reduced dimension(s)
            in the output Tensor. If ``keepdim`` is True, the dimensions of
            the output Tensor is the same as ``x`` except in the reduced
            dimensions(it is of size 1 in this case). Otherwise, the shape of
            the output Tensor is squeezed in ``axis`` . Default is False.
        name (str|None, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
        dtype (str): The desired data type of returned tensor. Default: None.
        out(Tensor|None, optional): The output tensor. Default: None.

    Returns:
        Tensor, results of average along ``axis`` of ``x``, with the same data
        type as ``x``.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[[1., 2., 3., 4.],
            ...                        [5., 6., 7., 8.],
            ...                        [9., 10., 11., 12.]],
            ...                       [[13., 14., 15., 16.],
            ...                        [17., 18., 19., 20.],
            ...                        [21., 22., 23., 24.]]])
            >>> out1 = paddle.mean(x)
            >>> print(out1.numpy())
            12.5
            >>> out2 = paddle.mean(x, axis=-1)
            >>> print(out2.numpy())
            [[ 2.5  6.5 10.5]
             [14.5 18.5 22.5]]
            >>> out3 = paddle.mean(x, axis=-1, keepdim=True)
            >>> print(out3.numpy())
            [[[ 2.5]
              [ 6.5]
              [10.5]]
             [[14.5]
              [18.5]
              [22.5]]]
            >>> out4 = paddle.mean(x, axis=[0, 2])
            >>> print(out4.numpy())
            [ 8.5 12.5 16.5]
            >>> out5 = paddle.mean(x, dtype='float64')
            >>> out5
            Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=True,
                12.50000000)
    Nr&   zx/input)	r)   uint16float16float32float64int32int64	complex64
complex128zmean/reduce_meanzaxis/dimzelements of axis/dimmean)r$   keep_dim
reduce_allreduce_meanXOuttypeinputsoutputsattrs)r9   )
isinstancer   VarDescVarTypeDataTyper   r%   r   r
   r   r9   r   r   r   intlisttupler   r   locals"create_variable_for_type_inference	append_op)r!   r#   r(   r*   r%   r&   r;   itemhelperrC   
out_tensors              b/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/tensor/stat.pyr9   r9   4   s   T %$,"6!FGG 	6.u55E7eQA *{1dG55557a@@
D 
 
 
 	
 	
 	
  	*sD%:<N	
 	
 	
 dT5M** 	  *(O&	    00vxx00'LL>>qwGG
8J'	 	 	
 	
 	
     )r!   r#   )
correctionr&   unbiasedbool | NonerS   floatc                  ||dk    rt          d          ||rdnd}nt          |          }t          j                    r,t	                      rt          j        | ||ng ||||          S t                      st          | dg dd	           t          | |d
|          }| j
        t          j        k    rt          j        n| j
        }	t          j        t          j        | |z
  d          ||||	          }
t          j        t          j        |           d          t          j        t          j        |
          d          z  }|                    |	          }|dk    rn||z
  }t          j        |t          j        |                    }t          j                    r.t          j        |dk              rt+          j        dd           n|}d
|_        |
|z  }
d }d| j        v r ||
          }
t3          | j                  dk    r!|dk    rt          j        d|
j                  }
|
j
        | j
        k    r|
                    | j
                  }n|
}|t          j        ||           |S |S )ay	  
    Computes the variance of ``x`` along ``axis`` .

    .. note::
        Alias Support: The parameter name ``input`` can be used as an alias for ``x``, and ``dim`` can be used as an alias for ``axis``.
        For example, ``var(input=tensor_x, dim=1, ...)`` is equivalent to ``var(x=tensor_x, axis=1, ...)``.

    Args:
        x (Tensor): The input Tensor with data type float16, float32, float64.
            alias: ``input``.
        axis (int|list|tuple|None, optional): The axis along which to perform variance calculations. ``axis`` should be int, list(int) or tuple(int).
            alias: ``dim``.

            - If ``axis`` is a list/tuple of dimension(s), variance is calculated along all element(s) of ``axis`` . ``axis`` or element(s) of ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` .
            - If ``axis`` or element(s) of ``axis`` is less than 0, it works the same way as :math:`axis + D` .
            - If ``axis`` is None, variance is calculated over all elements of ``x``. Default is None.

        unbiased (bool, optional): Whether to use the unbiased estimation. If ``unbiased`` is True, the divisor used in the computation is :math:`N - 1`, where :math:`N` represents the number of elements along ``axis`` , otherwise the divisor is :math:`N`. Default is True.
        keep_dim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the input unless keep_dim is true. Default is False.
        name (str|None, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
        correction (int|float, optional): Difference between the sample size and sample degrees of freedom.
            Defaults to 1 (Bessel's correction). If unbiased is specified, this parameter is ignored.
        out (Tensor|None, optional): Output tensor. Default is None.

    Returns:
        Tensor, results of variance along ``axis`` of ``x``, with the same data type as ``x``.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[1.0, 2.0, 3.0], [1.0, 4.0, 5.0]])
            >>> out1 = paddle.var(x)
            >>> print(out1.numpy())
            2.6666667
            >>> out2 = paddle.var(x, axis=1)
            >>> print(out2.numpy())
            [1.         4.3333335]
    Nr   z0Only one of unbiased and correction may be given      ?        r0   r!   r2   r3   r4   varTr   )r(   r*   r%   r6   r   zDegrees of freedom is <= 0.)
stacklevelc                    t          j        |                                 d          }t          j        |                                 |dt          d                                        | j                  }|S )Nr6   r%   r   nan)paddlearangenumel
index_fillflattenrV   reshapeshape)r&   indicesout_nans      rQ   _replace_nanzvar.<locals>._replace_nan  s`    -		7;;;#KKMM7AuU||
 

'#)

 	 rR   )stop_gradient)
ValueErrorrV   r`   is_compiled_with_cudar
   r   r[   r	   r   r9   r%   r2   r3   sumpowr   rb   astypemaximum
zeros_likeanywarningswarnrj   rf   len	to_tensorassign)r!   r#   rT   r(   r*   rS   r&   actual_correctionur%   rP   ncorrected_nri   results                  rQ   r[   r[      s   f 
aKLLL#+4CC!*--#%% 
*@*B*B 
z$DD"
 
 
 	
  
 s555u	
 	
 	
 	QdD!!Ag77FNNQWE
AEAgD  J 	FLOOW--Z  '1 1 	A 	
AA++n*;77
 
 !## 	G
;!3C(D(D 	GM7AFFFF $K+J   	AG||!\*--

17||q.!33%az7OPPP
17""""17++
fc"""
MrR   Tc                L   t                      st          | dg dd           t          j                    rDt                      r6||ng }||rdnd}nt	          |          }t          j        | ||||          S t          di t                      }t          j	        |          S )aP	  
    Computes the standard-deviation of ``x`` along ``axis`` .

    Args:
        x (Tensor): The input Tensor with data type float16, float32, float64.
        axis (int|list|tuple|None, optional): The axis along which to perform
            standard-deviation calculations. ``axis`` should be int, list(int)
            or tuple(int). If ``axis`` is a list/tuple of dimension(s),
            standard-deviation is calculated along all element(s) of ``axis`` .
            ``axis`` or element(s) of ``axis`` should be in range [-D, D),
            where D is the dimensions of ``x`` . If ``axis`` or element(s) of
            ``axis`` is less than 0, it works the same way as :math:`axis + D` .
            If ``axis`` is None, standard-deviation is calculated over all
            elements of ``x``. Default is None.
        unbiased (bool, optional): Whether to use the unbiased estimation. If
            ``unbiased`` is True, the standard-deviation is calculated via the
            unbiased estimator. If ``unbiased`` is True,  the divisor used in
            the computation is :math:`N - 1`, where :math:`N` represents the
            number of elements along ``axis`` , otherwise the divisor is
            :math:`N`. Default is True.
        keepdim (bool, optional): Whether to reserve the reduced dimension(s)
            in the output Tensor. If ``keepdim`` is True, the dimensions of
            the output Tensor is the same as ``x`` except in the reduced
            dimensions(it is of size 1 in this case). Otherwise, the shape of
            the output Tensor is squeezed in ``axis`` . Default is False.
        name (str|None, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor, results of standard-deviation along ``axis`` of ``x``, with the
        same data type as ``x``.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor([[1.0, 2.0, 3.0], [1.0, 4.0, 5.0]])
            >>> out1 = paddle.std(x)
            >>> print(out1.numpy())
            1.6329932
            >>> out2 = paddle.std(x, unbiased=False)
            >>> print(out2.numpy())
            1.490712
            >>> out3 = paddle.std(x, axis=1)
            >>> print(out3.numpy())
            [1.       2.081666]

    r!   rZ   stdNrX   rY    )
r
   r   r`   rl   rV   r   r~   r[   rK   sqrt)r!   r#   rT   r(   r*   rS   r&   s          rQ   r~   r~   +  s    p "## 
 s555u	
 	
 	
 #%% B*@*B*B B'ttR (1cJJz**Jz!T7HjAAA
////C;srR   c                N   t                      rt          j        |           S t          | t                    st          d          t          d	i t                      }|                    t          j
        j        j                  }|                    dd| id|i           |S )
a  
    Returns the number of elements for a tensor, which is a 0-D int64 Tensor with shape [].

    Args:
        x (Tensor): The input Tensor, it's data type can be bool, float16, float32, float64, uint8, int8, int32, int64, complex64, complex128.
        name (str|None, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: The number of elements for the input Tensor, whose shape is [].

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.full(shape=[4, 5, 7], fill_value=0, dtype='int32')
            >>> numel = paddle.numel(x)
            >>> print(numel.numpy())
            140


    zx must be a Tensor in numelrb   r^   sizeInputr>   )r@   rA   rB   N)rb   )r
   r   rb   rD   r   	TypeErrorr   rK   rL   r   rE   rF   INT64rM   )r!   r*   rO   r&   s       rQ   rb   rb   t  s    0  
|A!X&& 	;9:::111177,&, 8 
 
 	fgq\E3<PPP
rR   .rH   modeLiteral['min']tuple[Tensor, Tensor]c                    d S Nr   r!   r#   r(   r   r*   s        rQ   	nanmedianr     s	      CrR   Literal['avg', 'min']c                    d S r   r   r   s        rQ   r   r     	     SrR   avgc                x   t          | t          t          j        j        f          st          d          t          |t          t          f          r"t          |          dk    rt          d          |dvrt          d| d          |duot          |t          t          f           }|g }n=t          |t                    rt          |          }nt          |t                    r|g}t                      r"t          j        | |||          \  }}d|_        nt          | d	g d
d           t!          di t#                      }|||d}	|                    | j                  }|                    t          j                  }|                    dd	| i||d|	           d|_        |dk    r|r||fS |S )a?  
    Compute the median along the specified axis, while ignoring NaNs.

    If the valid count of elements is a even number,
    the average value of both elements in the middle is calculated as the median.

    Args:
        x (Tensor): The input Tensor, it's data type can be int32, int64, float16, bfloat16, float32, float64.
        axis (None|int|list|tuple, optional):
            The axis along which to perform median calculations ``axis`` should be int or list of int.
            ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` .
            If ``axis`` is less than 0, it works the same way as :math:`axis + D`.
            If ``axis`` is None, median is calculated over all elements of ``x``. Default is None.
        keepdim (bool, optional): Whether to reserve the reduced dimension(s)
            in the output Tensor. If ``keepdim`` is True, the dimensions of
            the output Tensor is the same as ``x`` except in the reduced
            dimensions(it is of size 1 in this case). Otherwise, the shape of
            the output Tensor is squeezed in ``axis`` . Default is False.
        mode (str, optional): Whether to use mean or min operation to calculate
            the nanmedian values when the input tensor has an even number of non-NaN elements
            along the dimension ``axis``. Support 'avg' and 'min'. Default is 'avg'.
        name (str|None, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor or tuple of Tensor. If ``mode`` == 'min' and ``axis`` is int, the result
        will be a tuple of two tensors (nanmedian value and nanmedian index). Otherwise,
        only nanmedian value will be returned.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> x = paddle.to_tensor([[float('nan'), 2. , 3. ], [0. , 1. , 2. ]])

            >>> y1 = x.nanmedian()
            >>> print(y1.numpy())
            2.0

            >>> y2 = x.nanmedian(0)
            >>> print(y2.numpy())
            [0.  1.5 2.5]

            >>> y3 = x.nanmedian(0, keepdim=True)
            >>> print(y3.numpy())
            [[0.  1.5 2.5]]

            >>> y4 = x.nanmedian((0, 1))
            >>> print(y4.numpy())
            2.0

            >>> y5 = x.nanmedian(mode='min')
            >>> print(y5.numpy())
            2.0

            >>> y6, y6_index = x.nanmedian(0, mode='min')
            >>> print(y6.numpy())
            [0. 1. 2.]
            >>> print(y6_index.numpy())
            [1 1 1]

            >>> y7, y7_index = x.nanmedian(1, mode='min')
            >>> print(y7.numpy())
            [2. 1.]
            >>> print(y7_index.numpy())
            [1 1]

            >>> y8 = x.nanmedian((0,1), mode='min')
            >>> print(y8.numpy())
            2.0
    *In median, the input x should be a Tensor.r   Axis list should not be empty.r   minMode & is not supported. Must be avg or min.NTr=   )r5   r6   r2   r3   r4   r1   r   )r#   r(   r   )r>   MedianIndexr?   r   )r   )rD   r   r`   pirValuer   rI   rJ   ru   rk   rH   r
   r   r   rj   r   r   rK   rL   r%   r6   rM   )
r!   r#   r(   r   r*   
need_indexr&   rg   rO   rC   s
             rQ   r   r     s   \ a(FJ$4566 FDEEE$u&& ;3t99>>9:::>!!MMMMNNNd"MZtUm-L-L)LJ|	D%	 	  Dzz	D#		 v %'4$??W $ III		
 	
 	
 55FHH55'4@@77@@;;FLII888	 	 	
 	
 	
 !%u}}}G|
rR   r0   tuple[Tensor, Tensor] | Nonec                   d S r   r   )r!   r#   r(   r   r*   r&   s         rQ   medianr   (  s	      CrR   
int | Nonec                    d S r   r   r   s        rQ   r   r   4  r   rR   r   c                  t          | t          t          j        j        f          st          d          t          |t          t          f          r"t          |          dk    rt          d          t          | j
                  }|dk    r|dv s
J d            n3|1t          |t                    r||k     r|| k    st          d          |dvrt          d	| d
          |du}|d}|g }nt          |t                    r|g}|dk    r4| j        t          j        k    s|                     t          j                  } t!          j        | ||||          \  }	}
d|
_        |dk    r|r|	|
fS |	S )a  
    Compute the median along the specified axis.

    .. note::
        Alias Support: The parameter name ``input`` can be used as an alias for ``x``, and ``dim`` can be used as an alias for ``axis``.
        When an alias replacement occurs, the default parameter for mode setting is min instead of avg.
        For example, ``median(input=tensor_x, dim=1, ...)`` is equivalent to ``median(x=tensor_x, axis=1, ...)``.

    Args:
        x (Tensor): The input Tensor, it's data type can be bfloat16, float16, float32, float64, int32, int64.
            alias: ``input``.
        axis (int|None, optional): The axis along which to perform median calculations ``axis`` should be int.
            alias: ``dim``.
            ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` .
            If ``axis`` is less than 0, it works the same way as :math:`axis + D`.
            If ``axis`` is None, median is calculated over all elements of ``x``. Default is None.
        keepdim (bool, optional): Whether to reserve the reduced dimension(s)
            in the output Tensor. If ``keepdim`` is True, the dimensions of
            the output Tensor is the same as ``x`` except in the reduced
            dimensions(it is of size 1 in this case). Otherwise, the shape of
            the output Tensor is squeezed in ``axis`` . Default is False.
        mode (str, optional): Whether to use mean or min operation to calculate
            the median values when the input tensor has an even number of elements
            in the dimension ``axis``. Support 'avg' and 'min'. Default is 'avg'.
            When an alias replacement occurs, the default parameter for mode setting is min instead of avg.
        name (str|None, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor or tuple of Tensor.
        If ``mode`` == 'avg', the result will be the tensor of median values;
        If ``mode`` == 'min' and ``axis`` is None, the result will be the tensor of median values;
        If ``mode`` == 'min' and ``axis`` is not None, the result will be a tuple of two tensors
        containing median values and their indices.

        When ``mode`` == 'avg', if data type of ``x`` is float64, data type of median values will be float64,
        otherwise data type of median values will be float32.
        When ``mode`` == 'min', the data type of median values will be the same as ``x``. The data type of
        indices will be int64.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import numpy as np

            >>> x = paddle.arange(12).reshape([3, 4])
            >>> print(x)
            Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0 , 1 , 2 , 3 ],
             [4 , 5 , 6 , 7 ],
             [8 , 9 , 10, 11]])

            >>> y1 = paddle.median(x)
            >>> print(y1)
            Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
            5.50000000)

            >>> y2 = paddle.median(x, axis=0)
            >>> print(y2)
            Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
            [4., 5., 6., 7.])

            >>> y3 = paddle.median(x, axis=1)
            >>> print(y3)
            Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [1.50000000, 5.50000000, 9.50000000])

            >>> y4 = paddle.median(x, axis=0, keepdim=True)
            >>> print(y4)
            Tensor(shape=[1, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[4., 5., 6., 7.]])

            >>> y5 = paddle.median(x, mode='min')
            >>> print(y5)
            Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
            5)

            >>> median_value, median_indices = paddle.median(x, axis=1, mode='min')
            >>> print(median_value)
            Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
            [1, 5, 9])
            >>> print(median_indices)
            Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
            [1, 1, 1])

            >>> # cases containing nan values
            >>> x = paddle.to_tensor(np.array([[1,float('nan'),3,float('nan')],[1,2,3,4],[float('nan'),1,2,3]]))

            >>> y6 = paddle.median(x, axis=-1, keepdim=True)
            >>> print(y6)
            Tensor(shape=[3, 1], dtype=float64, place=Place(cpu), stop_gradient=True,
            [[nan       ],
             [2.50000000],
             [nan       ]])

            >>> median_value, median_indices = paddle.median(x, axis=1, keepdim=True, mode='min')
            >>> print(median_value)
            Tensor(shape=[3, 1], dtype=float64, place=Place(cpu), stop_gradient=True,
            [[nan],
             [2. ],
             [nan]])
            >>> print(median_indices)
            Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[1],
             [1],
             [0]])
    r   r   r   )r   Nz8when input 0-D, axis can only be [-1, 0] or default NoneNzJIn median, axis should be none or an integer in range [-rank(x), rank(x)).r   r   r   Tr   r0   r   )rD   r   r`   r   r   r   rI   rJ   ru   rk   rf   rH   r%   r4   ro   r3   r   r   rj   )r!   r#   r(   r   r*   r&   dimsneed_idx
is_flattenvaluesrg   s              rQ   r   r   >  s   l a(FJ$4566 FDEEE$u&& ;3t99>>9:::qw<<Dqyy 
 
 
 
 F	
 
 
 

 
	$$$ 	TD[[TdU]]\   >!!MMMMNNN4H|
|	D#		 vu}}QW66HHV^$$mAtWdDDDOFG Gu}}}wrR   r   q'float | Sequence[float] | Tensor | Noneint | list[int] | Noneinterpolation
ignore_nanc                	    t           t          t          j        j        f          st          d          t          |t          t          f          r|g}nt          |t          t          f          r#t          |          dk    rt          d          nxt          |t          t          j        j        f          rCt          |j                  dk    rt          d          t          |j                  dk    r|g}nt          d          |D ]S}t                      s(t          |t          t          j        j        f          r n|dk     s|dk    rt          d          Tdvrt          d	           t           j                  }t           j                  }	t          j                    ddg|z  }	nKt          t                    rg g }}
D ]X}t          |t                    r||k     r|| k    st          d          |dk     r||z   }|
                    |           d|	|<   Yt          t!          t                     d                    }t          j         |
|           t          |          dk    rt          j                    dnlt          j         |d         |d                    |d         nAt          t                    r|k     r| k    st          d          dk     r|z  d|	<                                    }|                                                    d          }g }|D ]}t+                      rt          j        | j                  }|r|                    ||dz
  z             I||dz
  z  } j                 dz
  }t          j        ||          }t          j        |                    d          ||          }|                    |           t          j                    fd}g }|D ]P} ||          }|st          j        |          }n|                    |	          }|                    |           Qt          |          dk    rt          j        |d          }n|d         }|t          j        ||           |S |S )a  
    Compute the quantile of the input along the specified axis.

    Args:
        x (Tensor): The input Tensor, it's data type can be float32, float64, int32, int64.
        q (int|float|list|Tensor): The q for calculate quantile, which should be in range [0, 1]. If q is a list or
            a 1-D Tensor, each element of q will be calculated and the first dimension of output is same to the number of ``q`` .
            If q is a 0-D Tensor, it will be treated as an integer or float.
        axis (int|list, optional): The axis along which to calculate quantile. ``axis`` should be int or list of int.
            ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` .
            If ``axis`` is less than 0, it works the same way as :math:`axis + D`.
            If ``axis`` is a list, quantile is calculated over all elements of given axes.
            If ``axis`` is None, quantile is calculated over all elements of ``x``. Default is None.
        keepdim (bool, optional): Whether to reserve the reduced dimension(s)
            in the output Tensor. If ``keepdim`` is True, the dimensions of
            the output Tensor is the same as ``x`` except in the reduced
            dimensions(it is of size 1 in this case). Otherwise, the shape of
            the output Tensor is squeezed in ``axis`` . Default is False.
        interpolation (str, optional): The interpolation method to use
            when the desired quantile falls between two data points. Must be one of linear, higher,
            lower, midpoint and nearest. Default is linear.
        ignore_nan: (bool, optional): Whether to ignore NaN of input Tensor.
            If ``ignore_nan`` is True, it will calculate nanquantile.
            Otherwise it will calculate quantile. Default is False.
        out (Tensor|None, optional): The output tensor. Default: None.

    Returns:
        Tensor, results of quantile along ``axis`` of ``x``.
        In order to obtain higher precision, data type of results will be float64.
    zinput x should be a Tensor.r   zq should not be emptyr   z(q should be a 0-D tensor or a 1-D tensorz8Type of q should be int, float, list or tuple, or tensorzq should be in range [0, 1])r   r   r   r   r   z[interpolation must be one of 'linear', 'lower', 'higher', 'nearest' or 'midpoint', but got NzQAxis should be None, int, or a list, element should in range [-rank(x), rank(x)).r   T)r#   r(   r^   )
fill_valuec                ^   dk    rHt          j        |                               t           j                  }t          j        	|          S t          j        |                               t           j                  }dk    rt          j        	|          }dk    r|S t          j        |                               t           j                  }t          j        	|          }dk    r|S dk    r8|                    
j                  |                    
j                  z   dz  S | |                    | j                  z
                      
j                  }t          j        |                    
j                  |                    
j                  |          S )Nr   r#   r   r   r   r   )	r`   roundro   r5   take_along_axisfloorceilr%   lerp)indexidxindices_belowtensor_belowindices_uppertensor_upperweightsr#   r   sorted_tensorr!   s          rQ   _compute_indexz)_compute_quantile.<locals>._compute_indexd  s   I%%,u%%,,V\::C)-4HHHHU++226<@@H$$!1}4  L G##E**11&,??-=t
 
 
 H$$J&&##AG,,|/B/B17/K/KK  =//<<<DDQWMM{((((
 
 	
rR   r   ) rD   r   r`   r   r   r   rH   rV   rI   rJ   ru   rk   rf   r	   rd   appendrangemoveaxisisnanlogical_notrm   r
   rv   r%   	full_likewhererr   sortsqueezere   stackrw   )r!   r   r#   r(   r   r   r&   q_numr   	out_shapeaxis_srcaxis_dstaxis_singlemaskvalid_countsrg   r   
last_indexnumsr   rB   retr   s   ` ` `                 @rQ   _compute_quantiler     s>   P a(FJ$4566 75666 !c5\"" 
C	Ae}	%	% 
q66Q;;4555 	A&*"23	4	4 
qw<<!GHHHqw<<1AF
 
 	
  < <   	ZHfj./&
 &
 	 E199		:;;; "     yjwyy
 
 	
 qw<<DQWI|N1C$J		dD!! 	 !#RhH# 
+ 
+!+s33 $&&;4%+?+?$k   ??"-"4K,,,)*	+&&E3t99*a0011H8X66A8}}!!N1%%N1hqk8B<@@{dC(( $ g   axxIdO7799D##%%))tT)BBLG 
" 
"!## 	;$U!':::E 	"NN5L1$456666\A-.E*J#EjAAADLtT!B!BD%PPENN5!!!!K4((M 
  
  
  
  
  
  
  
D G   nU## 	).4000CC++i((Cs
7||a,w**!*
gs###
NrR    float | Sequence[float] | Tensorc          	     .    t          | ||||d|          S )a  
    Compute the quantile of the input along the specified axis.
    If any values in a reduced row are NaN, then the quantiles for that reduction will be NaN.

    Args:
        x (Tensor): The input Tensor, it's data type can be float32, float64, int32, int64.
        q (int|float|list|Tensor): The q for calculate quantile, which should be in range [0, 1]. If q is a list or
            a 1-D Tensor, each element of q will be calculated and the first dimension of output is same to the number of ``q`` .
            If q is a 0-D Tensor, it will be treated as an integer or float.
        axis (int|list, optional): The axis along which to calculate quantile. ``axis`` should be int or list of int.
            ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` .
            If ``axis`` is less than 0, it works the same way as :math:`axis + D`.
            If ``axis`` is a list, quantile is calculated over all elements of given axes.
            If ``axis`` is None, quantile is calculated over all elements of ``x``. Default is None.
        keepdim (bool, optional): Whether to reserve the reduced dimension(s)
            in the output Tensor. If ``keepdim`` is True, the dimensions of
            the output Tensor is the same as ``x`` except in the reduced
            dimensions(it is of size 1 in this case). Otherwise, the shape of
            the output Tensor is squeezed in ``axis`` . Default is False.
        interpolation (str, optional): The interpolation method to use
            when the desired quantile falls between two data points. Must be one of linear, higher,
            lower, midpoint and nearest. Default is linear.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
        out (Tensor|None, optional): The output tensor. Default: None.


    Returns:
        Tensor, results of quantile along ``axis`` of ``x``.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> y = paddle.arange(0, 8 ,dtype="float32").reshape([4, 2])
            >>> print(y)
            Tensor(shape=[4, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[0., 1.],
             [2., 3.],
             [4., 5.],
             [6., 7.]])

            >>> y1 = paddle.quantile(y, q=0.5, axis=[0, 1])
            >>> print(y1)
            Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
            3.50000000)

            >>> y2 = paddle.quantile(y, q=0.5, axis=1)
            >>> print(y2)
            Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
            [0.50000000, 2.50000000, 4.50000000, 6.50000000])

            >>> y3 = paddle.quantile(y, q=[0.3, 0.5], axis=0)
            >>> print(y3)
            Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[1.80000000, 2.80000000],
             [3.        , 4.        ]])

            >>> y[0,0] = float("nan")
            >>> y4 = paddle.quantile(y, q=0.8, axis=1, keepdim=True)
            >>> print(y4)
            Tensor(shape=[4, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[nan       ],
             [2.80000000],
             [4.80000000],
             [6.80000000]])

    F)r#   r(   r   r   r&   r   )r!   r   r#   r(   r   r*   r&   s          rQ   quantiler     s1    ` 		#   rR   list[int] | int | Nonec                ,    t          | ||||d          S )a  
    Compute the quantile of the input as if NaN values in input did not exist.
    If all values in a reduced row are NaN, then the quantiles for that reduction will be NaN.

    Args:
        x (Tensor): The input Tensor, it's data type can be float32, float64, int32, int64.
        q (int|float|list|Tensor): The q for calculate quantile, which should be in range [0, 1]. If q is a list or
            a 1-D Tensor, each element of q will be calculated and the first dimension of output is same to the number of ``q`` .
            If q is a 0-D Tensor, it will be treated as an integer or float.
        axis (int|list, optional): The axis along which to calculate quantile. ``axis`` should be int or list of int.
            ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` .
            If ``axis`` is less than 0, it works the same way as :math:`axis + D`.
            If ``axis`` is a list, quantile is calculated over all elements of given axes.
            If ``axis`` is None, quantile is calculated over all elements of ``x``. Default is None.
        keepdim (bool, optional): Whether to reserve the reduced dimension(s)
            in the output Tensor. If ``keepdim`` is True, the dimensions of
            the output Tensor is the same as ``x`` except in the reduced
            dimensions(it is of size 1 in this case). Otherwise, the shape of
            the output Tensor is squeezed in ``axis`` . Default is False.
        interpolation (str, optional): The interpolation method to use
            when the desired quantile falls between two data points. Must be one of linear, higher,
            lower, midpoint and nearest. Default is linear.
        name (str|None, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor, results of quantile along ``axis`` of ``x``.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> x = paddle.to_tensor(
            ...     [[0, 1, 2, 3, 4],
            ...      [5, 6, 7, 8, 9]],
            ...     dtype="float32")
            >>> x[0,0] = float("nan")

            >>> y1 = paddle.nanquantile(x, q=0.5, axis=[0, 1])
            >>> print(y1)
            Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
            5.)

            >>> y2 = paddle.nanquantile(x, q=0.5, axis=1)
            >>> print(y2)
            Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [2.50000000, 7.        ])

            >>> y3 = paddle.nanquantile(x, q=[0.3, 0.5], axis=0)
            >>> print(y3)
            Tensor(shape=[2, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[5.        , 2.50000000, 3.50000000, 4.50000000, 5.50000000],
             [5.        , 3.50000000, 4.50000000, 5.50000000, 6.50000000]])

            >>> y4 = paddle.nanquantile(x, q=0.8, axis=1, keepdim=True)
            >>> print(y4)
            Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[3.40000000],
             [8.20000000]])

            >>> nan = paddle.full(shape=[2, 3], fill_value=float("nan"))
            >>> y5 = paddle.nanquantile(nan, q=0.8, axis=1, keepdim=True)
            >>> print(y5)
            Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[nan],
             [nan]])

    T)r#   r(   r   r   r   )r!   r   r#   r(   r   s        rQ   nanquantiler     s.    X 		#   rR   )NFN)r!   r   r#   r'   r(   r)   r*   r+   r%   r,   r&   r-   r.   r   )NNFN)r!   r   r#   r'   rT   rU   r(   r)   r*   r+   rS   rV   r&   r-   r.   r   )NTFN)r!   r   r#   r'   rT   r)   r(   r)   r*   r+   r.   r   r   )r!   r   r*   r+   r.   r   )...)r!   r   r#   rH   r(   r)   r   r   r*   r+   r.   r   )....)r!   r   r#   r'   r(   r)   r   r   r*   r+   r.   r   )NFr   N)r!   r   r#   rH   r(   r)   r   r   r*   r+   r&   r   r.   r   )r!   r   r#   r   r(   r)   r   r   r*   r+   r.   r   )NFr   FN)r!   r   r   r   r#   r   r(   r)   r   r    r   r)   r&   r-   r.   r   )NFr   N)r!   r   r   r   r#   r   r(   r)   r   r    r*   r+   r&   r-   r.   r   )NFr   )r!   r   r   r   r#   r   r(   r)   r   r    r.   r   )0
__future__r   rs   typingr   r   typing_extensionsr   r   r`   r   paddle.frameworkr	   r
   paddle.utils.decorator_utilsr   r   r   base.data_feederr   r   common_ops_importr   	frameworkr   r   r   manipulationr   mathr   collections.abcr   r   paddle._typingr   r    __annotations____all__r9   r[   r~   rb   r   r   r   r   r   r   rR   rQ   <module>r      s   # " " " " " "  ) ) ) ) ) ) ) ) 1 1 1 1 1 1 1 1                        D C C C C C C C ( ( ( ( ( ( E E E E E E E E E E       . . . . . . )((((((((((((#6      #w&%11 (,	y #y y y y y 21yx G9ug6677 (, v v v v v v 87vv (,F F F F FR" " " " "J 
         
  
 (+"%    
 
		x x x xv 
   ),          
  
 "%    
 c7^fe_vuoNN 
		[ 	[ [ [ [ ON[B $($,| | | | |~ #w&%11 $($,W W W W W W 21Wz $($,S S S S S S SrR   