U
    Ãmœdœ@  ã                4   @   s€  d 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mZ d•dd„Zd	d
„ Zd–dd„Zdd„ Zdd„ Zdd„ Zd—dd„Zd˜dd„Zd™dd„Zdšdd„Zd›dd„Zdœdd „Zd�d#d$„Zdžd&d'„Zed(k�r|ed)ƒ ed*ƒ d+d+d+d+d+gZd,d-d.d/d0gZeD ]Zeeeƒƒ � qþeD ]Zeeeƒƒ �qeeeƒƒ eeeƒƒ d1d2d3d4d5d6d+d7d8d9d:d;d<gZ e
 !d=¡ e
 "d>¡ e
 #d?¡ e $dd!d@¡Z%e
 &e%ee%ƒ¡ e
 !d=¡ e
 "dA¡ e
 #d?¡ e $dd!dB¡Z%e
 &e%eeee%d!e% ƒƒ¡ e 'dddCgdDdDdDgdEdDdFgg¡Z(e( )d¡Z*e( )d!¡Z+ee*ƒZ,ee+ƒZ-ee(ƒZ.ee*e+e(ƒZ/ee+e*e(ƒZ0edej1ƒe 2e*e+¡ Z3edej1ƒe 2e+e*¡ Z4ee*e+e(ƒZ5edGƒ ee,e-e.e/e0e3e4e5ƒ edHƒ e 'dIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\dYd]d^d_d`dadbdcdddedfdgdhdidjdkdld^dmdndodpdqdrdsdtdudvdwdxg2¡ZeeƒZ6e edyƒ edzƒ ed{ƒ ed|ƒ ed}ƒ ed~e* ƒ edƒ d!e*d  Z7ed€e7 ƒ ee7d!e7 gƒZ8ed�e8 ƒ ed‚e8e7e 9d¡  e/f ƒ edƒƒ ed„e7e,d! e 9d…¡ f ƒ ed†ƒ ed‡ƒ e 'dˆdˆd‰gdCdCdCgdFdCd<gg¡Z:ee:ƒ edŠƒ ed‹e ;dee:d! ƒee:d ƒg¡d! e 9d…¡  ƒ edŒƒ e 'd�dŽd�gd�d‘d’gd“d,d”gg¡Z<dS )Ÿa:  
Information Theoretic and Entropy Measures

References
----------
Golan, As. 2008. "Information and Entropy Econometrics -- A Review and
    Synthesis." Foundations And Trends in Econometrics 2(1-2), 1-145.

Golan, A., Judge, G., and Miller, D.  1996.  Maximum Entropy Econometrics.
    Wiley & Sons, Chichester.
é    )ÚlzipÚlmap)ÚstatsN)Úpyplot)Ú	logsumexpc                 C   sf   |dkrt | ƒS t | ¡} t| jƒ}d||< | j|d�}t t | | |¡ ¡j	|d�¡}|| }|S )a-  
    Compute the log of the sum of exponentials log(e^{a_1}+...e^{a_n}) of a

    Avoids numerical overflow.

    Parameters
    ----------
    a : array_like
        The vector to exponentiate and sum
    axis : int, optional
        The axis along which to apply the operation.  Defaults is None.

    Returns
    -------
    sum(log(exp(a)))

    Notes
    -----
    This function was taken from the mailing list
    http://mail.scipy.org/pipermail/scipy-user/2009-October/022931.html

    This should be superceded by the ufunc when it is finished.
    Né   )Úaxis)
Úsp_logsumexpÚnpÚasarrayÚlistÚshapeÚmaxÚlogÚexpZreshapeÚsum)Úar   ZshpZa_maxÚsZlse© r   úU/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/statsmodels/sandbox/infotheo.pyr   -   s    

"r   c                 C   sD   t  | ¡} t  t  | ¡d¡r8t  | dk¡r8t  | dk¡s<dS dS dS )zC
    Checks to see if `X` is a proper probability distribution
    r   r   FTN)r
   r   Zallcloser   Úall©ÚXr   r   r   Ú_isproperdistQ   s    
.r   Úefc                 C   sè   t | ƒ}|dkr t t |¡¡}|dkr@t |t | ¡ | ¡}|dkrät | ¡t | ¡ }t || ¡}t 	| ¡\}}t 
|¡}d}|d }	|||d < td|ƒD ]>}
||
 |	| k rÆ||||
 < q¤||
 }	|d7 }||||
 < q¤|S )zû
    Discretize `X`

    Parameters
    ----------
    bins : int, optional
        Number of bins.  Default is floor(sqrt(N))
    method : str
        "ef" is equal-frequency binning
        "ew" is equal-width binning

    Examples
    --------
    Nr   Úewr   r   )Úlenr
   ÚfloorÚsqrtÚceilr   Zrankdatar   ÚminZfastsortZzerosÚrange)r   ÚmethodZnbinsZnobsZdiscreteÚwidthZsvecZivecZbinnumÚbaseÚir   r   r   Ú
discretize[   s(    
r&   c                 C   s   t  |¡t  | ¡ S )z¶
    There is a one-to-one transformation of the entropy value from
    a log base b to a log base a :

    H_{b}(X)=log_{b}(a)[H_{a}(X)]

    Returns
    -------
    log_{b}(a)
    )r
   r   )r   Úbr   r   r   Úlogbasechangeƒ   s    r(   c                 C   s   t tjdƒ|  S )z$
    Converts from nats to bits
    é   ©r(   r
   Úer   r   r   r   Ú
natstobits�   s    r,   c                 C   s   t dtjƒ|  S )z$
    Converts from bits to nats
    r)   r*   r   r   r   r   Ú
bitstonats–   s    r-   r)   c                 C   sh   t  | ¡} t  | dk¡r&t  | dk¡s.tdƒ‚t  t  | t  | ¡ ¡¡ }|dkr`td|ƒ| S |S dS )aC  
    This is Shannon's entropy

    Parameters
    ----------
    logbase, int or np.e
        The base of the log
    px : 1d or 2d array_like
        Can be a discrete probability distribution, a 2d joint distribution,
        or a sequence of probabilities.

    Returns
    -----
    For log base 2 (bits) given a discrete distribution
        H(p) = sum(px * log2(1/px) = -sum(pk*log2(px)) = E[log2(1/p(X))]

    For log base 2 (bits) given a joint distribution
        H(px,py) = -sum_{k,j}*w_{kj}log2(w_{kj})

    Notes
    -----
    shannonentropy(0) is defined as 0
    r   r   ú&px does not define proper distributionr)   N)r
   r   r   Ú
ValueErrorr   Ú
nan_to_numÚlog2r(   )ÚpxÚlogbaseÚentropyr   r   r   Úshannonentropyž   s    
r5   c                 C   s\   t  | ¡} t  | dk¡r&t  | dk¡s.tdƒ‚|dkrLtd|ƒ t  | ¡ S t  | ¡ S dS )zÌ
    Shannon's information

    Parameters
    ----------
    px : float or array_like
        `px` is a discrete probability distribution

    Returns
    -------
    For logbase = 2
    np.log2(px)
    r   r   r.   r)   N)r
   r   r   r/   r(   r1   )r2   r3   r   r   r   ÚshannoninfoÁ   s    
r6   c              	   C   s€   t | ƒrt |ƒstdƒ‚|dk	r0t |ƒs0tdƒ‚|dkrDt || ¡}t |t t || ¡¡ ¡}|dkrn|S td|ƒ| S dS )a˜  
    Return the conditional entropy of X given Y.

    Parameters
    ----------
    px : array_like
    py : array_like
    pxpy : array_like, optional
        If pxpy is None, the distributions are assumed to be independent
        and conendtropy(px,py) = shannonentropy(px)
    logbase : int or np.e

    Returns
    -------
    sum_{kj}log(q_{j}/w_{kj}

    where q_{j} = Y[j]
    and w_kj = X[k,j]
    ú1px or py is not a proper probability distributionNú&pxpy is not a proper joint distribtionr)   )r   r/   r
   Úouterr   r0   r1   r(   )r2   ÚpyÚpxpyr3   Úcondentr   r   r   Úcondentropy×   s    r=   c                 C   s`   t | ƒrt |ƒstdƒ‚|dk	r0t |ƒs0tdƒ‚|dkrDt || ¡}t| |d�t| |||d� S )aC  
    Returns the mutual information between X and Y.

    Parameters
    ----------
    px : array_like
        Discrete probability distribution of random variable X
    py : array_like
        Discrete probability distribution of random variable Y
    pxpy : 2d array_like
        The joint probability distribution of random variables X and Y.
        Note that if X and Y are independent then the mutual information
        is zero.
    logbase : int or np.e, optional
        Default is 2 (bits)

    Returns
    -------
    shannonentropy(px) - condentropy(px,py,pxpy)
    r7   Nr8   ©r3   )r   r/   r
   r9   r5   r=   ©r2   r:   r;   r3   r   r   r   Ú
mutualinfo÷   s    ÿr@   c                 C   s`   t | ƒrt |ƒstdƒ‚|dk	r0t |ƒs0tdƒ‚|dkrDt || ¡}t| |||d�t||d� S )aa  
    An information theoretic correlation measure.

    Reflects linear and nonlinear correlation between two random variables
    X and Y, characterized by the discrete probability distributions px and py
    respectively.

    Parameters
    ----------
    px : array_like
        Discrete probability distribution of random variable X
    py : array_like
        Discrete probability distribution of random variable Y
    pxpy : 2d array_like, optional
        Joint probability distribution of X and Y.  If pxpy is None, X and Y
        are assumed to be independent.
    logbase : int or np.e, optional
        Default is 2 (bits)

    Returns
    -------
    mutualinfo(px,py,pxpy,logbase=logbase)/shannonentropy(py,logbase=logbase)

    Notes
    -----
    This is also equivalent to

    corrent(px,py,pxpy) = 1 - condent(px,py,pxpy)/shannonentropy(py)
    r7   Nr8   r>   )r   r/   r
   r9   r@   r5   r?   r   r   r   Úcorrent  s    ÿrA   c                 C   sd   t | ƒrt |ƒstdƒ‚|dk	r0t |ƒs0tdƒ‚|dkrDt || ¡}t| |||d�t|| ||d� S )ak  
    An information theoretic covariance measure.

    Reflects linear and nonlinear correlation between two random variables
    X and Y, characterized by the discrete probability distributions px and py
    respectively.

    Parameters
    ----------
    px : array_like
        Discrete probability distribution of random variable X
    py : array_like
        Discrete probability distribution of random variable Y
    pxpy : 2d array_like, optional
        Joint probability distribution of X and Y.  If pxpy is None, X and Y
        are assumed to be independent.
    logbase : int or np.e, optional
        Default is 2 (bits)

    Returns
    -------
    condent(px,py,pxpy,logbase=logbase) + condent(py,px,pxpy,
            logbase=logbase)

    Notes
    -----
    This is also equivalent to

    covent(px,py,pxpy) = condent(px,py,pxpy) + condent(py,px,pxpy)
    r7   Nr8   r>   )r   r/   r
   r9   r<   r?   r   r   r   Úcovent=  s    ÿrB   r   ÚRc                 C   sº   t | ƒstdƒ‚t|ƒ}|dkrBt| ƒ}|dkr>td|ƒ| S |S dt|ƒ ¡ ks\|tjkrnt 	t 
| ¡¡ S | | } t 	|  ¡ ¡}|dkrœdd|  | S dd|  td|ƒ | S dS )as  
    Renyi's generalized entropy

    Parameters
    ----------
    px : array_like
        Discrete probability distribution of random variable X.  Note that
        px is assumed to be a proper probability distribution.
    logbase : int or np.e, optional
        Default is 2 (bits)
    alpha : float or inf
        The order of the entropy.  The default is 1, which in the limit
        is just Shannon's entropy.  2 is Renyi (Collision) entropy.  If
        the string "inf" or numpy.inf is specified the min-entropy is returned.
    measure : str, optional
        The type of entropy measure desired.  'R' returns Renyi entropy
        measure.  'T' returns the Tsallis entropy measure.

    Returns
    -------
    1/(1-alpha)*log(sum(px**alpha))

    In the limit as alpha -> 1, Shannon's entropy is returned.

    In the limit as alpha -> inf, min-entropy is returned.
    z+px is not a proper probability distributionr   r)   ÚinfN)r   r/   Úfloatr5   r(   ÚstrÚlowerr
   rD   r   r   r   )r2   Úalphar3   ÚmeasureZgenentr   r   r   Úrenyientropyk  s    rJ   ÚTc                 C   s   dS )a“  
    Generalized cross-entropy measures.

    Parameters
    ----------
    px : array_like
        Discrete probability distribution of random variable X
    py : array_like
        Discrete probability distribution of random variable Y
    pxpy : 2d array_like, optional
        Joint probability distribution of X and Y.  If pxpy is None, X and Y
        are assumed to be independent.
    logbase : int or np.e, optional
        Default is 2 (bits)
    measure : str, optional
        The measure is the type of generalized cross-entropy desired. 'T' is
        the cross-entropy version of the Tsallis measure.  'CR' is Cressie-Read
        measure.
    Nr   )r2   r:   r;   rH   r3   rI   r   r   r   Úgencrossentropyž  s    rL   Ú__main__zQFrom Golan (2008) "Information and Entropy Econometrics -- A Review and Synthesisz	Table 3.1gš™™™™™É?gÏ÷Sã¥›Ô?g;ßO�—n²?g'1¬Zà?g²�ï§ÆK·?gü©ñÒMbp?gñhãˆµøä>g-Cëâ6?gü©ñÒMbP?g{®Gáz„?gš™™™™™¹?g333333Ã?g      Ð?g333333Ó?gffffffÖ?gš™™™™™Ù?gÍÌÌÌÌÌÜ?g      à?éo   ZInformationZProbabilityi¡† ZEntropyée   gUUUUUUÕ?gÇqÇq¼?gÇqÇq¬?gUUUUUUÅ?z	Table 3.3zdiscretize functionsg3333335@g     @F@g      ?@g     €3@gÍÌÌÌÌLD@gš™™™™YC@g333333&@gš™™™™™/@gfffffæ?@gÍÌÌÌÌÌ9@g3333334@gffffff,@g      8@g      5@gš™™™™™&@g      2@gÍÌÌÌÌL0@g3333336@g333333@gÍÌÌÌÌÌ;@gÍÌÌÌÌŒA@gÍÌÌÌÌÌ-@gš™™™™1@g333333<@gffffff0@g     €0@g      G@g      #@gÍÌÌÌÌÌ2@gÍÌÌÌÌ@@gš™™™™:@gš™™™™0@g333333@gffffff5@g      4@gÍÌÌÌÌL=@gš™™™™™ @g     €6@gš™™™™™)@gfffffæ:@g     €9@gfffffæ6@gffffff&@g33333³4@g333333:@gš™™™™™"@gš™™™™™%@g333333/@z0Example in section 3.6 of Golan, using table 3.3z'Bounding errors using Fano's inequalityz"H(P_{e}) + P_{e}log(K-1) >= H(X|Y)zor, a weaker inequalityzP_{e} >= [H(X|Y) - 1]/log(K)z	P(x) = %sz?X = 3 has the highest probability, so this is the estimate Xhatz1The probability of error Pe is 1 - p(X=3) = %0.4gzH(Pe) = %0.4g and K=3z-H(Pe) + Pe*log(K-1) = %0.4g >= H(X|Y) = %0.4gzor using the weaker inequalityz'Pe = %0.4g >= [H(X) - 1]/log(K) = %0.4gé   z>Consider now, table 3.5, where there is additional informationz.The conditional probabilities of P(X|Y=y) are g        g      ð?z2The probability of error given this information iszPe = [H(X|Y) -1]/log(K) = %0.4gz+such that more information lowers the errorgV-²á?g“V-Ò?gw¾Ÿ/ÝÄ?gÃõ(\�ÂÝ?g+‡ÙÎ÷Ó?g%�•C‹Ì?gáz®GáÚ?gP�—nƒÐ?)N)r   N)r)   )r)   )Nr)   )r)   )r)   )r)   )r   r)   rC   )r   r)   rK   )=Ú__doc__Zstatsmodels.compat.pythonr   r   Zscipyr   Únumpyr
   Z
matplotlibr   ZpltZscipy.specialr   r	   r   r&   r(   r,   r-   r5   r6   r=   r@   rA   rB   rJ   rL   Ú__name__Úprintr   ÚYr%   ÚpZsubplotZylabelZxlabelZlinspaceÚxZplotÚarrayÚwr   r2   r:   ZH_XZH_YZH_XYZ	H_XgivenYZ	H_YgivenXr+   r4   ZD_YXZD_XYZI_XYZdiscXÚpeZH_per1   Zw2ZmeanZmarkovchainr   r   r   r   Ú<module>   sò   "
$

(
#

 

(
.
3







"

                                   ýÿ"6