o
    2h/                     @   s  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dG dd dejZG dd deZeeedddZdS )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                       s   e Zd ZdZejdddd			 d0 fdd	Zed	d
 Ze	dd Z
e	dd Zdd Zdd Zdd Zdd Zedd1ddZdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zed+d,d- Zd.d/ Z  ZS )2r   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_onceFc              	      s   t t }tj|||gdB}t|rt|t|gng ! tj|dd| _	tj|dd| _
t| j	| j
g W d   n1 sDw   Y  W d   n1 sSw   Y  tt| j| j	j||tj|| j	| j
g|d dS )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__ d/var/www/html/chatgem/venv/lib/python3.10/site-packages/tensorflow/python/ops/distributions/gamma.pyr-   |   s>   
%



zGamma.__init__c                 C   s    t tdtj| tjdgd S )Nr   r   r      )r#   zipr   convert_to_tensorr   int32)sample_shaper3   r3   r4   _param_shapes   s   zGamma._param_shapesc                 C      | j S )zConcentration parameter.)r)   r0   r3   r3   r4   r         zGamma.concentrationc                 C   r=   )zRate parameter.)r*   r>   r3   r3   r4   r      r?   z
Gamma.ratec                 C   s   t t | jt | jS N)r   broadcast_dynamic_shapeshaper   r   r>   r3   r3   r4   _batch_shape_tensor   s   

zGamma._batch_shape_tensorc                 C   s   t | j | j S r@   )r   broadcast_static_shaper   	get_shaper   r>   r3   r3   r4   _batch_shape   s   zGamma._batch_shapec                 C   s   t jg tjdS )Nr6   )r   constantr   r:   r>   r3   r3   r4   _event_shape_tensor   s   zGamma._event_shape_tensorc                 C   s
   t g S r@   )r   TensorShaper>   r3   r3   r4   _event_shape   s   
zGamma._event_shapezMNote: See `tf.random.gamma` docstring for sampling details and
      caveats.Nc                 C   s   t j|g| j| j| j|dS )N)rB   alphabetar   seed)r   random_gammar   r   r   )r0   nrM   r3   r3   r4   	_sample_n   s   zGamma._sample_nc                 C   s   |  ||   S r@   )_log_unnormalized_prob_log_normalizationr0   xr3   r3   r4   	_log_prob      zGamma._log_probc                 C   s   |  |}t| j| j| S r@   )_maybe_assert_valid_sampler	   igammar   r   rS   r3   r3   r4   _cdf   s   
z
Gamma._cdfc                 C   s&   |  |}t| jd || j|  S N      ?)rW   r	   xlogyr   r   rS   r3   r3   r4   rQ      s   
zGamma._log_unnormalized_probc                 C   s   t | j| jt | j  S r@   )r	   lgammar   logr   r>   r3   r3   r4   rR      s   
zGamma._log_normalizationc                 C   s4   | j t| j t| j  d| j  t| j   S rZ   )r   r	   r^   r   r]   digammar>   r3   r3   r4   _entropy   s   


zGamma._entropyc                 C   s   | j | j S r@   r5   r>   r3   r3   r4   _mean   s   zGamma._meanc                 C   s   | j t| j S r@   )r   r	   squarer   r>   r3   r3   r4   	_variance   rV   zGamma._variancec                 C   s   t | j| j S r@   )r	   sqrtr   r   r>   r3   r3   r4   _stddev   rV   zGamma._stddevzThe 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                 C   sv   | j d | j }| jr(tj|  tjtj| j	
 ddd}t| j dk||S ttjtg | j	| j ddg|S )Nr[   r6   nanr   z,mode not defined when any concentration <= 1)message)r   r   r   r   fillbatch_shape_tensornparrayrf   r   as_numpy_dtypewhere_v2r   with_dependenciesr   assert_lessones)r0   moderf   r3   r3   r4   _mode  s"   zGamma._modec                 C   s0   t j|g| jd | js|S tt |g|S )N)tensorsr   )r   r+   r   r   r   rn   r'   rS   r3   r3   r4   rW     s   z Gamma._maybe_assert_valid_sample)FTr   r@   )__name__
__module____qualname____doc__r   
deprecatedr-   staticmethodr<   propertyr   r   rC   rF   rH   rJ   distribution_utilAppendDocstringrP   rU   rY   rQ   rR   r`   ra   rc   re   rr   rW   __classcell__r3   r3   r1   r4   r   *   sL    P2



c                       s8   e Zd ZdZejdddd			 d	 fdd	Z  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   Fc                    st   t t }tj|||gd}tt| jtj|ddtj|dd|||d W d    n1 s0w   Y  || _	d S )Nr   softplus_concentrationr   softplus_rate)r   r   r   r   r   )
r#   r$   r   r%   r,   r   r-   r
   softplus_parametersr/   r1   r3   r4   r-   "  s   


z+GammaWithSoftplusConcentrationRate.__init__)FTr   )rt   ru   rv   rw   r   rx   r-   r}   r3   r3   r1   r4   r     s    c                 C   s   t j|d| j| j|j|jgd= | j|j t| j t|j t| j |jt| j  |jt|j  | j|j| j d   W  d   S 1 sPw   Y  dS )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   r[   N)r   r%   r   r   r	   r_   r]   r^   )g0g1r   r3   r3   r4   _kl_gamma_gamma9  s"   




$r   r@   )rw   numpyrj   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   r3   r3   r3   r4   <module>   s4   
 u
