o
    pi                     @  s   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	 d dl
mZ d dlmZ er:d dlmZ d d	lmZ G d
d dejZddddZdS )    )annotationsN)TYPE_CHECKING)check_variable_and_dtype)LayerHelper)exponential_family)in_dynamic_or_pir_mode)Sequence)Tensorc                      s   e Zd ZU dZded< d fddZeddd	Zedd
dZg fdddZ	d ddZ
d ddZdddZed!ddZd"ddZ  ZS )#	Dirichletaa  
    Dirichlet distribution with parameter "concentration".

    The Dirichlet distribution is defined over the `(k-1)-simplex` using a
    positive, length-k vector concentration(`k > 1`).
    The Dirichlet is identically the Beta distribution when `k = 2`.

    For independent and identically distributed continuous random variable
    :math:`\boldsymbol X \in R_k` , and support
    :math:`\boldsymbol X \in (0,1), ||\boldsymbol X|| = 1` ,
    The probability density function (pdf) is

    .. math::

        f(\boldsymbol X; \boldsymbol \alpha) = \frac{1}{B(\boldsymbol \alpha)} \prod_{i=1}^{k}x_i^{\alpha_i-1}

    where :math:`\boldsymbol \alpha = {\alpha_1,...,\alpha_k}, k \ge 2` is
    parameter, the normalizing constant is the multivariate beta function.

    .. math::

        B(\boldsymbol \alpha) = \frac{\prod_{i=1}^{k} \Gamma(\alpha_i)}{\Gamma(\alpha_0)}

    :math:`\alpha_0=\sum_{i=1}^{k} \alpha_i` is the sum of parameters,
    :math:`\Gamma(\alpha)` is gamma function.

    Args:
        concentration (Tensor): "Concentration" parameter of dirichlet
            distribution, also called :math:`\alpha`. When it's over one
            dimension, the last axis denotes the parameter of distribution,
            ``event_shape=concentration.shape[-1:]`` , axes other than last are
            consider batch dimensions with ``batch_shape=concentration.shape[:-1]`` .

    Examples:

        .. code-block:: python

            >>> import paddle
            >>> dirichlet = paddle.distribution.Dirichlet(paddle.to_tensor([1., 2., 3.]))
            >>> print(dirichlet.entropy())
            Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
            -1.24434423)

            >>> print(dirichlet.prob(paddle.to_tensor([.3, .5, .6])))
            Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
            10.80000019)
    r	   concentrationreturnNonec                   sP   |  dk st|jdkrtd|| _t |jd d |jdd   d S )N   r   z:`concentration` parameter must be at least one dimensional)dimmathprodshape
ValueErrorr   super__init__)selfr   	__class__ d/home/app/PaddleOCR-VL/.venv_paddleocr/lib/python3.10/site-packages/paddle/distribution/dirichlet.pyr   S   s   &zDirichlet.__init__c                 C  s   | j | j jddd S )zbMean of Dirichlet distribution.

        Returns:
            Mean value of distribution.
        r   TZkeepdim)r   sumr   r   r   r   mean]   s   zDirichlet.meanc                 C  s2   | j jddd}| j || j   |d|d   S )zjVariance of Dirichlet distribution.

        Returns:
            Variance value of distribution.
        r   Tr      r   )r   r   pow)r   concentration0r   r   r   variancef   s   zDirichlet.variancer   Sequence[int]c                 C  s,   t |tr|nt|}t| j| |S )zSample from dirichlet distribution.

        Args:
            shape (Sequence[int], optional): Sample shape. Defaults to empty list.
        )
isinstancetuple
_dirichletr   expandZ_extend_shape)r   r   r   r   r   sampler   s   zDirichlet.samplevaluec                 C  s   t | |S )zProbability density function(PDF) evaluated at value.

        Args:
            value (Tensor): Value to be evaluated.

        Returns:
            PDF evaluated at value.
        )paddleexplog_probr   r*   r   r   r   prob{   s   	zDirichlet.probc                 C  s>   t || jd  dt | jd t | jd S )zoLog of probability density function.

        Args:
            value (Tensor): Value to be evaluated.
              ?r   )r+   logr   r   lgammar.   r   r   r   r-      s   zDirichlet.log_probc                 C  sb   | j d}| j jd }t| j dt| || t|  | j d t| j  d S )zbEntropy of Dirichlet distribution.

        Returns:
            Entropy of distribution.
        r   r0   )r   r   r   r+   r2   Zdigamma)r   r"   kr   r   r   entropy   s   zDirichlet.entropytuple[Tensor]c                 C  s   | j fS N)r   r   r   r   r   _natural_parameters   s   zDirichlet._natural_parametersxc                 C  s   |  dt |d S )Nr   )r2   r   r+   )r   r8   r   r   r   _log_normalizer   s   zDirichlet._log_normalizer)r   r	   r   r   )r   r	   )r   r$   r   r	   )r*   r	   r   r	   )r   r5   )r8   r	   r   r	   )__name__
__module____qualname____doc____annotations__r   propertyr   r#   r)   r/   r-   r4   r7   r9   __classcell__r   r   r   r   r
       s   
 0

	

r
   r   r	   name
str | Noner   c                 C  sf   t  r	tj| S d}t| dg d| t|fi t }|j| jd}|j	|d| id|ii d |S )N	dirichletr   )Zfloat16Zfloat32Zfloat64Zuint16)dtypeAlphaZOut)typeZinputsZoutputsattrs)
r   r+   Z_C_opsrC   r   r   localsZ"create_variable_for_type_inferencerD   Z	append_op)r   rA   Zop_typehelperoutr   r   r   r'      s(   r'   r6   )r   r	   rA   rB   r   r	   )
__future__r   r   typingr   r+   Zpaddle.base.data_feederr   Zpaddle.base.layer_helperr   Zpaddle.distributionr   Zpaddle.frameworkr   collections.abcr   r	   ZExponentialFamilyr
   r'   r   r   r   r   <module>   s    