Ë
    £�Dj¢B  ã                   óÒ  — 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 dCd„Zd„ ZdDd	„Zd
„ Zd„ Zd„ ZdEd„ZdEd„ZdFd„ZdEd„ZdEd„ZdEd„ZdGd„ZdHd„Zedk(  �r� ed«        ed«       g d¢Zg d¢ZeD ]  Z e ee«      «       Œ eD ]  Z e ee«      «       Œ  e ee«      «        e ee«      «       g d¢Z  e
jB                  d«        e
jD                  d«        e
jF                  d«        ejH                  ddd «      Z% e
jL                  e% ee%«      «        e
jB                  d«        e
jD                  d!«        e
jF                  d«        ejH                  ddd"«      Z% e
jL                  e% ee ee%de%z
  «      «      «        ejN                  g d#¢g d$¢g d%¢g«      Z(e(jS                  d«      Z*e(jS                  d«      Z+ ee*«      Z, ee+«      Z- ee(«      Z. ee*e+e(«      Z/ ee+e*e(«      Z0 edejb                  «       ejd                  e*e+«      z  Z3 edejb                  «       ejd                  e+e*«      z  Z4 ee*e+e(«      Z5 ed&«        ee,e-e.e/e0e3e4e5«        ed'«        ejN                  g d(¢«      Z ee«      Z6e  ed)«        ed*«        ed+«        ed,«        ed-«        ed.e*z  «        ed/«       de*d   z
  Z7 ed0e7z  «        ee7de7z
  g«      Z8 ed1e8z  «        ed2e8e7 ejr                  d«      z  z   e/fz  «        ed3«        ed4e7d5›d6e,dz
   ejr                  d7«      z  d5›�«        ed8«        ed9«        ejN                  g d:¢g d;¢g d<¢g«      Z: ee:«        ed=«        ed> ejv                  d ee:d   «       ee:d   «      g«      dz
   ejr                  d7«      z  z  «        ed?«        ejN                  g d@¢g dA¢g dB¢g«      Z<yy)Ia:  
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                 ó@  — |€t        | «      S t        j                  | «      } t        | j                  «      }d||<   | j                  |¬«      }t        j                  t        j                  | |j                  |«      z
  «      j                  |¬«      «      }||z   }|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.
    é   )Úaxis)
Úsp_logsumexpÚnpÚasarrayÚlistÚshapeÚmaxÚlogÚexpÚreshapeÚsum)Úar
   ÚshpÚa_maxÚsÚlses         ú`C:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\statsmodels/sandbox/infotheo.pyr   r   -   s‡   € ð0 €|ä˜A‹ÐÜ
�
‰
�1‹€AÜ
ˆq�w‰w‹-€CØ€Cˆ�IØ�E‰E�tˆEÓ€EÜ
�‰Œr�v‰v�a˜%Ÿ-™-¨Ó,Ñ,Ó-×1Ñ1°tÐ1Ó<Ó=€AØ�1‰9€CØ€Jó    c                 óâ   — t        j                  | «      } t        j                  t        j                  | «      d«      r0t        j                  | dk\  «      rt        j                  | dk  «      syy)zC
    Checks to see if `X` is a proper probability distribution
    r	   r   FT)r   r   Úallcloser   Úall©ÚXs    r   Ú_isproperdistr!   Q   sI   € ô 	�
‰
�1‹€AÜ�;‰;”r—v‘v˜a“y !Ô$¬B¯F©F°1°a±4¬LÄÇÁÀqÈ!ÁtÄØàr   c                 óL  — t        | «      }|€(t        j                  t        j                  |«      «      }|dk(  r.t        j                  |t        j                  | «      z  |z  «      }|dk(  r¶t        j                  | «      t        j                  | «      z
  }t        j                  ||z  «      }t        j                  | «      \  }}t        j                  |«      }d}|d   }	|||d   <   t        d|«      D ](  }
||
   |	|z   k  r	||||
   <   Œ||
   }	|dz  }||||
   <   Œ* 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
    --------
    ÚefÚewr	   r   )Úlenr   ÚfloorÚsqrtÚceilr   Úrankdatar   ÚminÚfastsortÚzerosÚrange)r    ÚmethodÚnbinsÚnobsÚdiscreteÚwidthÚsvecÚivecÚbinnumÚbaseÚis              r   Ú
discretizer8   [   s  € ô ˆq‹6€DØ€}Ü—‘œŸ™ ›Ó'ˆØ�‚~Ü—7‘7˜5¤5§>¡>°!Ó#4Ñ4°TÑ9Ó:ˆØ�‚~Ü—‘�q“	œBŸF™F 1›IÑ%ˆÜ—‘˜˜u™Ó%ˆÜ—^‘^ AÓ&‰
ˆˆdÜ—8‘8˜D“>ˆØˆØ�A‰wˆØ"ˆ��a‘ÑÜ�q˜“ò 	+ˆAØ�A‰w˜ ™Ò%Ø$*�˜˜a™Ò!à˜A‘w�Ø˜!‘�Ø$*�˜˜a™Ò!ð	+ð €Or   c                 óX   — t        j                  |«      t        j                  | «      z  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   Úbs     r   Úlogbasechanger;   ƒ   s   € ô �6‰6�!‹9”R—V‘V˜A“YÑÐr   c                 ó<   — t        t        j                  d«      | z  S )z$
    Converts from nats to bits
    é   ©r;   r   Úer   s    r   Ú
natstobitsr@   �   s   € ô œŸ™˜qÓ! AÑ%Ð%r   c                 ó<   — t        dt        j                  «      | z  S )z$
    Converts from bits to nats
    r=   r>   r   s    r   Ú
bitstonatsrB   –   s   € ô ˜œBŸD™DÓ! AÑ%Ð%r   r=   c                 óL  — t        j                  | «      } t        j                  | dk  «      rt        j                  | dk\  «      st        d«      ‚t        j                  t        j
                  | t        j                  | «      z  «      «       }|dk7  rt        d|«      |z  S |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=   )r   r   r   Ú
ValueErrorr   Ú
nan_to_numÚlog2r;   )ÚpxÚlogbaseÚentropys      r   ÚshannonentropyrK   ž   s~   € ô2 
�‰�B‹€BÜ�6‰6�"˜‘'Œ?¤"§&¡&¨¨q©¤/ÜÐAÓBÐBÜ�v‰v”b—m‘m B¤r§w¡w¨r£{¡NÓ3Ó4Ð4€GØ�!‚|Ü˜Q˜wÓ'¨'Ñ1Ð1àˆr   c                 ó  — t        j                  | «      } t        j                  | dk  «      rt        j                  | dk\  «      st        d«      ‚|dk7  r#t	        d|«       t        j
                  | «      z  S t        j
                  | «       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   rD   r=   )r   r   r   rE   r;   rG   )rH   rI   s     r   ÚshannoninforM   Á   sn   € ô 
�‰�B‹€BÜ�6‰6�"˜‘'Œ?¤"§&¡&¨¨q©¤/ÜÐAÓBÐBØ�!‚|Ü˜q Ó)Ð)¬B¯G©G°B«KÑ7Ð7ä—‘˜“ˆ}Ðr   c           	      óR  — t        | «      rt        |«      st        d«      ‚|�t        |«      st        d«      ‚|€t        j                  || «      }t        j                  |t        j
                  t        j                  ||z  «      «      z  «      }|dk(  r|S t        d|«      |z  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 distributionú&pxpy is not a proper joint distribtionr=   )r!   rE   r   Úouterr   rF   rG   r;   )rH   ÚpyÚpxpyrI   Úcondents        r   ÚcondentropyrU   ×   s“   € ô( ˜Ô¤M°"Ô$5ÜÐLÓMÐMØÐ¤¨dÔ 3ÜÐAÓBÐBØ€|Ü�x‰x˜˜2‹ˆÜ�f‰f�TœBŸM™M¬"¯'©'°"°T±'Ó*:Ó;Ñ;Ó<€GØ�!‚|Øˆä˜Q Ó(¨7Ñ2Ð2r   c                 óÞ   — t        | «      rt        |«      st        d«      ‚|�t        |«      st        d«      ‚|€t        j                  || «      }t	        | |¬«      t        | |||¬«      z
  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)
    rO   rP   ©rI   )r!   rE   r   rQ   rK   rU   ©rH   rR   rS   rI   s       r   Ú
mutualinforY   ÷   sp   € ô* ˜Ô¤M°"Ô$5ÜÐLÓMÐMØÐ¤¨dÔ 3ÜÐAÓBÐBØ€|Ü�x‰x˜˜2‹ˆÜ˜" gÔ.´¸RÀÀ4Øô2ñ ð r   c                 óÞ   — t        | «      rt        |«      st        d«      ‚|�t        |«      st        d«      ‚|€t        j                  || «      }t	        | |||¬«      t        ||¬«      z  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)
    rO   rP   rW   )r!   rE   r   rQ   rY   rK   rX   s       r   Úcorrentr[     sp   € ô< ˜Ô¤M°"Ô$5ÜÐLÓMÐMØÐ¤¨dÔ 3ÜÐAÓBÐBØ€|Ü�x‰x˜˜2‹ˆä�b˜˜D¨Ô1´.ÀØô3ñ ð r   c                 óâ   — t        | «      rt        |«      st        d«      ‚|�t        |«      st        d«      ‚|€t        j                  || «      }t	        | |||¬«      t	        || ||¬«      z   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)
    rO   rP   rW   )r!   rE   r   rQ   rT   rX   s       r   Úcoventr]   =  st   € ô> ˜Ô¤M°"Ô$5ÜÐLÓMÐMØÐ¤¨dÔ 3ÜÐAÓBÐBØ€|Ü�x‰x˜˜2‹ˆô �B˜˜D¨'Ô2Ü�b˜"˜d¨GÔ4ñ5ð 6r   r	   c                 óÞ  — t        | «      st        d«      ‚t        |«      }|dk(  r!t        | «      }|dk7  rt	        d|«      |z  S |S dt        |«      j                  «       v s|t        j                  k(  r)t        j                  t        j                  | «      «       S | |z  } t        j                  | j                  «       «      }|dk(  rdd|z
  z  |z  S dd|z
  z  t	        d|«      z  |z  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=   Úinf)r!   rE   ÚfloatrK   r;   ÚstrÚlowerr   r_   r   r   r   )rH   ÚalpharI   ÚmeasureÚgenents        r   Úrenyientropyrf   k  sá   € ô: ˜ÔÜÐFÓGÐGÜ�%‹L€EØ�‚zÜ Ó#ˆØ�aŠ<Ü   GÓ,¨vÑ5Ð5ØˆØ	”#�e“*×"Ñ"Ó$Ñ	$¨´·±ªÜ—‘”r—v‘v˜b“zÓ"Ð"Ð"ð 
ˆU‰€BÜ�V‰V�B—F‘F“HÓ€FØ�!‚|Ø�!�E‘'‰{˜VÑ#Ð#à�!�E‘'‰{œ]¨1¨gÓ6Ñ6¸Ñ?Ð?r   c                  ó   — y)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.
    N© )rH   rR   rS   rc   rI   rd   s         r   Úgencrossentropyri   ž  s   � r   Ú__main__zQFrom Golan (2008) "Information and Entropy Econometrics -- A Review and Synthesisz	Table 3.1)çš™™™™™É?rk   rk   rk   rk   )çÏ÷Sã¥›Ô?g;ßO�—n²?g'1¬Zà?g²�ï§ÆK·?gü©ñÒMbp?)gñhãˆµøä>g-Cëâ6?gü©ñÒMbP?g{®Gáz„?gš™™™™™¹?g333333Ã?rk   g      Ð?g333333Ó?gffffffÖ?gš™™™™™Ù?gÍÌÌÌÌÌÜ?ç      à?éo   ÚInformationÚProbabilityi¡† ÚEntropyée   )r   r   çUUUUUUÕ?)çÇqÇq¼?rt   rt   )gÇqÇq¬?rt   çUUUUUUÅ?z	Table 3.3zdiscretize functions)2g3333335@g     @F@g      ?@g     €3@gÍÌÌÌÌLD@gš™™™™YC@g333333&@gš™™™™™/@gfffffæ?@gÍÌÌÌÌÌ9@g3333334@gffffff,@g      8@g      5@gš™™™™™&@g      2@çÍÌÌÌÌL0@g3333336@g333333@gÍÌÌÌÌÌ;@rv   gÍÌÌÌÌŒA@çÍÌÌÌÌÌ-@gš™™™™1@g333333<@gffffff0@g     €0@g      G@g      #@gÍÌÌÌÌÌ2@gÍÌÌÌÌ@@gš™™™™:@gš™™™™0@g333333@gffffff5@g      4@gÍÌÌÌÌL=@rw   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 = z0.4gz >= [H(X) - 1]/log(K) = é   z>Consider now, table 3.5, where there is additional informationz.The conditional probabilities of P(X|Y=y) are )ç        ry   g      ð?)rs   rs   rs   )ru   rs   rm   z2The probability of error given this information iszPe = [H(X|Y) -1]/log(K) = %0.4gz+such that more information lowers the error)gV-²á?g“V-Ò?gw¾Ÿ/ÝÄ?)gÃõ(\�ÂÝ?g+‡ÙÎ÷Ó?g%�•C‹Ì?)gáz®GáÚ?rl   gP�—nƒÐ?)N)r#   N)r=   )Nr=   )r	   r=   ÚR)r	   r=   ÚT)=Ú__doc__Ústatsmodels.compat.pythonr   r   Úscipyr   Únumpyr   Ú
matplotlibr   ÚpltÚscipy.specialr   r   r!   r8   r;   r@   rB   rK   rM   rU   rY   r[   r]   rf   ri   Ú__name__Úprintr    ÚYr7   ÚpÚsubplotÚylabelÚxlabelÚlinspaceÚxÚplotÚarrayÚwr   rH   rR   ÚH_XÚH_YÚH_XYÚ	H_XgivenYÚ	H_YgivenXr?   rJ   ÚD_YXÚD_XYÚI_XYÚdiscXÚpeÚH_perG   Úw2ÚmeanÚmarkovchainrh   r   r   ú<module>r�      sA  ðñ
÷D 1Ý Û Ý $Ý 3ó!òHó#òPò&ò&ó óFó,3ó@ó<&óP(6ó\.@ófð, ˆzÓÙ	ð ô á	ˆ+Ôò 	€AÚ"€Aàò ˆÙ‰k˜!‹nÕðàò ˆÙ‰k˜!‹nÕðá	‰.˜Ó
ÔÙ	‰.˜Ó
Ôâ;€Aà€C‡K�K�ÔØ€C‡J�Jˆ}ÔØ€C‡J�Jˆ}ÔØˆ�‰�A�a˜Ó€AØ€C‡H�HˆQ‘˜A“Ôð €C‡K�K�ÔØ€C‡J�JˆyÔØ€C‡J�Jˆ}ÔØˆ�‰�A�a˜Ó€AØ€C‡H�HˆQ‘�^¡T¨!¨A¨a©C£[Ó1Ô2ð
 	ˆ�‰’*Ò-Ò.?Ð@ÓA€Aà	
�‰ˆq‹€BØ	
�‰ˆq‹€BÙ
˜Ó
€CÙ
˜Ó
€CÙ˜!Ó€DÙ˜B˜r !Ó$€IÙ˜B˜r !Ó$€Iá˜˜2Ÿ4™4Ó   §¡¨r°2Ó!6Ñ6€DÙ˜˜2Ÿ4™4Ó   §¡¨r°2Ó!6Ñ6€DÙ�b˜˜AÓ€DÙ	ˆ+ÔÙ	ˆ#ˆc�4˜ I¨t°T¸4Ô@á	Ð
 Ô!Ø€b‡h�hò :ó ;€Añ �q‹M€Eñ 
Ù	Ð
<Ô=Ù	Ð
3Ô4Ù	Ð
.Ô/Ù	Ð
#Ô$Ù	Ð
(Ô)Ù	ˆ+˜Ñ
ÔÙ	Ð
KÔLØ	
ˆR�‰U‰€BÙ	Ð
=ÀÑ
BÔCÙ˜2˜a ™d˜)Ó$€DÙ	Ð
! DÑ
(Ô)Ù	Ð
9Ø�"�W�R—W‘W˜Q“Z‘-Ñ Ð+ñ,ô -á	Ð
*Ô+Ù	ˆE�"�T�Ð2°C¸!±G¸W¸R¿W¹WÀQ»ZÑ3GÈÐ2MÐ
NÔOÙ	Ð
JÔKÙ	Ð
:Ô;Ø	ˆ�‰’:Ò.Ò/?Ð@Ó	A€BÙ	ˆ"„Iá	Ð
>Ô?Ù	Ð
+°°·±¸¹>È"ÈQÉ%Ó;PÑQ_Ð`bÐcdÑ`eÓQfÐ8gÓ0hÐijÑ0jÐlsÐln×lsÑlsÐtuÓlvÑ/vÑ
wÔxÙ	Ð
7Ô8ð �"—(‘(Ò,Ò-=Ò>NÐOÓP�Kði r   