
    Αi,<                        S SK Jr  S SKJr  S SKJr  S SKrS SKJr  \(       a  S SKJ	r	J
r
   " S S\R                  5      rg)	    )annotations)Sequence)TYPE_CHECKINGN)distribution)Tensordtypec                    ^  \ rS rSr% SrS\S'   S\S'   S\S'    S     SU 4S jjjrSS jrSS	 jrSS
 jr	SS jr
SS jr\SS j5       r\SS j5       r/ 4SS jjr/ 4SS jjrSS jrSS jrSS jrSS jrSS jrSS jrSrU =r$ )ContinuousBernoulli   a   The Continuous Bernoulli distribution with parameter: `probs` characterizing the shape of the density function.
The Continuous Bernoulli distribution is defined on [0, 1], and it can be viewed as a continuous version of the Bernoulli distribution.

`The continuous Bernoulli: fixing a pervasive error in variational autoencoders. <https://arxiv.org/abs/1907.06845>`_

Mathematical details

The probability density function (pdf) is

.. math::

    p(x;\lambda) = C(\lambda)\lambda^x (1-\lambda)^{1-x}

In the above equation:

* :math:`x`: is continuous between 0 and 1
* :math:`probs = \lambda`: is the probability.
* :math:`C(\lambda)`: is the normalizing constant factor

.. math::

    C(\lambda) =
    \left\{
    \begin{aligned}
    &2 & \text{ if $\lambda = \frac{1}{2}$} \\
    &\frac{2\tanh^{-1}(1-2\lambda)}{1 - 2\lambda} & \text{ otherwise}
    \end{aligned}
    \right.

Args:
    probs(int|float|Tensor): The probability of Continuous Bernoulli distribution between [0, 1],
        which characterize the shape of the pdf. If the input data type is int or float, the data type of
        `probs` will be convert to a 1-D Tensor the paddle global default dtype.
    lims(tuple): Specify the unstable calculation region near 0.5, where the calculation is approximated
        by talyor expansion. The default value is (0.499, 0.501).

Examples:
    .. code-block:: python

        >>> import paddle
        >>> from paddle.distribution import ContinuousBernoulli
        >>> paddle.set_device("cpu")
        >>> paddle.seed(100)

        >>> rv = ContinuousBernoulli(paddle.to_tensor([0.2, 0.5]))

        >>> print(rv.sample([2]))
        Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
        [[0.38694882, 0.20714243],
         [0.00631948, 0.51577556]])

        >>> print(rv.mean)
        Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
        [0.38801414, 0.50000000])

        >>> print(rv.variance)
        Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
        [0.07589778, 0.08333334])

        >>> print(rv.entropy())
        Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
        [-0.07641457,  0.        ])

        >>> print(rv.cdf(paddle.to_tensor(0.1)))
        Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
        [0.17259926, 0.10000000])

        >>> print(rv.icdf(paddle.to_tensor(0.1)))
        Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
        [0.05623737, 0.10000000])

        >>> rv1 = ContinuousBernoulli(paddle.to_tensor([0.2, 0.8]))
        >>> rv2 = ContinuousBernoulli(paddle.to_tensor([0.7, 0.5]))
        >>> print(rv1.kl_divergence(rv2))
        Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
        [0.20103608, 0.07641447])
r   probslimsr   c                  > [         R                  " 5       U l        U R                  U5      U l        [         R
                  " X R                  S9U l        [         R                  " U R                  R                  5      R                  n[         R                  " U R                  USU-
  S9U l        U R                  R                  n[        TU ]1  U5        g )Nr      )minmax)paddleget_default_dtyper   
_to_tensorr   	to_tensorr   finfoepsclipshapesuper__init__)selfr   r   eps_probbatch_shape	__class__s        h/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/distribution/continuous_bernoulli.pyr   ContinuousBernoulli.__init__n   s     --/
__U+
$$T<	 <<

 0 0155[[q8|L
jj&&%    c                    [        U[        [        45      (       a"  [        R                  " U/U R
                  S9nU$ UR
                  U l        U$ )zWConvert the input parameters into tensors

Returns:
    Tensor: converted probability.
r   )
isinstancefloatintr   r   r   )r   r   s     r!   r   ContinuousBernoulli._to_tensor|   sF     eeS\**$$eWDJJ?E  DJr#   c                    [         R                  " [         R                  " U R                  U R                  S   5      [         R
                  " U R                  U R                  S   5      5      $ )zGenerate stable support region indicator (prob < self.lims[0] && prob >= self.lims[1] )

Returns:
    Tensor: the element of the returned indicator tensor corresponding to stable region is True, and False otherwise
r   r   )r   
logical_or
less_equalr   r   greater_thanr   s    r!   _cut_support_region'ContinuousBernoulli._cut_support_region   sO       djj$))A,7

DIIaL9
 	
r#   c                    [         R                  " U R                  5       U R                  U R                  S   [         R
                  " U R                  5      -  5      $ )zCut the probability parameter with stable support region

Returns:
    Tensor: the element of the returned probability tensor corresponding to unstable region is set to be self.lims[0], and unchanged otherwise
r   )r   wherer.   r   r   	ones_liker-   s    r!   
_cut_probsContinuousBernoulli._cut_probs   sG     ||$$&JJIIaL6++DJJ77
 	
r#   c                d    S[         R                  " U5      [         R                  " U* 5      -
  -  $ )zjCalculate the tanh inverse of value

Args:
    value (Tensor)

Returns:
    Tensor: tanh inverse of value
      ?)r   log1pr   values     r!   _tanh_inverse!ContinuousBernoulli._tanh_inverse   s(     fll5)FLL%,@@AAr#   c           
        U R                  5       n[        R                  " SU R                  S9n[        R                  " [        R
                  " X5      U[        R                  " U5      5      n[        R                  " [        R                  " X5      U[        R                  " U5      5      n[        R                  " S[        R                  " U R                  SSU-  -
  5      5      -  5      [        R                  " [        R
                  " X5      [        R                  " SU-  5      [        R                  " SU-  S-
  5      5      -
  n[        R                  " U R                  S-
  5      n[        R                  " [        R                  " SU R                  S95      SSU-  -   U-  -   n[        R                  " U R                  5       XW5      $ )zCalculate the logarithm of the constant factor :math:`C(lambda)` in the pdf of the Continuous Bernoulli distribution

Returns:
    Tensor: logarithm of the constant factor
r6   r          @      ?g       gUUUUUU?g'}'}@)r3   r   r   r   r1   r+   
zeros_likegreater_equalr2   logabsr:   r7   squarer   r.   )r   	cut_probshalfcut_probs_below_halfcut_probs_above_halflog_constant_proposextaylor_expansions           r!   _log_constant!ContinuousBernoulli._log_constant   sv    OO%	4::6%||i.i( 

  &||  1Y' 

  &zz&**T//cIo0EFGG 
LLi.LL 445JJs11C78
 
 MM$**s*+JJv''4::>?<!++q01 	 ||$$&(<
 	
r#   c           
        U R                  5       n[        R                  " USU-  S-
  5      nU[        R                  " [        R                  " SU R                  S9SU R                  SSU-  -
  5      -  5      -   nU R                  S-
  nSSS[        R                  " U5      -  -   U-  -   n[        R                  " U R                  5       X55      $ )zMMean of Continuous Bernoulli distribution.

Returns:
    Tensor: mean value.
r=   r>   r   r6   gUUUUUU?gll?)
r3   r   divider   r   r:   r   rC   r1   r.   r   rD   tmpproposerI   rJ   s         r!   meanContinuousBernoulli.mean   s     OO%	mmIsY'<=S

3$$$S3?%:;;
 
 JJ9{V]]1-===BB 	 ||$$&
 	
r#   c           
     (   U R                  5       n[        R                  " XS-
  -  [        R                  " SSU-  -
  5      5      nU[        R                  " [        R                  " SU R
                  S9[        R                  " [        R                  " U* 5      [        R                  " U5      -
  5      5      -   n[        R                  " U R                  S-
  5      nSSSU-  -
  U-  -
  n[        R                  " U R                  5       X55      $ )zUVariance of Continuous Bernoulli distribution.

Returns:
    Tensor: variance value.
r>   r=   r   r6   gUUUUUU?g?ggjV?)r3   r   rN   rC   r   r   r7   rA   r   r1   r.   rO   s         r!   varianceContinuousBernoulli.variance   s     OO%	mmS)MM#i/0
 S

3MM&,,	z2VZZ	5JJK
 
 MM$**s*+%ma6G)G1(LL||$$&
 	
r#   c                    [         R                  " 5          U R                  U5      sSSS5        $ ! , (       d  f       g= f)  Generate Continuous Bernoulli samples of the specified shape. The final shape would be ``sample_shape + batch_shape``.

Args:
    shape (Sequence[int], optional): Prepended shape of the generated samples.

Returns:
    Tensor, Sampled data with shape `sample_shape` + `batch_shape`.
N)r   no_gradrsample)r   r   s     r!   sampleContinuousBernoulli.sample   s&     ^^<<& s   1
?c                    [        U[        5      (       d  [        S5      e[        U5      n[        U R                  5      n[        X-   5      n[
        R                  " X0R                  SSS9nU R                  U5      $ )rX   z%sample shape must be Sequence object.r   r   )r   r   r   r   )	r%   r   	TypeErrortupler   r   uniformr   icdf)r   r   r   output_shapeus        r!   rZ   ContinuousBernoulli.rsample  sg     %**CDDeD,,-U01NNZZQANyy|r#   c                   [         R                  " XR                  S9n[         R                  " U R                  R                  5      R
                  n[         R                  " U[         R                  " U R                  5      -  SU-
  [         R                  " SU R                  -
  5      -  -   U* S9nU R                  5       U-   $ )zLog probability density function.

Args:
  value (Tensor): The input tensor.

Returns:
  Tensor: log probability. The data type is the same as `self.probs`.
r   r>   r   )neginf)	r   castr   r   r   r   
nan_to_numrA   rK   )r   r9   r   cross_entropys       r!   log_probContinuousBernoulli.log_prob  s     E4ll4::++,00))FJJtzz**U{fjjTZZ8894

 !!#m33r#   c                L    [         R                  " U R                  U5      5      $ )zProbability density function.

Args:
    value (Tensor): The input tensor.

Returns:
    Tensor: probability. The data type is the same as `self.probs`.
)r   exprj   r8   s     r!   probContinuousBernoulli.prob'  s     zz$--.//r#   c           
        [         R                  " U R                  5      n[         R                  " U R                  * 5      n[         R                  " [         R
                  " U R                  [         R                  " SU R                  S95      [         R                  " U R                  S5      U R                  5       * U R                  X!-
  -  -   U-
  5      $ )aB  Shannon entropy in nats.

The entropy is

.. math::

    \mathcal{H}(X) = -\log C + \left[ \log (1 - \lambda) -\log \lambda \right] \mathbb{E}(X)  - \log(1 - \lambda)

In the above equation:

* :math:`\Omega`: is the support of the distribution.

Returns:
    Tensor, Shannon entropy of Continuous Bernoulli distribution.
r6   r           )r   rA   r   r7   r1   equalr   r   	full_likerK   rR   )r   log_plog_1_minus_ps      r!   entropyContinuousBernoulli.entropy2  s      

4::&djj[1||LLV%5%5c%LMTZZ-##%%))}456 	
 	
r#   c                   [         R                  " XR                  S9nU R                  5       n[         R                  " X!5      [         R                  " SU-
  SU-
  5      -  U-   S-
  SU-  S-
  -  n[         R
                  " U R                  5       X15      n[         R
                  " [         R                  " U[         R                  " SU R                  S95      [         R                  " U5      [         R
                  " [         R                  " U[         R                  " SU R                  S95      [         R                  " U5      U5      5      $ )a  Cumulative distribution function

.. math::

    {   P(X \le t; \lambda) =
        F(t;\lambda) =
        \left\{
        \begin{aligned}
        &t & \text{ if $\lambda = \frac{1}{2}$} \\
        &\frac{\lambda^t (1 - \lambda)^{1 - t} + \lambda - 1}{2\lambda - 1} & \text{ otherwise}
        \end{aligned}
        \right. }

Args:
    value (Tensor): The input tensor.

Returns:
    Tensor: quantile of :attr:`value`. The data type is the same as `self.probs`.
r   r>   r=   rq   )r   rg   r   r3   powr1   r.   r+   r   r?   r@   r2   )r   r9   rD   cdfsunbounded_cdfss        r!   cdfContinuousBernoulli.cdfO  s   ( E4OO%	JJy(jjy#+67  9_s"$  d&>&>&@$N||eV%5%5c%LMe$LL$$6++CtzzB   '

 
	
r#   c           	     z   [         R                  " XR                  S9nU R                  5       n[         R                  " U R                  5       [         R                  " U* USU-  S-
  -  -   5      [         R                  " U* 5      -
  [         R                  " U5      [         R                  " U* 5      -
  -  U5      $ )a  Inverse cumulative distribution function

.. math::

    {   F^{-1}(x;\lambda) =
        \left\{
        \begin{aligned}
        &x & \text{ if $\lambda = \frac{1}{2}$} \\
        &\frac{\log(1+(\frac{2\lambda - 1}{1 - \lambda})x)}{\log(\frac{\lambda}{1-\lambda})} & \text{ otherwise}
        \end{aligned}
        \right. }

Args:
    value (Tensor): The input tensor, meaning the quantile.

Returns:
    Tensor: the value of the r.v. corresponding to the quantile. The data type is the same as `self.probs`.
r   r=   r>   )r   rg   r   r3   r1   r.   r7   rA   )r   r9   rD   s      r!   ra   ContinuousBernoulli.icdfx  s    & E4OO%	||$$&iZ%3?S3H*IIJ,,	z*+ zz)$v||YJ'??	A
 
 	
r#   c                D   U R                   UR                   :w  a  [        S5      eU R                  5       * n[        R                  " UR
                  5      n[        R                  " UR
                  * 5      nUR                  5       U R                  X4-
  -  -   U-   * nX%-   $ )a  The KL-divergence between two Continuous Bernoulli distributions with the same `batch_shape`.

The probability density function (pdf) is

.. math::

    KL\_divergence(\lambda_1, \lambda_2) = - H - \{\log C_2 + [\log \lambda_2 -  \log (1-\lambda_2)]  \mathbb{E}_1(X) +  \log (1-\lambda_2)  \}

Args:
    other (ContinuousBernoulli): instance of Continuous Bernoulli.

Returns:
    Tensor, kl-divergence between two Continuous Bernoulli distributions.

z\KL divergence of two Continuous Bernoulli distributions should share the same `batch_shape`.)	r   
ValueErrorrv   r   rA   r   r7   rK   rR   )r   otherpart1log_qlog_1_minus_qpart2s         r!   kl_divergence!ContinuousBernoulli.kl_divergence  s    " u000n  

5;;'ekk\2!ii5012

 }r#   )r   r   r   ))gV-?gx&1?)r   float | Tensorr   ztuple[float]returnNone)r   r   r   r   )r   r   )r9   r   r   r   )r   zSequence[int]r   r   )r   r
   r   r   )__name__
__module____qualname____firstlineno____doc____annotations__r   r   r.   r3   r:   rK   propertyrR   rU   r[   rZ   rj   rn   rv   r|   ra   r   __static_attributes____classcell__)r    s   @r!   r
   r
      s    L\ M
LL ;I&#&+7&	& &	


	B 
D 
 
( 
 
* -/ 
' .0 "4$	0
:'
R
> r#   r
   )
__future__r   collections.abcr   typingr   r   paddle.distributionr   r   r   Distributionr
    r#   r!   <module>r      s0    # $    ,$Y,33 Yr#   