
    AVhi7                     &   d 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 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 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 ddlmZ ddgZ edg       G d dej2                               Z G d de      Zy)zStudent's t distribution class.    N)constant_op)dtypes)ops)tensor_shape)	array_ops)	check_ops)control_flow_ops)math_ops)nn)
random_ops)special_math_ops)distribution)util)deprecation)	tf_exportStudentTStudentTWithAbsDfSoftplusScalezdistributions.StudentT)v1c                   >    e Zd ZdZ ej
                  ddd      	 	 	 d fd	       Zed        Ze	d        Z
e	d	        Ze	d
        Zd Zd Zd Zd ZddZd Zd Zd Zd Zd Z ej0                  d      d        Z ej0                  d      d        Zd Z xZS )r   a  Student's t-distribution.

  This distribution has parameters: degree of freedom `df`, location `loc`,
  and `scale`.

  #### Mathematical details

  The probability density function (pdf) is,

  ```none
  pdf(x; df, mu, sigma) = (1 + y**2 / df)**(-0.5 (df + 1)) / Z
  where,
  y = (x - mu) / sigma
  Z = abs(sigma) sqrt(df pi) Gamma(0.5 df) / Gamma(0.5 (df + 1))
  ```

  where:
  * `loc = mu`,
  * `scale = sigma`, and,
  * `Z` is the normalization constant, and,
  * `Gamma` is the [gamma function](
    https://en.wikipedia.org/wiki/Gamma_function).

  The StudentT distribution is a member of the [location-scale family](
  https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be
  constructed as,

  ```none
  X ~ StudentT(df, loc=0, scale=1)
  Y = loc + scale * X
  ```

  Notice that `scale` has semantics more similar to standard deviation than
  variance. However it is not actually the std. deviation; the Student's
  t-distribution std. dev. is `scale sqrt(df / (df - 2))` when `df > 2`.

  Samples of this distribution are reparameterized (pathwise differentiable).
  The derivatives are computed using the approach described in
  (Figurnov et al., 2018).

  #### Examples

  Examples of initialization of one or a batch of distributions.

  ```python
  import tensorflow_probability as tfp
  tfd = tfp.distributions

  # Define a single scalar Student t distribution.
  single_dist = tfd.StudentT(df=3)

  # Evaluate the pdf at 1, returning a scalar Tensor.
  single_dist.prob(1.)

  # Define a batch of two scalar valued Student t's.
  # The first has degrees of freedom 2, mean 1, and scale 11.
  # The second 3, 2 and 22.
  multi_dist = tfd.StudentT(df=[2, 3], loc=[1, 2.], scale=[11, 22.])

  # Evaluate the pdf of the first distribution on 0, and the second on 1.5,
  # returning a length two tensor.
  multi_dist.prob([0, 1.5])

  # Get 3 samples, returning a 3 x 2 tensor.
  multi_dist.sample(3)
  ```

  Arguments are broadcast when possible.

  ```python
  # Define a batch of two Student's t distributions.
  # Both have df 2 and mean 1, but different scales.
  dist = tfd.StudentT(df=2, loc=1, scale=[11, 22.])

  # Evaluate the pdf of both distributions on the same point, 3.0,
  # returning a length 2 tensor.
  dist.prob(3.0)
  ```

  Compute the gradients of samples w.r.t. the parameters:

  ```python
  df = tf.constant(2.0)
  loc = tf.constant(2.0)
  scale = tf.constant(11.0)
  dist = tfd.StudentT(df=df, loc=loc, scale=scale)
  samples = dist.sample(5)  # Shape [5]
  loss = tf.reduce_mean(tf.square(samples))  # Arbitrary loss function
  # Unbiased stochastic gradients of the loss function
  grads = tf.gradients(loss, [df, loc, scale])
  ```

  References:
    Implicit Reparameterization Gradients:
      [Figurnov et al., 2018]
      (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients)
      ([pdf](http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf))
  
2019-01-01zThe TensorFlow Distributions library has moved to TensorFlow Probability (https://github.com/tensorflow/probability). You should update all references to use `tfp.distributions` instead of `tf.distributions`.T	warn_oncec           
         t        t                     }t        j                  ||||g      5 }t        j                  |rt        j                  |      gng       5  t        j                  |d      | _	        t        j                  |d      | _
        t        j                  |d      | _        t        j                  | j                  | j                  | j                  f       ddd       ddd       t        t        | ?  | j                  j                   t"        j$                  |||| j                  | j                  | j                  g|       y# 1 sw Y   oxY w# 1 sw Y   sxY w)a  Construct Student's t distributions.

    The distributions have degree of freedom `df`, mean `loc`, and scale
    `scale`.

    The parameters `df`, `loc`, and `scale` must be shaped in a way that
    supports broadcasting (e.g. `df + loc + scale` is a valid operation).

    Args:
      df: Floating-point `Tensor`. The degrees of freedom of the
        distribution(s). `df` must contain only positive values.
      loc: Floating-point `Tensor`. The mean(s) of the distribution(s).
      scale: Floating-point `Tensor`. The scaling factor(s) for the
        distribution(s). Note that `scale` is not technically the standard
        deviation of this distribution but has semantics more similar to
        standard deviation than variance.
      validate_args: Python `bool`, default `False`. When `True` distribution
        parameters are checked for validity despite possibly degrading runtime
        performance. When `False` invalid inputs may silently render incorrect
        outputs.
      allow_nan_stats: Python `bool`, default `True`. When `True`,
        statistics (e.g., mean, mode, variance) use the value "`NaN`" to
        indicate the result is undefined. When `False`, an exception is raised
        if one or more of the statistic's batch members are undefined.
      name: Python `str` name prefixed to Ops created by this class.

    Raises:
      TypeError: if loc and scale are different dtypes.
    valuesdfnamelocscaleN)dtypereparameterization_typevalidate_argsallow_nan_stats
parametersgraph_parentsr   )dictlocalsr   
name_scopecontrol_dependenciesr   assert_positiver   identity_df_loc_scaleassert_same_float_dtypesuperr   __init__r!   r   FULLY_REPARAMETERIZED	selfr   r   r    r#   r$   r   r%   	__class__s	           ]/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/distributions/student_t.pyr2   zStudentT.__init__   s'   X fhJ	b#u%5	6 0$##'4 &/%>%>r%B$C:<> 0%%bt4&&s7	((W=))XXtyy$++.	000 
(D"kk , B B#'xxDKK8 # 0 00 0s$   .E"BE(E"E	E""E+c           	      z    t        t        dt        j                  | t        j
                        gdz              S )N)r   r   r    r!      )r'   zipr   convert_to_tensorr   int32)sample_shapes    r7   _param_shapeszStudentT._param_shapes   s>    """FLL2 3567	9: :    c                     | j                   S )z8Degrees of freedom in these Student's t distribution(s).)r-   r5   s    r7   r   zStudentT.df   s     88Or@   c                     | j                   S )z/Locations of these Student's t distribution(s).)r.   rB   s    r7   r   zStudentT.loc   s     99r@   c                     | j                   S )z5Scaling factors of these Student's t distribution(s).)r/   rB   s    r7   r    zStudentT.scale   s     ;;r@   c           	         t        j                  t        j                  | j                        t        j                  t        j                  | j                        t        j                  | j
                                    S N)r   broadcast_dynamic_shapeshaper   r   r    rB   s    r7   _batch_shape_tensorzStudentT._batch_shape_tensor   sU    ,, ))OODHH%ytzz'B	DE Er@   c                     t        j                  t        j                  | j                  j                         | j                  j                               | j
                  j                               S rF   )r   broadcast_static_shaper   	get_shaper   r    rB   s    r7   _batch_shapezStudentT._batch_shape   sR    ++(():):)<)-););)=	?

   r@   c                 L    t        j                  g t        j                        S )Nr9   )r   constantr
   r=   rB   s    r7   _event_shape_tensorzStudentT._event_shape_tensor   s    (..99r@   c                 ,    t        j                  g       S rF   )r   TensorShaperB   s    r7   _event_shapezStudentT._event_shape   s    ##B''r@   c           
         t        j                  |g| j                         gd      }t        j                  || j
                  |      }| j                  t        j                  | j                         | j
                        z  }t        j                  |gd|z  d| j
                  t        j                  |d            }|t        j                  ||z        z  }|| j                  z  | j                  z   S )Nr   )r!   seedr9         ?	student_t)salt)betar!   rU   )r   concatbatch_shape_tensorr   random_normalr!   r   onesrandom_gammadistribution_utilgen_new_seedr
   rsqrtr    r   )r5   nrU   rH   normal_sampler   gamma_samplesampless           r7   	_sample_nzStudentT._sample_n   s     qc4#:#:#<=qAE,,U$**4PM	9>>$"9"9";4::N	NB**	
bjj++D{CEL hnn\B->??GTZZ$((**r@   c                 F    | j                  |      | j                         z
  S rF   )_log_unnormalized_prob_log_normalization)r5   xs     r7   	_log_probzStudentT._log_prob  s!    &&q)D,C,C,EEEr@   c                     || j                   z
  | j                  z  }d| j                  dz   z  t        j                  |dz  | j                  z        z  S )Ng            ?       @)r   r    r   r
   log1p)r5   rj   ys      r7   rh   zStudentT._log_unnormalized_prob  sE    	
TXX#A477R< 8>>!R%$''/#BBBr@   c                    t        j                  t        j                  | j                              dt        j                  | j                        z  z   dt        j                  t
        j                        z  z   t        j                  d| j                  z        z   t        j                  d| j                  dz   z        z
  S )NrV   rm   )r
   logabsr    r   nppilgammarB   s    r7   ri   zStudentT._log_normalization  s    LLdjj12(,,tww''("&&-  OOC$''M*+ OOC477R<01	2 3r@   c                 H   || j                   z
  t        j                  | j                        z  }| j                  |dz  | j                  z   z  }dt        j
                  d| j                  z  d|      z  }t        j                  t        j                  |d      |d|z
        S )Nrn   rV   g        rm   )	r   r
   rs   r    r   betaincr   where_v2less)r5   rj   rp   x_tneg_cdfs        r7   _cdfzStudentT._cdf  s    	
TXXdjj11A
''QUTWW_
%CH$$S477]C==GhmmAr2GR'\JJr@   c                    t        j                  | j                         | j                        dt         j                  f   }|| j
                  dt         j                  f   z  }t        j                  ||gd      dz  }t        j                  t        j                  | j                              dt        j                  | j
                        z  z   t        j                  |      z   d| j
                  dz   z  t        j                  d| j
                  dz   z        t        j                  d| j
                  z        z
  z  z   S )Nr9   .rn   rV   rm   )r   r]   r[   r!   newaxisr   rZ   r
   rr   rs   r    r   lbetadigamma)r5   vubeta_args       r7   _entropyzStudentT._entropy  s   t..0!ZZ	)),i.?.?)?	AA	DGGC***++AA+b0HLLdjj12(,,tww''(""8,- 477R< cTWWr\23cDGGm,-.. /r@   zThe mean of Student's T equals `loc` if `df > 1`, otherwise it is
      `NaN`. If `self.allow_nan_stats=True`, then an exception will be raised
      rather than returning `NaN`.c           	         | j                   t        j                  | j                         | j                        z  }| j
                  rt        j                  t        j                  | j                  j                               }t        j                  t        j                  | j                  t        j                  | j                         | j                              |t        j                  | j                         |d            S t        j                   t#        j$                  t        j                  g | j                        | j                  d      g|      S )Nr9   nanr   z*mean not defined for components of df <= 1message)r   r   r]   r[   r!   r$   rt   arrayr   as_numpy_dtypery   r
   greaterr   fillr	   with_dependenciesr   assert_less)r5   meanr   s      r7   _meanzStudentT._mean)  s   
 88innT%<%<%>+/::7 7DHHRVV4::#<#<#>?c


ggnnT446djjIK 	t668#EJ	L L //##..4::6''FH  r@   z
      The variance for Student's T equals

      ```
      df / (df - 2), when df > 2
      infinity, when 1 < df <= 2
      NaN, when df <= 1
      ```
      c           	         t        j                  t        j                  | j                  d      | j                  dz
  t        j
                  | j                              }t        j                  | j                         | j                        t        j                  | j                        z  | j                  z  |z  }t        j                  t        j                  | j                  j                               }t        j                  | j                  t        j                  | j                         d      kD  |t        j                  | j                         |d            }| j                   rt        j                  t        j"                  | j                  j                               }t        j                  t        j                  | j                  t        j                  | j                         | j                              |t        j                  | j                         |d            S t%        j&                  t)        j*                  t        j                  g | j                        | j                  d      g|      S )Nrn   r9   infr   r   z.variance not defined for components of df <= 1r   )r   ry   r
   r   r   	ones_liker]   r[   r!   squarer    rt   r   r   r   r   r$   r   r	   r   r   r   )r5   denomvarr   result_where_definedr   s         r7   	_variancezStudentT._varianceA  s    "%tww|DGG$&E >>$1134::F??4::&')-1389C ((266!:!:!<
=C$--)..!8!8!:B??t..0#EBD HHRVV4::#<#<#>?c


ggnnT446djjIK 
..002Ce
DF F //##..4::6''JL    r@   c                 @    t        j                  | j                        S rF   )r   r,   r   rB   s    r7   _modezStudentT._modek  s    dhh''r@   )FTr   rF   )__name__
__module____qualname____doc__r   
deprecatedr2   staticmethodr?   propertyr   r   r    rI   rM   rP   rS   rf   rk   rh   ri   r}   r   r_   AppendDocstringr   r   r   __classcell__r6   s   @r7   r   r   *   s   aF ;'
  ##44l : :      E :(+&FC3K
/ %$$&'	'( %$$ &
   B(r@   c                   Z     e Zd ZdZ ej
                  ddd      	 	 	 d fd	       Z xZS )r   zBStudentT with `df = floor(abs(df))` and `scale = softplus(scale)`.r   zLUse `tfd.StudentT(tf.floor(tf.abs(df)), loc, tf.nn.softplus(scale)) instead.Tr   c           	      L   t        t                     }t        j                  |||g      5 }t        t
        |   t        j                  t        j                  |            |t        j                  |d      |||       d d d        || _        y # 1 sw Y   || _        y xY w)Nr   softplus_scaler   )r   r   r    r#   r$   r   )r'   r(   r   r)   r1   r   r2   r
   floorrs   r   softplus_parametersr4   s	           r7   r2   z'StudentTWithAbsDfSoftplusScale.__init__r  s     fhJ	b%[	1 T*D:^^HLL,-E(89%) ;  "D "Ds   ABB#)FTr   )r   r   r   r   r   r   r2   r   r   s   @r7   r   r   o  s;    J;(	 ##4"
"r@   )r   numpyrt   tensorflow.python.frameworkr   r   r   r   tensorflow.python.opsr   r   r	   r
   r   r   r   #tensorflow.python.ops.distributionsr   r   r_   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   __all__Distributionr   r    r@   r7   <module>r      s    &  3 . + 4 + + 2 * $ , 2 < I . 6 $ '()A(|(( A( *A(H
"X "r@   