
    AVh/                     Z   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 ej8                  ee      dd       Zy)zThe Gamma distribution class.    N)constant_op)dtypes)ops)tensor_shape)	array_ops)	check_ops)control_flow_ops)math_ops)nn)
random_ops)distribution)kullback_leibler)util)deprecation)	tf_exportGamma"GammaWithSoftplusConcentrationRatezdistributions.Gamma)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d
 Zd Zd Zd Z ej"                  d      dd       Zd Zd Zd Zd Zd Zd Zd Zd Z ej"                  d      d        Zd Z xZS )r   a	  Gamma distribution.

  The Gamma distribution is defined over positive real numbers using
  parameters `concentration` (aka "alpha") and `rate` (aka "beta").

  #### Mathematical Details

  The probability density function (pdf) is,

  ```none
  pdf(x; alpha, beta, x > 0) = x**(alpha - 1) exp(-x beta) / Z
  Z = Gamma(alpha) beta**(-alpha)
  ```

  where:

  * `concentration = alpha`, `alpha > 0`,
  * `rate = beta`, `beta > 0`,
  * `Z` is the normalizing constant, and,
  * `Gamma` is the [gamma function](
    https://en.wikipedia.org/wiki/Gamma_function).

  The cumulative density function (cdf) is,

  ```none
  cdf(x; alpha, beta, x > 0) = GammaInc(alpha, beta x) / Gamma(alpha)
  ```

  where `GammaInc` is the [lower incomplete Gamma function](
  https://en.wikipedia.org/wiki/Incomplete_gamma_function).

  The parameters can be intuited via their relationship to mean and stddev,

  ```none
  concentration = alpha = (mean / stddev)**2
  rate = beta = mean / stddev**2 = concentration / mean
  ```

  Distribution parameters are automatically broadcast in all functions; see
  examples for details.

  Warning: The samples of this distribution are always non-negative. However,
  the samples that are smaller than `np.finfo(dtype).tiny` are rounded
  to this value, so it appears more often than it should.
  This should only be noticeable when the `concentration` is very small, or the
  `rate` is very large. See note in `tf.random.gamma` docstring.

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

  #### Examples

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

  dist = tfd.Gamma(concentration=3.0, rate=2.0)
  dist2 = tfd.Gamma(concentration=[3.0, 4.0], rate=[2.0, 3.0])
  ```

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

  ```python
  concentration = tf.constant(3.0)
  rate = tf.constant(2.0)
  dist = tfd.Gamma(concentration, rate)
  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, [concentration, rate])
  ```

  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                  |      t        j                  |      gng       5  t        j                  |d      | _	        t        j                  |d      | _
        t        j                  | j                  | j                  g       ddd       ddd       t        t        | ;  | j                  j                  ||t         j"                  || j                  | j                  g|       y# 1 sw Y   dxY w# 1 sw Y   hxY w)a  Construct Gamma with `concentration` and `rate` parameters.

    The parameters `concentration` and `rate` must be shaped in a way that
    supports broadcasting (e.g. `concentration + rate` is a valid operation).

    Args:
      concentration: Floating point tensor, the concentration params of the
        distribution(s). Must contain only positive values.
      rate: Floating point tensor, the inverse scale params of the
        distribution(s). Must contain only positive values.
      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 `concentration` and `rate` are different dtypes.
    valuesconcentrationnamerateN)dtypevalidate_argsallow_nan_statsreparameterization_type
parametersgraph_parentsr   )dictlocalsr   
name_scopecontrol_dependenciesr   assert_positiver   identity_concentration_rateassert_same_float_dtypesuperr   __init__r    r   FULLY_REPARAMETERIZEDselfr   r   r!   r"   r   r$   	__class__s          Y/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/distributions/gamma.pyr0   zGamma.__init__|   s(   J fhJ	mT%:	; 	/t##  
#
#M
2

#
#D
)% !" / (001''6:
))  $**-	//	/ 
%!!''#' , B B**zz#   / /	/ 	/s%   AE0A$D7E7E 	<EEc           	      z    t        t        dt        j                  | t        j
                        gdz              S )Nr   r   r       )r&   zipr   convert_to_tensorr   int32)sample_shapes    r5   _param_shapeszGamma._param_shapes   s=    %)>)>*. )/12)3 	56 6    c                     | j                   S )zConcentration parameter.)r,   r3   s    r5   r   zGamma.concentration   s     r?   c                     | j                   S )zRate parameter.)r-   rA   s    r5   r   z
Gamma.rate   s     ::r?   c                     t        j                  t        j                  | j                        t        j                  | j                              S N)r   broadcast_dynamic_shapeshaper   r   rA   s    r5   _batch_shape_tensorzGamma._batch_shape_tensor   s7    ,,**+		"$ $r?   c                     t        j                  | j                  j                         | j                  j                               S rD   )r   broadcast_static_shaper   	get_shaper   rA   s    r5   _batch_shapezGamma._batch_shape   s7    ++$$&		 r?   c                 L    t        j                  g t        j                        S )Nr8   )r   constantr   r<   rA   s    r5   _event_shape_tensorzGamma._event_shape_tensor   s    &,,77r?   c                 ,    t        j                  g       S rD   )r   TensorShaperA   s    r5   _event_shapezGamma._event_shape   s    ##B''r?   zMNote: See `tf.random.gamma` docstring for sampling details and
      caveats.c                 t    t        j                  |g| j                  | j                  | j                  |      S )N)rF   alphabetar    seed)r   random_gammar   r   r    )r3   nrU   s      r5   	_sample_nzGamma._sample_n   s6     ""c  YYjj r?   c                 F    | j                  |      | j                         z
  S rD   )_log_unnormalized_prob_log_normalizationr3   xs     r5   	_log_probzGamma._log_prob   s!    &&q)D,C,C,EEEr?   c                 ~    | j                  |      }t        j                  | j                  | j                  |z        S rD   )_maybe_assert_valid_sampler
   igammar   r   r\   s     r5   _cdfz
Gamma._cdf   s3    ''*A ??4--tyy1}==r?   c                     | j                  |      }t        j                  | j                  dz
  |      | j                  |z  z
  S N      ?)r`   r
   xlogyr   r   r\   s     r5   rZ   zGamma._log_unnormalized_prob   s;    ''*A>>$,,r115		AEEr?   c                     t        j                  | j                        | j                  t        j                  | j                        z  z
  S rD   )r
   lgammar   logr   rA   s    r5   r[   zGamma._log_normalization   s9    OOD../  8<<		#::; <r?   c                     | j                   t        j                  | j                        z
  t        j                  | j                         z   d| j                   z
  t        j
                  | j                         z  z   S rd   )r   r
   ri   r   rh   digammarA   s    r5   _entropyzGamma._entropy   sj    ll499%&ood0012 T''' 2 2345 6r?   c                 4    | j                   | j                  z  S rD   r7   rA   s    r5   _meanzGamma._mean   s    		))r?   c                 Z    | j                   t        j                  | j                        z  S rD   )r   r
   squarer   rA   s    r5   	_variancezGamma._variance   s     		 :::r?   c                 Z    t        j                  | j                        | j                  z  S rD   )r
   sqrtr   r   rA   s    r5   _stddevzGamma._stddev   s     ==++,tyy88r?   zThe mode of a gamma distribution is `(shape - 1) / rate` when
      `shape > 1`, and `NaN` otherwise. If `self.allow_nan_stats` is `False`,
      an exception will be raised rather than returning `NaN`.c                    | j                   dz
  | j                  z  }| j                  rt        j                  | j                         t        j                  t        j                  | j                  j                               d      }t        j                  | j                   dkD  ||      S t        j                  t        j                  t        j                   g | j                        | j                   d      g|      S )Nre   r8   nanr   z,mode not defined when any concentration <= 1)message)r   r   r"   r   fillbatch_shape_tensornparrayrv   r    as_numpy_dtypewhere_v2r	   with_dependenciesr   assert_lessones)r3   moderv   s      r5   _modezGamma._mode  s    
 #tyy0DNN

!
!
#
((266!:!:!<
=c  2 2R 7sCC//


nnR,  DF1
  r?   c                     t        j                  |g| j                         | j                  s|S t	        j
                  t        j                  |      g|      S )N)tensorsr    )r   r.   r    r!   r	   r~   r*   r\   s     r5   r`   z Gamma._maybe_assert_valid_sample  sO    %%qcDh--!!!$/
 
r?   )FTr   rD   )__name__
__module____qualname____doc__r   
deprecatedr0   staticmethodr>   propertyr   r   rG   rK   rN   rQ   distribution_utilAppendDocstringrX   r^   rb   rZ   r[   rl   rn   rq   rt   r   r`   __classcell__r4   s   @r5   r   r   *   s   N` ;'
  ##00d 6 6
    $

8( %$$F>F<6*;9 %$$BC	C 
r?   c                   Z     e Zd ZdZ ej
                  ddd      	 	 	 d fd	       Z xZS )r   z4`Gamma` with softplus of `concentration` and `rate`.r   zMUse `tfd.Gamma(tf.nn.softplus(concentration), tf.nn.softplus(rate))` instead.Tr   c                 (   t        t                     }t        j                  |||g      5 }t        t
        |   t        j                  |d      t        j                  |d      |||       d d d        || _	        y # 1 sw Y   || _	        y xY w)Nr   softplus_concentrationr   softplus_rate)r   r   r!   r"   r   )
r&   r'   r   r(   r/   r   r0   r   softplus_parametersr2   s          r5   r0   z+GammaWithSoftplusConcentrationRate.__init__"  s     fhJ	mT%:	; t.>M)AC{{4o6%) ?  "D "Ds   ABB)FTr   )r   r   r   r   r   r   r0   r   r   s   @r5   r   r     s;    <;(	 ##8"
"r?   c                    t        j                  |d| j                  | j                  |j                  |j                  g      5  | j                  |j                  z
  t	        j
                  | j                        z  t	        j                  |j                        z   t	        j                  | j                        z
  |j                  t	        j                  | j                        z  z   |j                  t	        j                  |j                        z  z
  | j                  |j                  | j                  z  dz
  z  z   cddd       S # 1 sw Y   yxY w)aV  Calculate the batched KL divergence KL(g0 || g1) with g0 and g1 Gamma.

  Args:
    g0: instance of a Gamma distribution object.
    g1: instance of a Gamma distribution object.
    name: (optional) Name to use for created operations.
      Default is "kl_gamma_gamma".

  Returns:
    kl_gamma_gamma: `Tensor`. The batchwise KL(g0 || g1).
  kl_gamma_gammar   re   N)r   r(   r   r   r
   rk   rh   ri   )g0g1r   s      r5   _kl_gamma_gammar   9  s    ~~d,!1!12776< = ; !1!11 0 012oob../0 oob../0 bgg!66	7
 bgg!667 "''BGG"3b"89:; ; ;s   C=EErD   )r   numpyrz   tensorflow.python.frameworkr   r   r   r   tensorflow.python.opsr   r   r	   r
   r   r   #tensorflow.python.ops.distributionsr   r   r   r   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   __all__Distributionr   r   
RegisterKLr    r?   r5   <module>r      s    $  3 . + 4 + + 2 * $ , < @ I . 6 ( $%&q
L%% q
 'q
h" "4 UE*; +;r?   