o
    * i)                     @  s  U d dl mZ d dlmZ d dlZd dlm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 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 d dlmZ d dlmZ eeee ee ejeejej f  ef Z!de"d< G dd dej#Z$dS )    )annotations)TYPE_CHECKINGN)_C_ops)
check_typeconvert_dtype)Variable)distribution)in_dynamic_mode)random)Sequence)Union)	TypeAlias)Tensor)NestedSequencer   _UniformBoundaryc                      sf   e Zd ZU dZded< ded< 	dd fddZg dfdddZdddZdddZdddZ	  Z
S ) Uniformaj
  Uniform distribution with `low` and `high` parameters.

    Mathematical Details

    The probability density function (pdf) is

    .. math::

        pdf(x; a, b) = \frac{1}{Z}, \ a <=x <b

    .. math::

        Z = b - a

    In the above equation:

    * :math:`low = a`,
    * :math:`high = b`,
    * :math:`Z`: is the normalizing constant.

    The parameters `low` and `high` must be shaped in a way that supports
    `Broadcasting` (e.g., `high - low` is a valid operation).

    Note:
        If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .

        .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor

    Args:
        low(int|float|list|tuple|numpy.ndarray|Tensor): The lower boundary of
            uniform distribution.The data type is float32 and float64.
        high(int|float|list|tuple|numpy.ndarray|Tensor): The higher boundary
            of uniform distribution.The data type is float32 and float64.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> from paddle.distribution import Uniform
            >>> paddle.seed(2023)

            >>> # Without broadcasting, a single uniform distribution [3, 4]:
            >>> u1 = Uniform(low=3.0, high=4.0)
            >>> # 2 distributions [1, 3], [2, 4]
            >>> u2 = Uniform(low=[1.0, 2.0], high=[3.0, 4.0])
            >>> # 4 distributions
            >>> u3 = Uniform(low=[[1.0, 2.0], [3.0, 4.0]],
            ...             high=[[1.5, 2.5], [3.5, 4.5]])
            ...
            >>> # With broadcasting:
            >>> u4 = Uniform(low=3.0, high=[5.0, 6.0, 7.0])

            >>> # Complete example
            >>> value_tensor = paddle.to_tensor([0.8], dtype="float32")

            >>> uniform = Uniform([0.], [2.])

            >>> sample = uniform.sample([2])
            >>> # a random tensor created by uniform distribution with shape: [2, 1]
            >>> entropy = uniform.entropy()
            >>> print(entropy)
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.69314718])

            >>> lp = uniform.log_prob(value_tensor)
            >>> print(lp)
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [-0.69314718])

            >>> p = uniform.probs(value_tensor)
            >>> print(p)
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.50000000])
    r   lowhighNr   name
str | NonereturnNonec              
     sz  t  s%t|dtttjttjj	t
tfd t|dtttjttjj	t
tfd d| _d| _|d ur1|nd| _d| _t|tr@t|}t|trIt|}| ||r\|| _|| _t|j| _nWt|trit|trid| _t|tjr{t|jdv r{|j| _nt|tjrt|jdv r|j| _| ||\| _| _| jt| jjkrtj| j| jd| _tj| j| jd| _t | jj d S )	Nr   r   r   Ffloat32T)r   float64dtype)r	   r   intfloatnpZndarrayr   paddleZpirValuelisttupleall_arg_is_floatZbatch_size_unknownr   r   
isinstanceZ_validate_argsr   r   r   strZ
_to_tensorcastsuper__init__shape)selfr   r   r   	__class__ g/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/paddle/distribution/uniform.pyr(      sd   		


zUniform.__init__r   r)   Sequence[int]seedr   c                 C  sV  t  st|dttfd t|dtd t|}| jd }t| j| j j}d|v rx|| }t|| }t	| j| j d 
 |d< t	|d| j}tj||j| jdd|d	}t	||}	t	||}
|
|	| j | j  }t	j|| j|d
}|S || }t	j|| jdd|d	t	j|| jd| j| j   }t	j|| j|d
}| jrt	j|||d
S |S )aS  Generate samples of the specified shape.

        Args:
            shape (Sequence[int], optional): 1D `int32`. Shape of the generated samples.
                Defaults to [].
            seed (int): Python integer number.

        Returns:
            Tensor, A tensor with prepended dimensions shape. The data type is float32.

        r)   sampler0   Z_sampler   g        g      ?)r   minmaxr0   r   r   )r	   r   r!   r"   r   r   r   r   r)   r   itemfullr   r
   Zuniform_random_batch_size_likeZreshapeadduniformZzerosr#   )r*   r)   r0   r   Zbatch_shapeZoutput_shapeZ
fill_shapeZzero_tmpZuniform_random_tmpZzero_tmp_reshapeZuniform_random_tmp_reshapeoutputr-   r-   r.   r1      sP   

zUniform.samplevaluec                 C  s   |  | j|}t r2| j|k }|| jk }t||j}t||j}t|| t| j| j  S | j	d }| j|k }|| jk }tj||jd}tj||jd}tj
t|| t| j| j |dS )zLog probability density/mass function.

        Args:
            value (Tensor): The input tensor.

        Returns:
            Tensor, log probability.The data type is same with value.

        Z	_log_probr   r5   )_check_values_dtype_in_probsr   r	   r   r   r&   r   r   logr   subtractr*   r;   Zlb_boolZub_boolZlbZubr   r-   r-   r.   log_prob   s   


 


zUniform.log_probc                 C  s   |  | j|}t r,| j|k }|| jk }t||j}t||j}|| | j| j  S | jd }| j|k }|| jk }tj||jd}tj||jd}tj	|| | j| j |dS )zProbability density/mass function.

        Args:
            value (Tensor): The input tensor.

        Returns:
            Tensor, probability. The data type is same with value.

        Z_probsr   r5   )
r<   r   r	   r   r   r&   r   r   r   divider?   r-   r-   r.   probs  s   





zUniform.probsc                 C  s    | j d }tj| j| j |dS )zShannon entropy in nats.

        The entropy is

        .. math::

            entropy(low, high) = \\log (high - low)

        Returns:
            Tensor, Shannon entropy of uniform distribution.The data type is float32.

        Z_entropyr5   )r   r   r=   r   r   )r*   r   r-   r-   r.   entropy1  s   
zUniform.entropy)N)r   r   r   r   r   r   r   r   )r)   r/   r0   r   r   r   )r;   r   r   r   )r   r   )__name__
__module____qualname____doc____annotations__r(   r1   r@   rB   rC   __classcell__r-   r-   r+   r.   r   /   s   
 LF
6
r   )%
__future__r   typingr   numpyr   Znumpy.typingZnptr   r   Zpaddle.base.data_feederr   r   Zpaddle.base.frameworkr   Zpaddle.distributionr   Zpaddle.frameworkr	   Zpaddle.tensorr
   collections.abcr   r   Ztyping_extensionsr   r   Zpaddle._typingr   r   ZNDArrayr   r   r   rH   Distributionr   r-   r-   r-   r.   <module>   s4   	