
    zj{E                    "   U d dl mZ d dlZd dlmZ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mZ d dlmZ d dlmZ d dlmZ d d	lmZ erd d
lmZ d dlmZ d dlmZmZ d dlmZ eee f         Z!de"d<   ee	j#        e	j$        e	j%        e	j&        f         Z'de"d<   ee!ee!         ee!         ej(        e'         ef         Z)de"d<   eeee         ee         ej(        ee	j#        e	j$        f                  ef         Z*de"d<    G d dej+                  Z,dS )    )annotationsN)IterableSequence)TYPE_CHECKING)
check_typeconvert_dtype)Variable)distribution)in_dynamic_mode)random)Union)	TypeAlias)Tensordtype)NestedSequencer   _NormalLocBase_NormalLocNDArray
_NormalLoc_NormalScalec                       e Zd ZU dZded<   ded<   ded<   ded<   	 dd fdZed d            Zed d            Zg dfd!dZ	g fd"dZ
d dZd#dZd#dZd$dZ xZS )%Normala  The Normal distribution with location `loc` and `scale` parameters.

    Mathematical details

    If 'loc' is real number, the probability density function (pdf) is

    .. math::

        pdf(x; \mu, \sigma) = \frac{1}{Z}e^{\frac {-0.5 (x - \mu)^2}  {\sigma^2} }

    .. math::

        Z = (2 \pi \sigma^2)^{0.5}

    If 'loc' is complex number, the probability density function (pdf) is

    .. math::

        pdf(x; \mu, \sigma) = \frac{1}{Z}e^{\frac {-(x - \mu)^2}  {\sigma^2} }

    .. math::

        Z = \pi \sigma^2

    In the above equations:

    * :math:`loc = \mu`: is the mean.
    * :math:`scale = \sigma`: is the std.
    * :math:`Z`: is the normalization constant.

    Args:
        loc(int|float|complex|list|tuple|numpy.ndarray|Tensor): The mean of normal distribution.The data type is float32, float64, complex64 and complex128.
        scale(int|float|list|tuple|numpy.ndarray|Tensor): The std of normal distribution.The data type is float32 and float64.
        name(str|None, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> from paddle.distribution import Normal

            >>> # Define a single scalar Normal distribution.
            >>> dist = Normal(loc=0., scale=3.)
            >>> # Define a batch of two scalar valued Normals.
            >>> # The first has mean 1 and standard deviation 11, the second 2 and 22.
            >>> dist = Normal(loc=[1., 2.], scale=[11., 22.])
            >>> # Get 3 samples, returning a 3 x 2 tensor.
            >>> dist.sample([3])

            >>> # Define a batch of two scalar valued Normals.
            >>> # Both have mean 1, but different standard deviations.
            >>> dist = Normal(loc=1., scale=[11., 22.])

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

            >>> normal_a = Normal([0.], [1.])
            >>> normal_b = Normal([0.5], [2.])
            >>> sample = normal_a.sample([2])
            >>> # a random tensor created by normal distribution with shape: [2, 1]
            >>> entropy = normal_a.entropy()
            >>> print(entropy)
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [1.41893852])
            >>> lp = normal_a.log_prob(value_tensor)
            >>> print(lp)
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [-1.23893857])
            >>> p = normal_a.probs(value_tensor)
            >>> print(p)
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.28969154])
            >>> kl = normal_a.kl_divergence(normal_b)
            >>> print(kl)
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.34939718])
    r   locscalestrnamer   Nr   r   
str | NonereturnNonec                   t                      st          |dt          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| _        ||nd| _        d| _        d| _        t#          |t                    rt          |          }t#          |t                    rt          |          }t#          |t          t          f          rht          j        |          }|j        t
          j        k    r|                    d          }|j        t
          j        k    r|                    d          }t#          |t          t          f          r t          j        |t
          j                  }t#          |t                    sdt#          |t
          j                  r|j        t
          j        t
          j        fv s+|                     |          r|                                rd| _        t#          |t                    rt#          |t                    rd| _        t#          |t
          j                  r|j        t
          j        k    rdnd	}|j        t
          j        k    rdnd	}t          j        |j        |          }t          j        |j        |          }t          j        ||          | _        nmt#          |t                    rQt          j        |j        d          }t          j        |j        d          }t          j        ||          | _        n|| _        t#          |t
          j                  r!t          j        ||j                  | _        n8t#          |t                    rt          j        |d          | _        n|| _        t?          | j        j                  | _        nx|                     ||          r)|| _        || _        t?          |j                  | _        n9t#          |t                    rt#          |t                    rd| _        t#          |t
          j                  r#tA          |j                  d
v r|j        | _        n<t#          |t
          j                  r"tA          |j                  d
v r|j        | _        | !                    ||          \  | _        | _        | j        t?          | j        j                  k    rJt          j"        | j        | j                  | _        t          j"        | j        | j                  | _        tG                      $                    | j        j%                   d S )Nr   r   r   Ffloat32	complex64r   Tfloat64)r    r#   )&r   r   intfloatcomplexnpndarrayr	   paddlepirValuelisttupleall_arg_is_floatr   r   _complex_gaussian
isinstancearrayr#   astype
complex128r    r!   _validate_args
is_complex	to_tensorrealimagr   r   r   r   
_to_tensorcastsuper__init__shape)	selfr   r   r   
real_dtype
imag_dtyper7   r8   	__class__s	           j/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/distribution/normal.pyr<   zNormal.__init__   s       	JJ$	    JJ$    !& ,DD(	
!&c3 	**CeS!! 	!%LLEcE4=)) 	.(3--CyBJ&&jj++yBM))jj--eeT]++ 	6HU"*555E sG$$:	K 3
++:	K I",!>>>##C(( ?-0^^-=-= ? &*D"#w'' -Jue,D,D -(,%#rz** !$bl!:!:II	  "%bl!:!:II	  '*=='*==!>$55C)) '	BBB'	BBB!>$55%,, ##-e5;GGG

E5)) ##-e9EEE

"
&tx~66DJJ""3.. K"
*3955

c5)) 1j.F.F 1,0D)c2:.. 	-3sy>> F 4 4 "%DJJrz22 -s5;7G7G L 8 8 "'DJ'+sE'B'B$$*:tx~!>!>>>%{484:FFFDH!'TZtz!J!J!JDJ(((((    c                    | j         S )zWMean of normal distribution.

        Returns:
            Tensor: mean value.
        )r   r>   s    rB   meanzNormal.mean  s     xrC   c                6    | j                             d          S )z_Variance of normal distribution.

        Returns:
            Tensor: variance value.
           )r   powrE   s    rB   variancezNormal.variance
  s     z~~a   rC   r   r=   Sequence[int]seedr$   c                   t          |t                    st          d          t                      st	          |dt
          d           t          |          }t          | j        | j        z   j	                  }| j
        dz   }d|v r||z   }t          ||z             }t          j	        | j        | j        z             d                                         |d<   t          j        |d| j                  }t          j        ||          }t          j	        |          }	t!          j        |	| j        rdndd	|| j        
          }
|
|| j        z   z  }t          j        || j        |          }|S ||z   }t!          j        || j        rdndd	|| j        
          t          j        || j                  | j        z   z  }t          j        || j        |          }| j        rt          j        |||          S |S )a&  Generate samples of the specified shape.

        Args:
            shape (Sequence[int], optional): Shape of the generated samples.
            seed (int): Python integer number.

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

        %sample shape must be Iterable object.rL   sample_sampler                                 ?)rF   stdrL   r   r   r"   )r0   r   	TypeErrorr   r   r$   r,   r   r   r=   r   r)   itemfullr   reshaper   gaussianr/   addzerosr.   )r>   r=   rL   batch_shaper   output_shape
fill_shapezero_tmpzero_tmp_reshapezero_tmp_shapenormal_random_tmpoutputs               rB   rO   zNormal.sample  s	    %** 	ECDDD   	6tVcH555UDHtz1899y9$ ;.LkE122J"LDJ)>??BGGIIJqM{:sDJ??H%~hEE#\*:;;N &%)%;Djjj! ! ! '*:TZ*GHFZt<<<FM ;.L_%)%;Djjj   l$*===
JLF Zt<<<F$ ~fe$????rC   c                    t          |t                    st          d          |                     t	          |                    }t          j        | j        rdnd|          }| j        || j	        z  z   S )a  Generate reparameterized samples of the specified shape.

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

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

        rN   rS   rR   )rF   r=   )
r0   r   rW   _extend_shaper-   r)   normalr/   r   r   )r>   r=   epss      rB   rsamplezNormal.rsampleH  s|     %** 	ECDDD""5<<00m!%!7@**S
 
 
 x#
***rC   c           	        | j         dz   }t          | j        | j        z   j                  }| j        rd|v rnt          |          }t          j        | j        | j        z             d                                         |d<   | j        j        }t          j	        |d|          }n t          j	        |d| j        j                  }t          j
        d|z   t          j        t          j                  dt          j        | j        |z             z  z   |          S d|v rvt          |          }t          j        | j        | j        z             d                                         |d<   | j        | j        z   j        }t          j	        |d|          }nt          j	        |d| j                  }t          j
        d|z   dt          j        d	t          j        z            z  t          j        | j        |z             z   |          S )
a  Shannon entropy in nats.

        If non-complex, the entropy is

        .. math::

            entropy(\sigma) = 0.5 \log (2 \pi e \sigma^2)

        If complex gaussian, the entropy is

        .. math::

            entropy(\sigma) = \log (\pi e \sigma^2) + 1

        In the above equation:

        * :math:`scale = \sigma`: is the std.

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

        _entropyrQ   r   rR   rT          @rV         ?rH   )r   r,   r   r   r=   r/   r)   rX   r   rY   r\   mathlogpi)r>   r   r^   r`   
fill_dtypera   s         rB   entropyzNormal.entropy[  s   . y:%DHtz1899! 	[  !+..
 &TX
-B C CA F K K M M
1!Z-
!;z3
CC!;{C9IJJ:h!!C&*TZ(5J*K*K$KK    [  !+..
 &TX
-B C CA F K K M M
1"h3:
!;z3
CC!;{CDD:hdhq47{+++fjh9N.O.OO   rC   valuec           
     @   | j         dz   }|                     | j        |          }| j        | j        z  }t	          j        | j                  }| j        rdt	          j        d|| j        z
                                  || j        z
  z  z  |z  d|z  t          j        t          j
                  z   |          S t	          j        d|| j        z
  || j        z
  z  z  d|z  z  |t          j        t          j        dt          j
        z                      z   |          S )zLog probability density/mass function.

        Args:
          value (Tensor): The input tensor.

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

        	_log_prob      rm   rV   )r   _check_values_dtype_in_probsr   r   r)   rp   r/   subtractconjro   rq   sqrt)r>   rt   r   var	log_scales        rB   log_probzNormal.log_prob  s    y;&11$(EBBj4:%Jtz**	! 	?)//11UTX5EFG3Oi$(47"3"33    ?)edh.>?@C#INDHTYsTW}%=%=>>>   rC   c                   | j         dz   }|                     | j        |          }| j        | j        z  }| j        rat          j        t          j        d|| j        z
                                  || j        z
  z  z  |z            t          j
        |z  |          S t          j        t          j        d|| j        z
  || j        z
  z  z  d|z  z            t          j        dt          j
        z            | j        z  |          S )zProbability density/mass function.

        Args:
            value (Tensor): The input tensor.

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

        _probsrw   rV   rm   rH   )r   rx   r   r   r/   r)   divideexprz   ro   rq   r{   )r>   rt   r   r|   s       rB   probszNormal.probs  s    y8#11$(EBBj4:%! 	=
(..00EDH4DEG 
 3    =
(UTX-=>@Sy" 
 1tw;''$*4   rC   otherc                   t                      st          |dt          d           | j        |j        k    rt	          d          | j        dz   }| j        |j        z  }||z  }| j        |j        z
  |j        z  }| j        r4|                                |z  }||z   dz
  t          j
        |          z
  S ||z  }t          j        d|z  d|dz
  t          j
        |          z
  z  |          S )a  The KL-divergence between two normal distributions.

        If non-complex, the KL-divergence is

        .. math::

            KL\_divergence(\mu_0, \sigma_0; \mu_1, \sigma_1) = 0.5 (ratio^2 + (\frac{diff}{\sigma_1})^2 - 1 - 2 \ln {ratio})

        If complex gaussian:

        .. math::

            KL\_divergence(\mu_0, \sigma_0; \mu_1, \sigma_1) = ratio^2 + (\frac{diff}{\sigma_1})^2 - 1 - 2 \ln {ratio}

        .. math::

            ratio = \frac{\sigma_0}{\sigma_1}

        .. math::

            diff = \mu_1 - \mu_0

        In the above equation:

        * :math:`loc = \mu_0`: is the mean of current Normal distribution.
        * :math:`scale = \sigma_0`: is the std of current Normal distribution.
        * :math:`loc = \mu_1`: is the mean of other Normal distribution.
        * :math:`scale = \sigma_1`: is the std of other Normal distribution.
        * :math:`ratio`: is the ratio of scales.
        * :math:`diff`: is the difference between means.

        Args:
            other (Normal): instance of Normal.

        Returns:
            Tensor, kl-divergence between two normal distributions.The data type is float32.

        r   kl_divergencezVThe kl divergence must be computed between two distributions in the same number field._kl_divergencerT   rn   rV   )r   r   r   r/   
ValueErrorr   r   r   rz   r)   rp   r\   )r>   r   r   	var_ratiot1s        rB   r   zNormal.kl_divergence  s   N    	@ugv???!U%<<<h   y++J,		)	h"ek1! 		RBr>C'&*Y*?*???bB:irCx&*Y"7"778   rC   )N)r   r   r   r   r   r   r   r   )r   r   )r=   rK   rL   r$   r   r   )r=   rK   r   r   )rt   r   r   r   )r   r   r   r   )__name__
__module____qualname____doc____annotations__r<   propertyrF   rJ   rO   rj   rs   r~   r   r   __classcell__)rA   s   @rB   r   r   :   sW        L L\ KKKMMMIIILLL HLq) q) q) q) q) q) q)f    X ! ! ! X! -/A 3 3 3 3 3j .0 + + + + +&3 3 3 3j   8! ! ! !F; ; ; ; ; ; ; ;rC   r   )-
__future__r   ro   collections.abcr   r   typingr   numpyr'   numpy.typingnptr)   paddle.base.data_feederr   r   paddle.base.frameworkr	   paddle.distributionr
   paddle.frameworkr   paddle.tensorr   r   typing_extensionsr   r   r   paddle._typingr   r%   r&   r   r   r    r#   r!   r3   r   NDArrayr   r   Distributionr    rC   rB   <module>r      sR   # " " " " " "  . . . . . . . .                        = = = = = = = = * * * * * * , , , , , , , , , , , ,             ++++++$$$$$$$$------ %eWn 5N5555#(

BJbm;$     " ~&%&		J     $uE"*bj012		L    P P P P P\& P P P P PrC   