
    }Yh                     x    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
mZmZ dgZ G d de          ZdS )	    )OptionalN)nanTensor)constraints)Distribution)lazy_propertylogits_to_probsprobs_to_logitsCategoricalc            	           e Zd ZdZej        ej        dZdZ	 	 	 dde	e
         de	e
         de	e         ddf fd	Zd fd
	Zd Z ej        dd          d             Zede
fd            Zede
fd            Zedej        fd            Zede
fd            Zede
fd            Zede
fd            Z ej                    fdZd Zd ZddZ xZS )r   a  
    Creates a categorical distribution parameterized by either :attr:`probs` or
    :attr:`logits` (but not both).

    .. note::
        It is equivalent to the distribution that :func:`torch.multinomial`
        samples from.

    Samples are integers from :math:`\{0, \ldots, K-1\}` where `K` is ``probs.size(-1)``.

    If `probs` is 1-dimensional with length-`K`, each element is the relative probability
    of sampling the class at that index.

    If `probs` is N-dimensional, the first N-1 dimensions are treated as a batch of
    relative probability vectors.

    .. note:: The `probs` argument must be non-negative, finite and have a non-zero sum,
              and it will be normalized to sum to 1 along the last dimension. :attr:`probs`
              will return this normalized value.
              The `logits` argument will be interpreted as unnormalized log probabilities
              and can therefore be any real number. It will likewise be normalized so that
              the resulting probabilities sum to 1 along the last dimension. :attr:`logits`
              will return this normalized value.

    See also: :func:`torch.multinomial`

    Example::

        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ]))
        >>> m.sample()  # equal probability of 0, 1, 2, 3
        tensor(3)

    Args:
        probs (Tensor): event probabilities
        logits (Tensor): event log probabilities (unnormalized)
    )probslogitsTNr   r   validate_argsreturnc                    |d u |d u k    rt          d          |G|                                dk     rt          d          ||                    dd          z  | _        nJ|J |                                dk     rt          d          ||                    dd          z
  | _        || j        n| j        | _        | j                                        d         | _        | j        	                                dk    r!| j                                        d d         nt          j                    }t                                          ||	           d S )
Nz;Either `probs` or `logits` must be specified, but not both.   z3`probs` parameter must be at least one-dimensional.T)keepdimz4`logits` parameter must be at least one-dimensional.)dimr   r   )
ValueErrorr   sumr   	logsumexpr   _paramsize_num_events
ndimensiontorchSizesuper__init__)selfr   r   r   batch_shape	__class__s        q/var/www/tools.fuzzalab.pt/emblema-extractor/venv/lib/python3.11/site-packages/torch/distributions/categorical.pyr!   zCategorical.__init__8   sV    TMv~..M   yy{{Q !VWWW2t!<!<<DJJ%%%zz||a !WXXX 6#3#3D#3#I#IIDK$)$5djj4;;++--b1'+{'='='?'?!'C'CDKss## 	 	MBBBBB    c                    |                      t          |          }t          j        |          }|t          j        | j        f          z   }d| j        v r+| j                            |          |_        |j        |_        d| j        v r+| j	                            |          |_	        |j	        |_        | j        |_        t          t          |                              |d           | j        |_        |S )Nr   r   Fr   )_get_checked_instancer   r   r   r   __dict__r   expandr   r   r    r!   _validate_args)r"   r#   	_instancenewparam_shaper$   s        r%   r*   zCategorical.expandS   s    ((i@@j--!EJ0@/B$C$CCdm##
))+66CICJt}$$++K88CJCJ*k3((E(JJJ!0
r&   c                 &     | j         j        |i |S N)r   r-   )r"   argskwargss      r%   _newzCategorical._newb   s    t{////r&   r   )is_discrete	event_dimc                 <    t          j        d| j        dz
            S )Nr   r   )r   integer_intervalr   r"   s    r%   supportzCategorical.supporte   s    +At/?!/CDDDr&   c                 *    t          | j                  S r0   )r
   r   r8   s    r%   r   zCategorical.logitsi   s    tz***r&   c                 *    t          | j                  S r0   )r	   r   r8   s    r%   r   zCategorical.probsm   s    t{+++r&   c                 4    | j                                         S r0   )r   r   r8   s    r%   r.   zCategorical.param_shapeq   s    {!!!r&   c                     t          j        |                                 t          | j        j        | j        j                  S Ndtypedevicer   full_extended_shaper   r   r@   rA   r8   s    r%   meanzCategorical.meanu   =    z  ""*":$	
 
 
 	
r&   c                 8    | j                             d          S )Nr   )r   )r   argmaxr8   s    r%   modezCategorical.mode~   s    z  R (((r&   c                     t          j        |                                 t          | j        j        | j        j                  S r>   rB   r8   s    r%   variancezCategorical.variance   rF   r&   c                 H   t          |t          j                  st          j        |          }| j                            d| j                  }t          j        ||                                d          j        }|                    | 	                    |                    S )Nr   T)

isinstancer   r   r   reshaper   multinomialnumelTrD   )r"   sample_shapeprobs_2d
samples_2ds       r%   samplezCategorical.sample   s    ,
33 	4 :l33L:%%b$*:;;&x1C1C1E1EtLLN
!!$"6"6|"D"DEEEr&   c                 ,   | j         r|                     |           |                                                    d          }t	          j        || j                  \  }}|dd df         }|                    d|                              d          S )Nr   .r   )	r+   _validate_samplelong	unsqueezer   broadcast_tensorsr   gathersqueeze)r"   valuelog_pmfs      r%   log_probzCategorical.log_prob   s     	)!!%(((

&&r**0DDwc2A2g~~b%((00444r&   c                     t          j        | j        j                  j        }t          j        | j        |          }|| j        z  }|                    d           S )N)minr   )r   finfor   r@   ra   clampr   r   )r"   min_realr   p_log_ps       r%   entropyzCategorical.entropy   sN    ;t{0115T[h7774:%Br&   c                    | j         }t          j        |t          j        | j        j                  }|                    ddt          | j                  z  z             }|r|	                    d| j        z             }|S )Nr?   )r   )r   )
r   r   arangerX   r   rA   viewlen_batch_shaper*   )r"   r*   
num_eventsvaluess       r%   enumerate_supportzCategorical.enumerate_support   ss    %
j
4;CUVVVUTC0A,B,B%BBCC 	>]]54+<#<==Fr&   )NNNr0   )T) __name__
__module____qualname____doc__r   simplexreal_vectorarg_constraintshas_enumerate_supportr   r   boolr!   r*   r3   dependent_propertyr9   r   r   r   propertyr   r   r.   rE   rI   rK   rU   r_   rf   rn   __classcell__)r$   s   @r%   r   r      sT       $ $L !, 3{?VWWO  #'#'(,	C CC  C  ~	C
 
C C C C C C6     0 0 0 $[#BBBE E CBE + + + + ]+ ,v , , , ], "UZ " " " X" 
f 
 
 
 X
 )f ) ) ) X) 
& 
 
 
 X
 #-%*,, F F F F5 5 5            r&   )typingr   r   r   r   torch.distributionsr    torch.distributions.distributionr   torch.distributions.utilsr   r	   r
   __all__r    r&   r%   <module>r      s                   + + + + + + 9 9 9 9 9 9 U U U U U U U U U U /X X X X X, X X X X Xr&   