
    g`                       d Z ddlZddlZddlZddlZddlmZmZ ddlm	Z	m
Z
 ddlmZ ddlmZ  ed      Z G d d	e	      Z G d
 de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d d e      Z G d! d"e      Z G d# d$e      Z G d% d&e      Zd' Z d( Z! G d) d*e
      Z" G d+ d,e#e      Z$ G d- d.e$      Z% G d/ d0e$      Z& ejN                  d1d2      Z(d3 Z)d4 Z* G d5 d6      Z+ G d7 d8e+      Z,d9 Z-d: Z.d; Z/dDd=Z0d> Z1e2d?k(  r e0d<d@        e0dAdB        e1        g dCZ3y)Ea  
Classes for representing and processing probabilistic information.

The ``FreqDist`` class is used to encode "frequency distributions",
which count the number of times that each outcome of an experiment
occurs.

The ``ProbDistI`` class defines a standard interface for "probability
distributions", which encode the probability of each outcome for an
experiment.  There are two types of probability distribution:

  - "derived probability distributions" are created from frequency
    distributions.  They attempt to model the probability distribution
    that generated the frequency distribution.
  - "analytic probability distributions" are created directly from
    parameters (such as variance).

The ``ConditionalFreqDist`` class and ``ConditionalProbDistI`` interface
are used to encode conditional distributions.  Conditional probability
distributions can be derived or analytic; but currently the only
implementation of the ``ConditionalProbDistI`` interface is
``ConditionalProbDist``, a derived distribution.

    N)ABCMetaabstractmethod)Counterdefaultdict)reduce)raise_unorderable_typesz-1e300c                        e Zd ZdZd"dZd Z fdZ fdZ fdZ fdZ	d Z
d	 Zd"d
Zd"dZd Zd Zd ZddddddZd Zd Z fdZ fdZ fdZ fdZd Zd Zd Zd Zd Zd#dZd$dZd  Zd! Z  xZ!S )%FreqDista  
    A frequency distribution for the outcomes of an experiment.  A
    frequency distribution records the number of times each outcome of
    an experiment has occurred.  For example, a frequency distribution
    could be used to record the frequency of each word type in a
    document.  Formally, a frequency distribution can be defined as a
    function mapping from each sample to the number of times that
    sample occurred as an outcome.

    Frequency distributions are generally constructed by running a
    number of experiments, and incrementing the count for a sample
    every time it is an outcome of an experiment.  For example, the
    following code will produce a frequency distribution that encodes
    how often each word occurs in a text:

        >>> from nltk.tokenize import word_tokenize
        >>> from nltk.probability import FreqDist
        >>> sent = 'This is an example sentence'
        >>> fdist = FreqDist()
        >>> for word in word_tokenize(sent):
        ...    fdist[word.lower()] += 1

    An equivalent way to do this is with the initializer:

        >>> fdist = FreqDist(word.lower() for word in word_tokenize(sent))

    c                 >    t        j                  | |       d| _        y)ab  
        Construct a new frequency distribution.  If ``samples`` is
        given, then the frequency distribution will be initialized
        with the count of each object in ``samples``; otherwise, it
        will be initialized to be empty.

        In particular, ``FreqDist()`` returns an empty frequency
        distribution; and ``FreqDist(samples)`` first creates an empty
        frequency distribution, and then calls ``update`` with the
        list ``samples``.

        :param samples: The samples to initialize the frequency
            distribution with.
        :type samples: Sequence
        N)r   __init___Nselfsampless     E/var/www/openai/venv/lib/python3.12/site-packages/nltk/probability.pyr   zFreqDist.__init__V   s      	w'     c                 n    | j                   t        | j                               | _         | j                   S )z
        Return the total number of sample outcomes that have been
        recorded by this FreqDist.  For the number of unique
        sample values (or bins) with counts greater than zero, use
        ``FreqDist.B()``.

        :rtype: int
        )r   sumvaluesr   s    r   Nz
FreqDist.Nk   s(     77?$++-(DGwwr   c                 4    d| _         t        | 	  ||       y)zO
        Override ``Counter.__setitem__()`` to invalidate the cached N
        N)r   super__setitem__r   keyval	__class__s      r   r   zFreqDist.__setitem__y   s     C%r   c                 2    d| _         t        | 	  |       y)zO
        Override ``Counter.__delitem__()`` to invalidate the cached N
        N)r   r   __delitem__)r   r   r   s     r   r    zFreqDist.__delitem__   s     C r   c                 2    d| _         t        |   |i | y)zJ
        Override ``Counter.update()`` to invalidate the cached N
        N)r   r   update)r   argskwargsr   s      r   r"   zFreqDist.update   s     ''r   c                 4    d| _         t        | 	  ||       y)zN
        Override ``Counter.setdefault()`` to invalidate the cached N
        N)r   r   
setdefaultr   s      r   r&   zFreqDist.setdefault   s     3$r   c                     t        |       S )a  
        Return the total number of sample values (or "bins") that
        have counts greater than zero.  For the total
        number of sample outcomes recorded, use ``FreqDist.N()``.
        (FreqDist.B() is the same as len(FreqDist).)

        :rtype: int
        lenr   s    r   Bz
FreqDist.B   s     4yr   c                 >    | D cg c]  }| |   dk(  s| c}S c c}w )ze
        Return a list of all samples that occur once (hapax legomena)

        :rtype: list
            )r   items     r   hapaxeszFreqDist.hapaxes   s&     "&9dq999s   c                 *    | j                  |      |   S N)r_Nr)r   rbinss      r   NrzFreqDist.Nr   s    yyq!!r   c                     t        t              }| j                         D ]  }||xx   dz  cc<    ||| j                         z
  nd|d<   |S )a  
        Return the dictionary mapping r to Nr, the number of samples with frequency r, where Nr > 0.

        :type bins: int
        :param bins: The number of possible sample outcomes.  ``bins``
            is used to calculate Nr(0).  In particular, Nr(0) is
            ``bins-self.B()``.  If ``bins`` is not specified, it
            defaults to ``self.B()`` (so Nr(0) will be 0).
        :rtype: int
        r,   r   )r   intr   r*   )r   r4   _r_Nrcounts       r   r2   zFreqDist.r_Nr   sM     C [[]E%LAL # '+&64$&&(?Aar   c              #   6   K   d}|D ]  }|| |   z  }|  yw)a0  
        Return the cumulative frequencies of the specified samples.
        If no samples are specified, all counts are returned, starting
        with the largest.

        :param samples: the samples whose frequencies should be returned.
        :type samples: any
        :rtype: list(float)
                Nr-   )r   r   cfsamples       r   _cumulative_frequenciesz FreqDist._cumulative_frequencies   s*      F$v,BH s   c                 >    | j                         }|dk(  ry| |   |z  S )a0  
        Return the frequency of a given sample.  The frequency of a
        sample is defined as the count of that sample divided by the
        total number of sample outcomes that have been recorded by
        this FreqDist.  The count of a sample is defined as the
        number of times that sample outcome was recorded by this
        FreqDist.  Frequencies are always real numbers in the range
        [0, 1].

        :param sample: the sample whose frequency
               should be returned.
        :type sample: any
        :rtype: float
        r   r   )r   r=   ns      r   freqzFreqDist.freq   s(     FFH6F|ar   c                 b    t        |       dk(  rt        d      | j                  d      d   d   S )a  
        Return the sample with the greatest number of outcomes in this
        frequency distribution.  If two or more samples have the same
        number of outcomes, return one of them; which sample is
        returned is undefined.  If no outcomes have occurred in this
        frequency distribution, return None.

        :return: The sample with the maximum number of outcomes in this
                frequency distribution.
        :rtype: any or None
        r   z?A FreqDist must have at least one sample before max is defined.r,   )r)   
ValueErrormost_commonr   s    r   maxzFreqDist.max   s<     t9>Q  "1%a((r    F)title
cumulativepercentsshowc                Z   	 ddl m} t	        |      dk(  rt	        |       g} | j
                  | D 	
cg c]  \  }	}
|		 }}	}
|rt        | j                  |            }d}n|D cg c]  }| |   	 }}d}|r)|D cg c]  }|| j                         z  dz   }}|dz  }n|dz  }|j                         }|j                  d	d
       d|vrd|d<   |r|j                  |        |j                  |fi | |j                  t        t	        |                   |j                  |D cg c]  }t!        |       c}d       |j#                  d       |j%                  |       |r|j'                          |S # t        $ r}t        d      |d}~ww xY wc c}
}	w c c}w c c}w c c}w )a  
        Plot samples from the frequency distribution
        displaying the most frequent sample first.  If an integer
        parameter is supplied, stop after this many samples have been
        plotted.  For a cumulative plot, specify cumulative=True. Additional
        ``**kwargs`` are passed to matplotlib's plot function.
        (Requires Matplotlib to be installed.)

        :param title: The title for the graph.
        :type title: str
        :param cumulative: Whether the plot is cumulative. (default = False)
        :type cumulative: bool
        :param percents: Whether the plot uses percents instead of counts. (default = False)
        :type percents: bool
        :param show: Whether to show the plot, or only return the ax.
        :type show: bool
        r   NQThe plot function requires matplotlib to be installed.See https://matplotlib.org/Cumulative rG   d   PercentsCountsTsilvercolor	linewidth   Z   rotationSamples)matplotlib.pyplotpyplotImportErrorrD   r)   rE   listr>   r   gcagrid	set_titleplot
set_xticksrangeset_xticklabelsstr
set_xlabel
set_ylabelrK   )r   rH   rI   rJ   rK   r#   r$   plter.   _r   freqsylabelr=   faxss                     r   rb   zFreqDist.plot   s   (	+ t9>I;D'7t'7'7'>?'>GD!4'>?55g>?E"F078fT&\E8F167AQ\C'E7j FhFWWY
H%f$"#F;LL  
eCL)*
G4GqCFG4rB
i 
fHHJ	Q  	. 	 @ 9 8 5s.   E; F&F<F#*F(;	FFFc           
      \   t        |      dk(  rt        |       g}t        |d | j                  | D cg c]  \  }}|	 c}}      }t        |dd      }|rt        | j	                  |            }n|D cg c]  }| |   	 }}t        d |D              }	t        |	t        d |D                    }	t        t        |            D ]  }
t        d|	||
   fz  d	        t                t        t        |            D ]  }
t        d
|	||
   fz  d	        t                yc c}}w c c}w )a  
        Tabulate the given samples from the frequency distribution (cumulative),
        displaying the most frequent sample first.  If an integer
        parameter is supplied, stop after this many samples have been
        plotted.

        :param samples: The samples to plot (default is all samples)
        :type samples: list
        :param cumulative: A flag to specify whether the freqs are cumulative (default = False)
        :type title: bool
        r   r   rI   Fc              3   4   K   | ]  }t        |         y wr1   r(   .0rp   s     r   	<genexpr>z$FreqDist.tabulate.<locals>.<genexpr>P  s     1AC1#Ks   c              3   8   K   | ]  }t        d |z          ywz%dNr(   rt   rn   s     r   ru   z$FreqDist.tabulate.<locals>.<genexpr>Q  s     <es4!8}e   %*s end%*dN)r)   
_get_kwargrE   r^   r>   rF   rd   print)r   r#   r$   r.   rk   r   rI   rl   r=   widthis              r   tabulatezFreqDist.tabulate7  s"    t9>I;DI4DD4D4Dd4KL4Kq4KL
  e<
55g>?E078fT&\E8 111E3<e<<=s7|$A%5'!*--37 %s7|$A%5%(++5 %%  M 9s   D#6D)c                 $    | j                  |       S )zY
        Create a copy of this frequency distribution.

        :rtype: FreqDist
        r   r   s    r   copyzFreqDist.copyZ  s     ~~d##r   c                 @    | j                  t        | 	  |            S )z
        Add counts from two counters.

        >>> FreqDist('abbb') + FreqDist('bcc')
        FreqDist({'b': 4, 'c': 2, 'a': 1})

        )r   r   __add__r   otherr   s     r   r   zFreqDist.__add__d       ~~egoe455r   c                 @    | j                  t        | 	  |            S )z
        Subtract count, but keep only results with positive counts.

        >>> FreqDist('abbbc') - FreqDist('bccd')
        FreqDist({'b': 2, 'a': 1})

        )r   r   __sub__r   s     r   r   zFreqDist.__sub__n  r   r   c                 @    | j                  t        | 	  |            S )z
        Union is the maximum of value in either of the input counters.

        >>> FreqDist('abbb') | FreqDist('bcc')
        FreqDist({'b': 3, 'c': 2, 'a': 1})

        )r   r   __or__r   s     r   r   zFreqDist.__or__x  s     ~~egnU344r   c                 @    | j                  t        | 	  |            S )z
        Intersection is the minimum of corresponding counts.

        >>> FreqDist('abbb') & FreqDist('bcc')
        FreqDist({'b': 1})

        )r   r   __and__r   s     r   r   zFreqDist.__and__  r   r   c                      t        t              st        d        t               j	                        xr t         fd D              S )a8  
        Returns True if this frequency distribution is a subset of the other
        and for no key the value exceeds the value of the same key from
        the other frequency distribution.

        The <= operator forms partial order and satisfying the axioms
        reflexivity, antisymmetry and transitivity.

        >>> FreqDist('a') <= FreqDist('a')
        True
        >>> a = FreqDist('abc')
        >>> b = FreqDist('aabc')
        >>> (a <= b, b <= a)
        (True, False)
        >>> FreqDist('a') <= FreqDist('abcd')
        True
        >>> FreqDist('abc') <= FreqDist('xyz')
        False
        >>> FreqDist('xyz') <= FreqDist('abc')
        False
        >>> c = FreqDist('a')
        >>> d = FreqDist('aa')
        >>> e = FreqDist('aaa')
        >>> c <= d and d <= e and c <= e
        True
        <=c              3   4   K   | ]  }|   |   k    y wr1   r-   rt   r   r   r   s     r   ru   z"FreqDist.__le__.<locals>.<genexpr>  s"      1
/3DIs#t   )
isinstancer
   r   setissubsetallr   r   s   ``r   __le__zFreqDist.__le__  sK    6 %*#D$64y!!%( 
S 1
/31
 .
 	
r   c                      t        t              st        d        t               j	                        xr t         fdD              S )N>=c              3   4   K   | ]  }|   |   k\    y wr1   r-   r   s     r   ru   z"FreqDist.__ge__.<locals>.<genexpr>  s"      3
/4DIs#ur   )r   r
   r   r   
issupersetr   r   s   ``r   __ge__zFreqDist.__ge__  sI    %*#D$64y##E* 
s 3
/43
 0
 	
r   c                     | |k  xr | |k(   S r1   r-   r   s     r   <lambda>zFreqDist.<lambda>      !Dtu}3D!Dr   c                     | |k\  xr | |k(   S r1   r-   r   s     r   r   zFreqDist.<lambda>  r   r   c                 "    | j                         S )Z
        Return a string representation of this FreqDist.

        :rtype: string
        )pformatr   s    r   __repr__zFreqDist.__repr__  s     ||~r   c                 >    t        | j                  |      |       y)z
        Print a string representation of this FreqDist to 'stream'

        :param maxlen: The maximum number of items to print
        :type maxlen: int
        :param stream: The stream to print to. stdout by default
        )maxlen)fileN)r   r   )r   r   streams      r   pprintzFreqDist.pprint  s     	dll&l)7r   c                     | j                  |      D cg c]  } dj                  |  }}t        |       |kD  r|j                  d       dj                  dj	                  |            S c c}w )z
        Return a string representation of this FreqDist.

        :param maxlen: The maximum number of items to display
        :type maxlen: int
        :rtype: string
        z
{!r}: {!r}z...zFreqDist({{{0}}})z, )rE   formatr)   appendjoin)r   r   r.   itemss       r   r   zFreqDist.pformat  sk     9=8H8H8PQ8P$$$d+8PQt9vLL"))$))E*:;; Rs   A+c                 >    dt        |       | j                         fz  S )r   z*<FreqDist with %d samples and %d outcomes>)r)   r   r   s    r   __str__zFreqDist.__str__  s     <s4y$&&(>SSSr   c              #   b   K   | j                  | j                               D ]	  \  }}|  yw)zh
        Return an iterator which yields tokens ordered by frequency.

        :rtype: iterator
        N)rE   r*   )r   tokenrk   s      r   __iter__zFreqDist.__iter__  s,      ((2HE1K 3s   -/r1   )
   N)r   )"__name__
__module____qualname____doc__r   r   r   r    r"   r&   r*   r/   r5   r2   r>   rB   rF   rb   r   r   r   r   r   r   r   r   __lt____gt__r   r   r   r   r   __classcell__r   s   @r   r
   r
   9   s    8*&!(%	:"*" ()& %%e>@!F$6656
B
 EFDF8<Tr   r
   c                   h    e Zd ZdZdZ	 ed        Zed        Zd Zed        Z	ed        Z
d Zd	 Zy
)	ProbDistIa  
    A probability distribution for the outcomes of an experiment.  A
    probability distribution specifies how likely it is that an
    experiment will have any given outcome.  For example, a
    probability distribution could be used to predict the probability
    that a token in a document will have a given type.  Formally, a
    probability distribution can be defined as a function mapping from
    samples to nonnegative real numbers, such that the sum of every
    number in the function's range is 1.0.  A ``ProbDist`` is often
    used to model the probability distribution of the experiment used
    to generate a frequency distribution.
    Tc                      y)zN
        Classes inheriting from ProbDistI should implement __init__.
        Nr-   r   s    r   r   zProbDistI.__init__      r   c                      y)a  
        Return the probability for a given sample.  Probabilities
        are always real numbers in the range [0, 1].

        :param sample: The sample whose probability
               should be returned.
        :type sample: any
        :rtype: float
        Nr-   r   r=   s     r   probzProbDistI.prob  r   r   c                 f    | j                  |      }|dk7  rt        j                  |d      S t        S )z
        Return the base 2 logarithm of the probability for a given sample.

        :param sample: The sample whose probability
               should be returned.
        :type sample: any
        :rtype: float
        r   rV   )r   mathlog_NINF)r   r=   ps      r   logprobzProbDistI.logprob  s-     IIf!"atxx1~2U2r   c                      y)z
        Return the sample with the greatest probability.  If two or
        more samples have the same probability, return one of them;
        which sample is returned is undefined.

        :rtype: any
        Nr-   r   s    r   rF   zProbDistI.max  r   r   c                      y)z
        Return a list of all samples that have nonzero probabilities.
        Use ``prob`` to find the probability of each sample.

        :rtype: list
        Nr-   r   s    r   r   zProbDistI.samples(  r   r   c                      y)zi
        Return the ratio by which counts are discounted on average: c*/c

        :rtype: float
        r;   r-   r   s    r   discountzProbDistI.discount2  s     r   c                 N   t        j                          }|}| j                         D ]  }|| j                  |      z  }|dk  s|c S  |dk  rS | j                  rt	        j
                  d| d||z
  d       t        j                  t        | j                                     S )z
        Return a randomly selected sample from this probability distribution.
        The probability of returning each sample ``samp`` is equal to
        ``self.prob(samp)``.
        r   g-C6?zProbability distribution z	 sums to z.; generate() is returning an arbitrary sample.)randomr   r   
SUM_TO_ONEwarningswarnchoicer^   )r   r   p_initr=   s       r   generatezProbDistI.generate<  s     MMOllnF6""AAv %
 v:M??MM8<fqjJ }}T$,,.122r   N)r   r   r   r   r   r   r   r   r   rF   r   r   r   r-   r   r   r   r     sr     J/  
 	 	3    3r   r   )	metaclassc                   .    e Zd ZdZd Zd Zd Zd Zd Zy)UniformProbDistz
    A probability distribution that assigns equal probability to each
    sample in a given set; and a zero probability to all other
    samples.
    c                     t        |      dk(  rt        d      t        |      | _        dt        | j                        z  | _        t        | j                        | _        y)a4  
        Construct a new uniform probability distribution, that assigns
        equal probability to each sample in ``samples``.

        :param samples: The samples that should be given uniform
            probability.
        :type samples: list
        :raise ValueError: If ``samples`` is empty.
        r   zAA Uniform probability distribution must have at least one sample.      ?N)r)   rD   r   
_sampleset_probr^   _samplesr   s     r   r   zUniformProbDist.__init__[  sR     w<1X  g,3t//
T__-r   c                 :    || j                   v r| j                  S dS Nr   )r   r   r   s     r   r   zUniformProbDist.probm  s    #t6tzz=A=r   c                      | j                   d   S r   r   r   s    r   rF   zUniformProbDist.maxp  s    }}Qr   c                     | j                   S r1   r   r   s    r   r   zUniformProbDist.sampless      }}r   c                 2    dt        | j                        z  S )Nz!<UniformProbDist with %d samples>)r)   r   r   s    r   r   zUniformProbDist.__repr__v  s    2S5IIIr   N)	r   r   r   r   r   r   rF   r   r   r-   r   r   r   r   T  s!    .$> Jr   r   c                   >    e Zd ZdZd Zed        Zd Zd Zd Z	d Z
y)	RandomProbDistz
    Generates a random probability distribution whereby each sample
    will be between 0 and 1 with equal probability (uniform random distribution.
    Also called a continuous uniform distribution).
    c                     t        |      dk(  rt        d      | j                  |      | _        t	        | j                  j                               | _        y )Nr   z9A probability distribution must have at least one sample.)r)   rD   unirand_probsr^   keysr   r   s     r   r   zRandomProbDist.__init__  sI    w<1P  ll7+T[[--/0r   c                 d   t        |      }t        t        |            D cg c]  }t        j                          }}t	        |      }t        |      D ]  \  }}||z  ||<    t	        |      }|dk7  r|dxx   |dz
  z  cc<   t        |      D ci c]  \  }}|||    c}}S c c}w c c}}w )a  
        The key function that creates a randomized initial distribution
        that still sums to 1. Set as a dictionary of prob values so that
        it can still be passed to MutableProbDist and called with identical
        syntax to UniformProbDist
        r,   )r   rd   r)   r   r   	enumerate)clsr   r   randrowtotalxrp   s          r   r   zRandomProbDist.unirand  s     g,,1#g,,?@,?q6==?,?@Gg&DAqUGAJ ' GA: BK519$K*3G*<=*<$!Q71:*<== A >s   B'B,c                     t        | d      s2t        d | j                  j                         D              d   | _        | j                  S )N_maxc              3   *   K   | ]  \  }}||f  y wr1   r-   rt   vr   s      r   ru   z%RandomProbDist.max.<locals>.<genexpr>  s     E1Dv1QF1D   r,   )hasattrrF   r   r   r   r   s    r   rF   zRandomProbDist.max  s:    tV$E1B1B1DEEaHDIyyr   c                 :    | j                   j                  |d      S r   )r   getr   s     r   r   zRandomProbDist.prob  s    {{vq))r   c                     | j                   S r1   r   r   s    r   r   zRandomProbDist.samples  r   r   c                 2    dt        | j                        z  S )Nz'<RandomUniformProbDist with %d samples>)r)   r   r   s    r   r   zRandomProbDist.__repr__  s    83t{{;KKKr   N)r   r   r   r   r   classmethodr   rF   r   r   r   r-   r   r   r   r   z  s5    1 > >*
*Lr   r   c                   6    e Zd ZdZd	dZd Zd Zd Zd Zd Z	y)
DictionaryProbDistz
    A probability distribution whose probabilities are directly
    specified by a given dictionary.  The given dictionary maps
    samples to probabilities.
    Nc                    ||j                         ni | _        || _        |rOt        |      dk(  rt	        d      |rt        t        | j                  j                                     }|t        k  r9t        j                  dt        |      z  d      }|D ]  }|| j                  |<    y| j                  j                         D ]  \  }}| j                  |xx   |z  cc<    yt        | j                  j                               }|dk(  r%dt        |      z  }|D ]  }|| j                  |<    yd|z  }| j                  j                         D ]  \  }}| j                  |xx   |z  cc<    yy)a  
        Construct a new probability distribution from the given
        dictionary, which maps values to probabilities (or to log
        probabilities, if ``log`` is true).  If ``normalize`` is
        true, then the probability values are scaled by a constant
        factor such that they sum to 1.

        If called without arguments, the resulting probability
        distribution assigns zero probability to all values.
        Nr   zOA DictionaryProbDist must have at least one sample before it can be normalized.r   rV   )r   
_prob_dict_logr)   rD   sum_logsr^   r   r   r   r   r   r   )	r   	prob_dictr   	normalize	value_sumlogpr   r   norm_factors	            r   r   zDictionaryProbDist.__init__  sS    /8.C)..*	 9~" 5  $T$//*@*@*B%CD	%88C#i.$8!<D&-1* ' !% 5 5 71*i7* !8   6 6 89	>c)n,A&-.* ' #&	/K $ 5 5 71*k9* !8/ r   c                     | j                   r"|| j                  v rd| j                  |   z  S dS | j                  j                  |d      S )NrV   r   )r  r  r   r   s     r   r   zDictionaryProbDist.prob  sE    995;t5N101UTUU??&&vq11r   c                     | j                   r | j                  j                  |t              S || j                  vrt        S | j                  |   dk(  rt        S t	        j
                  | j                  |   d      S )Nr   rV   )r  r  r   r   r   r   r   s     r   r   zDictionaryProbDist.logprob  sa    99??&&vu55T__,(A-xx 7;;r   c                     t        | d      s2t        d | j                  j                         D              d   | _        | j                  S )Nr   c              3   *   K   | ]  \  }}||f  y wr1   r-   r   s      r   ru   z)DictionaryProbDist.max.<locals>.<genexpr>  s     I1Hv1QF1Hr   r,   )r   rF   r  r   r   r   s    r   rF   zDictionaryProbDist.max  s:    tV$I1F1F1HII!LDIyyr   c                 6    | j                   j                         S r1   )r  r   r   s    r   r   zDictionaryProbDist.samples  s    ##%%r   c                 2    dt        | j                        z  S )Nz<ProbDist with %d samples>)r)   r  r   s    r   r   zDictionaryProbDist.__repr__  s    +c$//.BBBr   )NFF)
r   r   r   r   r   r   r   rF   r   r   r-   r   r   r  r    s'    (:T2	<
&Cr   r  c                   6    e Zd ZdZd	dZd Zd Zd Zd Zd Z	y)
MLEProbDista%  
    The maximum likelihood estimate for the probability distribution
    of the experiment used to generate a frequency distribution.  The
    "maximum likelihood estimate" approximates the probability of
    each sample as the frequency of that sample in the frequency
    distribution.
    Nc                     || _         y)a)  
        Use the maximum likelihood estimate to create a probability
        distribution for the experiment used to generate ``freqdist``.

        :type freqdist: FreqDist
        :param freqdist: The frequency distribution that the
            probability estimates should be based on.
        N	_freqdistr   freqdistr4   s      r   r   zMLEProbDist.__init__  s     "r   c                     | j                   S z
        Return the frequency distribution that this probability
        distribution is based on.

        :rtype: FreqDist
        r  r   s    r   r  zMLEProbDist.freqdist       ~~r   c                 8    | j                   j                  |      S r1   )r  rB   r   s     r   r   zMLEProbDist.prob  s    ~~""6**r   c                 6    | j                   j                         S r1   r  rF   r   s    r   rF   zMLEProbDist.max      ~~!!##r   c                 6    | j                   j                         S r1   r  r   r   s    r   r   zMLEProbDist.samples      ~~""$$r   c                 <    d| j                   j                         z  S )\
        :rtype: str
        :return: A string representation of this ``ProbDist``.
        z!<MLEProbDist based on %d samples>r  r   r   s    r   r   zMLEProbDist.__repr__"  s    
 3T^^5E5E5GGGr   r1   )
r   r   r   r   r   r  r   rF   r   r   r-   r   r   r  r    s&    	"+$%Hr   r  c                   @    e Zd ZdZdZddZd Zd Zd Zd Z	d	 Z
d
 Zy)LidstoneProbDista8  
    The Lidstone estimate for the probability distribution of the
    experiment used to generate a frequency distribution.  The
    "Lidstone estimate" is parameterized by a real number *gamma*,
    which typically ranges from 0 to 1.  The Lidstone estimate
    approximates the probability of a sample with count *c* from an
    experiment with *N* outcomes and *B* bins as
    ``c+gamma)/(N+B*gamma)``.  This is equivalent to adding
    *gamma* to the count for each bin, and taking the maximum
    likelihood estimate of the resulting frequency distribution.
    FNc                 F   |dk(  s|=|j                         dk(  r*| j                  j                  dd }t        d|z  dz         |W||j	                         k  rD| j                  j                  dd }t        d|z  d|z  z   dz   d	|j	                         z  z         || _        t        |      | _        | j
                  j                         | _        ||j	                         }|| _	        | j                  ||z  z   | _
        | j                  d
k(  rd| _        d| _
        yy)a  
        Use the Lidstone estimate to create a probability distribution
        for the experiment used to generate ``freqdist``.

        :type freqdist: FreqDist
        :param freqdist: The frequency distribution that the
            probability estimates should be based on.
        :type gamma: float
        :param gamma: A real number used to parameterize the
            estimate.  The Lidstone estimate is equivalent to adding
            *gamma* to the count for each bin, and taking the
            maximum likelihood estimate of the resulting frequency
            distribution.
        :type bins: int
        :param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            ``bins`` is not specified, it defaults to ``freqdist.B()``.
        r   NizA %s probability distribution zmust have at least one bin.z)
The number of bins in a %s distribution z&(%d) must be greater than or equal to
z(the number of bins in the FreqDist used zto create it (%d).r;   r,   )r   r   r   rD   r*   r  float_gammar   _bins_divisor)r   r  gammar4   names        r   r   zLidstoneProbDist.__init__9  s,   * AI4<HJJLA,=>>**3B/D047:WW  4(**,#6>>**3B/D<tC;dBC<= '56  "El..""$<::<D
$,.==C DKDM	  r   c                     | j                   S r  r  r   s    r   r  zLidstoneProbDist.freqdistk  r  r   c                 X    | j                   |   }|| j                  z   | j                  z  S r1   )r  r+  r-  r   r=   cs      r   r   zLidstoneProbDist.probt  s'    NN6"DKK4==00r   c                 6    | j                   j                         S r1   r  r   s    r   rF   zLidstoneProbDist.maxx  s     ~~!!##r   c                 6    | j                   j                         S r1   r"  r   s    r   r   zLidstoneProbDist.samples~  r#  r   c                 X    | j                   | j                  z  }|| j                  |z   z  S r1   )r+  r,  r   )r   gbs     r   r   zLidstoneProbDist.discount  s'    [[4::%TWWr\""r   c                 <    d| j                   j                         z  S )[
        Return a string representation of this ``ProbDist``.

        :rtype: str
        z&<LidstoneProbDist based on %d samples>r&  r   s    r   r   zLidstoneProbDist.__repr__  s     8$..:J:J:LLLr   r1   )r   r   r   r   r   r   r  r   rF   r   r   r   r-   r   r   r(  r(  *  s3    
 J0d1$%#Mr   r(  c                       e Zd ZdZddZd Zy)LaplaceProbDista  
    The Laplace estimate for the probability distribution of the
    experiment used to generate a frequency distribution.  The
    "Laplace estimate" approximates the probability of a sample with
    count *c* from an experiment with *N* outcomes and *B* bins as
    *(c+1)/(N+B)*.  This is equivalent to adding one to the count for
    each bin, and taking the maximum likelihood estimate of the
    resulting frequency distribution.
    Nc                 4    t         j                  | |d|       y)a  
        Use the Laplace estimate to create a probability distribution
        for the experiment used to generate ``freqdist``.

        :type freqdist: FreqDist
        :param freqdist: The frequency distribution that the
            probability estimates should be based on.
        :type bins: int
        :param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            ``bins`` is not specified, it defaults to ``freqdist.B()``.
        r,   Nr(  r   r  s      r   r   zLaplaceProbDist.__init__  s     	!!$!T:r   c                 <    d| j                   j                         z  S )r%  z%<LaplaceProbDist based on %d samples>r&  r   s    r   r   zLaplaceProbDist.__repr__  s    
 79I9I9KKKr   r1   r   r   r   r   r   r   r-   r   r   r;  r;    s    ;"Lr   r;  c                       e Zd ZdZddZd Zy)ELEProbDista  
    The expected likelihood estimate for the probability distribution
    of the experiment used to generate a frequency distribution.  The
    "expected likelihood estimate" approximates the probability of a
    sample with count *c* from an experiment with *N* outcomes and
    *B* bins as *(c+0.5)/(N+B/2)*.  This is equivalent to adding 0.5
    to the count for each bin, and taking the maximum likelihood
    estimate of the resulting frequency distribution.
    Nc                 4    t         j                  | |d|       y)a  
        Use the expected likelihood estimate to create a probability
        distribution for the experiment used to generate ``freqdist``.

        :type freqdist: FreqDist
        :param freqdist: The frequency distribution that the
            probability estimates should be based on.
        :type bins: int
        :param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            ``bins`` is not specified, it defaults to ``freqdist.B()``.
              ?Nr=  r  s      r   r   zELEProbDist.__init__  s     	!!$#t<r   c                 <    d| j                   j                         z  S )r9  z!<ELEProbDist based on %d samples>r&  r   s    r   r   zELEProbDist.__repr__  s     3T^^5E5E5GGGr   r1   r?  r-   r   r   rA  rA    s    ="Hr   rA  c                   R    e Zd ZdZdZddZd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd Zy)HeldoutProbDistag  
    The heldout estimate for the probability distribution of the
    experiment used to generate two frequency distributions.  These
    two frequency distributions are called the "heldout frequency
    distribution" and the "base frequency distribution."  The
    "heldout estimate" uses uses the "heldout frequency
    distribution" to predict the probability of each sample, given its
    frequency in the "base frequency distribution".

    In particular, the heldout estimate approximates the probability
    for a sample that occurs *r* times in the base distribution as
    the average frequency in the heldout distribution of all samples
    that occur *r* times in the base distribution.

    This average frequency is *Tr[r]/(Nr[r].N)*, where:

    - *Tr[r]* is the total count in the heldout distribution for
      all samples that occur *r* times in the base distribution.
    - *Nr[r]* is the number of samples that occur *r* times in
      the base distribution.
    - *N* is the number of outcomes recorded by the heldout
      frequency distribution.

    In order to increase the efficiency of the ``prob`` member
    function, *Tr[r]/(Nr[r].N)* is precomputed for each value of *r*
    when the ``HeldoutProbDist`` is created.

    :type _estimate: list(float)
    :ivar _estimate: A list mapping from *r*, the number of
        times that a sample occurs in the base distribution, to the
        probability estimate for that sample.  ``_estimate[r]`` is
        calculated by finding the average frequency in the heldout
        distribution of all samples that occur *r* times in the base
        distribution.  In particular, ``_estimate[r]`` =
        *Tr[r]/(Nr[r].N)*.
    :type _max_r: int
    :ivar _max_r: The maximum number of times that any sample occurs
        in the base distribution.  ``_max_r`` is used to decide how
        large ``_estimate`` must be.
    FNc                 <   || _         || _        ||j                            | _        | j	                         }|j                  |      }t        | j                  dz         D cg c]  }||   	 }}|j                         }| j                  |||      | _	        yc c}w )a  
        Use the heldout estimate to create a probability distribution
        for the experiment used to generate ``base_fdist`` and
        ``heldout_fdist``.

        :type base_fdist: FreqDist
        :param base_fdist: The base frequency distribution.
        :type heldout_fdist: FreqDist
        :param heldout_fdist: The heldout frequency distribution.
        :type bins: int
        :param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            ``bins`` is not specified, it defaults to ``freqdist.B()``.
        r,   N)
_base_fdist_heldout_fdistrF   _max_r_calculate_Trr2   rd   r   _calculate_estimate	_estimate)	r   
base_fdistheldout_fdistr4   Trr2   r3   r5   r   s	            r   r   zHeldoutProbDist.__init__  s    $ &+ !!12 !t$$T[[1_565!d1g56OO 11"b!< 7s   "Bc                     dg| j                   dz   z  }| j                  D ]+  }| j                  |   }||xx   | j                  |   z  cc<   - |S )z
        Return the list *Tr*, where *Tr[r]* is the total count in
        ``heldout_fdist`` for all samples that occur *r*
        times in ``base_fdist``.

        :rtype: list(float)
        r;   r,   )rJ  rI  rH  )r   rP  r=   r3   s       r   rK  zHeldoutProbDist._calculate_Tr%  sX     UdkkAo&))F  (AqET((00E * 	r   c                     g }t        | j                  dz         D ]9  }||   dk(  r|j                  d       |j                  ||   ||   |z  z         ; |S )a~  
        Return the list *estimate*, where *estimate[r]* is the probability
        estimate for any sample that occurs *r* times in the base frequency
        distribution.  In particular, *estimate[r]* is *Tr[r]/(N[r].N)*.
        In the special case that *N[r]=0*, *estimate[r]* will never be used;
        so we define *estimate[r]=None* for those cases.

        :rtype: list(float)
        :type Tr: list(float)
        :param Tr: the list *Tr*, where *Tr[r]* is the total count in
            the heldout distribution for all samples that occur *r*
            times in base distribution.
        :type Nr: list(float)
        :param Nr: The list *Nr*, where *Nr[r]* is the number of
            samples that occur *r* times in the base distribution.
        :type N: int
        :param N: The total number of outcomes recorded by the heldout
            frequency distribution.
        r,   r   N)rd   rJ  r   )r   rP  r5   r   estimater3   s         r   rL  z#HeldoutProbDist._calculate_estimate3  s[    ( t{{Q'A!uz%1A 34	 (
 r   c                     | j                   S )z
        Return the base frequency distribution that this probability
        distribution is based on.

        :rtype: FreqDist
        )rH  r   s    r   rN  zHeldoutProbDist.base_fdistO  s     r   c                     | j                   S )z
        Return the heldout frequency distribution that this
        probability distribution is based on.

        :rtype: FreqDist
        )rI  r   s    r   rO  zHeldoutProbDist.heldout_fdistX  s     """r   c                 6    | j                   j                         S r1   )rH  r   r   s    r   r   zHeldoutProbDist.samplesa  s    $$&&r   c                 >    | j                   |   }| j                  |   S r1   )rH  rM  )r   r=   r3   s      r   r   zHeldoutProbDist.probd  s!    V$~~a  r   c                 6    | j                   j                         S r1   )rH  rF   r   s    r   rF   zHeldoutProbDist.maxi  s     ##%%r   c                     t               r1   NotImplementedErrorr   s    r   r   zHeldoutProbDist.discounto      !##r   c                 t    d}|| j                   j                         | j                  j                         fz  S )r%  z6<HeldoutProbDist: %d base samples; %d heldout samples>)rH  r   rI  )r   rp   s     r   r   zHeldoutProbDist.__repr__r  s8    
 ED$$&&($*=*=*?*?*ABBBr   r1   )r   r   r   r   r   r   rK  rL  rN  rO  r   r   rF   r   r   r-   r   r   rF  rF    sC    'R J =D8 #'!
&$Cr   rF  c                   8    e Zd ZdZdZd Zd Zd Zd Zd Z	d Z
y	)
CrossValidationProbDistaA  
    The cross-validation estimate for the probability distribution of
    the experiment used to generate a set of frequency distribution.
    The "cross-validation estimate" for the probability of a sample
    is found by averaging the held-out estimates for the sample in
    each pair of frequency distributions.
    Fc                     || _         g | _        |D ]6  }|D ]/  }||ust        |||      }| j                  j                  |       1 8 y)a  
        Use the cross-validation estimate to create a probability
        distribution for the experiment used to generate
        ``freqdists``.

        :type freqdists: list(FreqDist)
        :param freqdists: A list of the frequency distributions
            generated by the experiment.
        :type bins: int
        :param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            ``bins`` is not specified, it defaults to ``freqdist.B()``.
        N)
_freqdists_heldout_probdistsrF  r   )r   	freqdistsr4   fdist1fdist2probdists         r   r   z CrossValidationProbDist.__init__  sS      $ #%F#'.vvtDH++228< $  r   c                     | j                   S )z
        Return the list of frequency distributions that this ``ProbDist`` is based on.

        :rtype: list(FreqDist)
        )ra  r   s    r   rc  z!CrossValidationProbDist.freqdists  s     r   c                 N    t        t        d | j                  D        g             S )Nc              3   2   K   | ]  }t        |        y wr1   )r^   )rt   fds     r   ru   z2CrossValidationProbDist.samples.<locals>.<genexpr>  s     ;?RR?s   )r   r   ra  r   s    r   r   zCrossValidationProbDist.samples  s    3;4??;R@AAr   c                     d}| j                   D ]  }||j                  |      z  } |t        | j                         z  S )Nr;   )rb  r   r)   )r   r=   r   heldout_probdists       r   r   zCrossValidationProbDist.prob  sF      $ 7 7$))&11D !8c$11222r   c                     t               r1   rZ  r   s    r   r   z CrossValidationProbDist.discount  r\  r   c                 2    dt        | j                        z  S )r9  z!<CrossValidationProbDist: %d-way>)r)   ra  r   s    r   r   z CrossValidationProbDist.__repr__  s     3S5IIIr   N)r   r   r   r   r   r   rc  r   r   r   r   r-   r   r   r_  r_  {  s.     J=6B3$Jr   r_  c                   <    e Zd ZdZd
dZd Zd Zd Zd Zd Z	d	 Z
y)WittenBellProbDista  
    The Witten-Bell estimate of a probability distribution. This distribution
    allocates uniform probability mass to as yet unseen events by using the
    number of events that have only been seen once. The probability mass
    reserved for unseen events is equal to *T / (N + T)*
    where *T* is the number of observed event types and *N* is the total
    number of observed events. This equates to the maximum likelihood estimate
    of a new type event occurring. The remaining probability mass is discounted
    such that all probability estimates sum to one, yielding:

        - *p = T / Z (N + T)*, if count = 0
        - *p = c / (N + T)*, otherwise
    Nc                    |+||j                         k\  sJ d|j                         z         ||j                         }|| _        | j                  j                         | _        || j                  j                         z
  | _        | j                  j	                         | _        | j
                  dk(  rd| j                  z  | _        y| j                  | j                  | j
                  | j                  z   z  z  | _        y)a)  
        Creates a distribution of Witten-Bell probability estimates.  This
        distribution allocates uniform probability mass to as yet unseen
        events by using the number of events that have only been seen once. The
        probability mass reserved for unseen events is equal to *T / (N + T)*
        where *T* is the number of observed event types and *N* is the total
        number of observed events. This equates to the maximum likelihood
        estimate of a new type event occurring. The remaining probability mass
        is discounted such that all probability estimates sum to one,
        yielding:

            - *p = T / Z (N + T)*, if count = 0
            - *p = c / (N + T)*, otherwise

        The parameters *T* and *N* are taken from the ``freqdist`` parameter
        (the ``B()`` and ``N()`` values). The normalizing factor *Z* is
        calculated using these values along with the ``bins`` parameter.

        :param freqdist: The frequency counts upon which to base the
            estimation.
        :type freqdist: FreqDist
        :param bins: The number of possible event types. This must be at least
            as large as the number of bins in the ``freqdist``. If None, then
            it's assumed to be equal to that of the ``freqdist``
        :type bins: int
        Nz4bins parameter must not be less than %d=freqdist.B()r   r   )r*   r  _T_Zr   r   _P0r  s      r   r   zWittenBellProbDist.__init__  s    6 |txzz|3 	
BXZZ\Q	
3 <::<D!..""$))++..""$77a<TWW}DHww$''TWWtww->"?@DHr   c                 z    | j                   |   }|dk7  r|| j                  | j                  z   z  S | j                  S r   )r  r   rr  rt  r2  s      r   r   zWittenBellProbDist.prob  s7    NN6"*+q&qDGGdgg%&>dhh>r   c                 6    | j                   j                         S r1   r  r   s    r   rF   zWittenBellProbDist.max   r   r   c                 6    | j                   j                         S r1   r"  r   s    r   r   zWittenBellProbDist.samples  r#  r   c                     | j                   S r1   r  r   s    r   r  zWittenBellProbDist.freqdist      ~~r   c                     t               r1   rZ  r   s    r   r   zWittenBellProbDist.discount	  r\  r   c                 <    d| j                   j                         z  S )r9  z(<WittenBellProbDist based on %d samples>r&  r   s    r   r   zWittenBellProbDist.__repr__  s     :DNN<L<L<NNNr   r1   )r   r   r   r   r   r   rF   r   r  r   r   r-   r   r   rp  rp    s-    )AV?
$%$Or   rp  c                   v    e Zd ZdZdZddZd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zy)SimpleGoodTuringProbDista=  
    SimpleGoodTuring ProbDist approximates from frequency to frequency of
    frequency into a linear line under log space by linear regression.
    Details of Simple Good-Turing algorithm can be found in:

    - Good Turing smoothing without tears" (Gale & Sampson 1995),
      Journal of Quantitative Linguistics, vol. 2 pp. 217-237.
    - "Speech and Language Processing (Jurafsky & Martin),
      2nd Edition, Chapter 4.5 p103 (log(Nc) =  a + b*log(c))
    - https://www.grsampson.net/RGoodTur.html

    Given a set of pair (xi, yi),  where the xi denotes the frequency and
    yi denotes the frequency of frequency, we want to minimize their
    square variation. E(x) and E(y) represent the mean of xi and yi.

    - slope: b = sigma ((xi-E(x)(yi-E(y))) / sigma ((xi-E(x))(xi-E(x)))
    - intercept: a = E(y) - b.E(x)
    FNc                 <   |.||j                         kD  sJ d|j                         dz   z         ||j                         dz   }|| _        || _        | j                         \  }}| j	                  ||       | j                  ||       | j                  ||       y)ap  
        :param freqdist: The frequency counts upon which to base the
            estimation.
        :type freqdist: FreqDist
        :param bins: The number of possible event types. This must be
            larger than the number of bins in the ``freqdist``. If None,
            then it's assumed to be equal to ``freqdist``.B() + 1
        :type bins: int
        Nz6bins parameter must not be less than %d=freqdist.B()+1r,   )r*   r  r,  r8   find_best_fit_switch_renormalize)r   r  r4   r3   nrs        r   r   z!SimpleGoodTuringProbDist.__init__f  s     LD8::</	YCxzz|VWGWX	Y/<::<!#D!


21b!Q!R r   c                 @    | j                   j                         }|d= |S r   )r  r2   )r   r2   s     r   _r_Nr_non_zeroz'SimpleGoodTuringProbDist._r_Nr_non_zero|  s     ~~""$Gr   c                 l    | j                         }|sg g fS t        t        |j                                S )zW
        Split the frequency distribution in two list (r, Nr), where Nr(r) > 0
        )r  zipsortedr   )r   nonzeros     r   r8   zSimpleGoodTuringProbDist._r_Nr  s4     %%'r6MF7==?+,,r   c                    |r|syg }t        t        |            D ]T  }|dkD  r||dz
     nd}|t        |      dz
  k(  rd||   z  |z
  n||dz      }d||   z  ||z
  z  }|j                  |       V |D cg c]  }t        j                  |       }}|D cg c]  }t        j                  |       }	}dx}
}t        |      t        |      z  }t        |	      t        |	      z  }t        ||	      D ]  \  }}|
||z
  ||z
  z  z  }
|||z
  dz  z  }  |dk7  r|
|z  nd| _        | j                  dk\  rt        j                  d       || j                  |z  z
  | _
        yc c}w c c}w )	z
        Use simple linear regression to tune parameters self._slope and
        self._intercept in the log-log space based on count and Nr(count)
        (Work in log space to avoid floating point underflow.)
        Nr   r,   rV   g       @r;   r   zSimpleGoodTuring did not find a proper best fit line for smoothing probabilities of occurrences. The probability estimates are likely to be unreliable.)rd   r)   r   r   r   r   r  _sloper   r   
_intercept)r   r3   r  zrjr   kzr_log_rlog_zrxy_covx_varx_meany_meanr   ys                   r   r  z&SimpleGoodTuringProbDist.find_best_fit  sz    s1vAE!a%qA !SVaZAaD1Qq1uXA1+Q'CIIcN	  '((a!a(')*r!$((1+r*Uc%j(Vs6{*v&DAqq6za&j11Fa&jQ&&E ' ).
fun;;"MM !4;;#77# )*s   7E#E(c           
         t        |      D ]  \  }}t        |      |dz   k(  s||dz      |dz   k7  r	|| _         y| j                  }|dz    ||dz         z   ||      z  }|dz   ||dz      z  ||   z  }t	        j
                  | j                  |||   ||dz                  }t        ||z
        d|z  k  s|| _         y y)zl
        Calculate the r frontier where we must switch from Nr to Sr
        when estimating E[Nr].
        r,   g\(\?N)r   r)   
_switch_at
smoothedNrr   sqrt	_varianceabs)	r   r3   r  r   r_Srsmooth_r_starunsmooth_r_starstds	            r   r  z SimpleGoodTuringProbDist._switch  s    
 q\EAr1vQ!AE(b1f"4"$B!Vr"q&z1BrF:M!AvAE2RU:O))DNN2r!ubQi@AC?]23tczA"$ "r   c                 x    t        |      }t        |      }t        |      }|dz   dz  ||dz  z  z  d||z  z   z  S )Nr   rV   )r*  )r   r3   r  nr_1s       r   r  z"SimpleGoodTuringProbDist._variance  sE    !H2YT{CA~A.#r	/BBr   c                     d}t        ||      D ]  \  }}||| j                  |      z  z  } |rd| j                  d      z
  |z  | _        yy)ay  
        It is necessary to renormalize all the probability estimates to
        ensure a proper probability distribution results. This can be done
        by keeping the estimate of the probability mass for unseen items as
        N(1)/N and renormalizing all the estimates for previously seen items
        (as Gale and Sampson (1995) propose). (See M&S P.213, 1999)
        r;   r,   r   N)r  _prob_measure	_renormal)r   r3   r  prob_covr  nr_s         r   r  z%SimpleGoodTuringProbDist._renormalize  s[     1bzGBd00444H "$"4"4Q"778CDN r   c                     t        j                  | j                  | j                  t        j                  |      z  z         S )z
        Return the number of samples with count r.

        :param r: The amount of frequency.
        :type r: int
        :rtype: float
        )r   expr  r  r   )r   r3   s     r   r  z#SimpleGoodTuringProbDist.smoothedNr  s-     xx$++*CCDDr   c                    | j                   |   }| j                  |      }|dk(  rW| j                  | j                   j                         k(  rd}|S || j                  | j                   j                         z
  z  }|S || j                  z  }|S )z
        Return the sample's probability.

        :param sample: sample of the event
        :type sample: str
        :rtype: float
        r   r;   )r  r  r,  r*   r  )r   r=   r9   r   s       r   r   zSimpleGoodTuringProbDist.prob  s     v&u%A:zzT^^--//
  dnn&6&6&889  DNN"Ar   c                 $   |dk(  r| j                   j                         dk(  ry|dk(  rS| j                   j                         dk7  r6| j                   j                  d      | j                   j                         z  S | j                  |kD  r:| j                   j                  |dz         }| j                   j                  |      }n%| j	                  |dz         }| j	                  |      }|dz   |z  |z  }|| j                   j                         z  S )Nr   r   r,   )r  r   r5   r  r  )r   r9   Er_1Err_stars        r   r  z&SimpleGoodTuringProbDist._prob_measure  s    A:$..**,1aZDNN,,.!3>>$$Q'$..*:*:*<<<??U">>$$UQY/D""5)B??519-D'B!)t#b(((***r   c                     d}t        dt        | j                              D ]3  }|| j                  |   | j                  |      z  | j                  z  z  }5 t        d|       y )Nr;   r   zProbability Sum:)rd   r)   _Nrr  r  r   )r   prob_sumr   s      r   checkzSimpleGoodTuringProbDist.check  sV    q#dhh-(Ad&8&8&;;dnnLLH ) (+r   c                 Z    | j                  d      | j                  j                         z  S )z
        This function returns the total mass of probability transfers from the
        seen samples to the unseen samples.
        r,   )r  r  r   r   s    r   r   z!SimpleGoodTuringProbDist.discount  s%    
 q!DNN$4$4$666r   c                 6    | j                   j                         S r1   r  r   s    r   rF   zSimpleGoodTuringProbDist.max  r   r   c                 6    | j                   j                         S r1   r"  r   s    r   r   z SimpleGoodTuringProbDist.samples   r#  r   c                     | j                   S r1   r  r   s    r   r  z!SimpleGoodTuringProbDist.freqdist#  ry  r   c                 <    d| j                   j                         z  S )r9  z.<SimpleGoodTuringProbDist based on %d samples>r&  r   s    r   r   z!SimpleGoodTuringProbDist.__repr__&  s     @$..BRBRBTTTr   r1   )r   r   r   r   r   r   r  r8   r  r  r  r  r  r   r  r  r   rF   r   r  r   r-   r   r   r}  r}  P  sc    & J!,
-'8R(CDE &+ ,7$%Ur   r}  c                   8    e Zd ZdZd	dZd Zd Zd Zd Zd	dZ	y)
MutableProbDistz
    An mutable probdist where the probabilities may be easily modified. This
    simply copies an existing probdist, storing the probability values in a
    mutable dictionary and providing an update method.
    c                    || _         t        t        |            D ci c]  }||   |
 c}| _        t	        j                  ddg      t        |      z  | _        t        t        |            D ]G  }|r"|j                  ||         | j
                  |<   '|j                  ||         | j
                  |<   I || _        yc c}w )a  
        Creates the mutable probdist based on the given prob_dist and using
        the list of samples given. These values are stored as log
        probabilities if the store_logs flag is set.

        :param prob_dist: the distribution from which to garner the
            probabilities
        :type prob_dist: ProbDist
        :param samples: the complete set of samples
        :type samples: sequence of any
        :param store_logs: whether to store the probabilities as logarithms
        :type store_logs: bool
        dr;   N)	r   rd   r)   _sample_dictarray_datar   r   _logs)r   	prob_distr   
store_logsr   s        r   r   zMutableProbDist.__init__6  s      49#g,4GH4GqWQZ]4GH[[se,s7|;
s7|$A ) 1 1'!* =

1 )wqz :

1	 %
  
 Is   Cc                 \    t        d | j                  j                         D              d   S )Nc              3   *   K   | ]  \  }}||f  y wr1   r-   r   s      r   ru   z&MutableProbDist.max.<locals>.<genexpr>P  s     B(Afq!Aq6(Ar   r,   )rF   r  r   r   s    r   rF   zMutableProbDist.maxN  s'    B(9(9(?(?(ABB1EEr   c                     | j                   S r1   r   r   s    r   r   zMutableProbDist.samplesR  s    }}r   c                     | j                   j                  |      }|y| j                  rd| j                  |   z  S | j                  |   S )Nr;   rV   )r  r   r  r  r   r=   r   s      r   r   zMutableProbDist.probV  sF    !!&)9'+zzqTZZ]#Dtzz!}Dr   c                     | j                   j                  |      }|t        d      S | j                  r| j                  |   S t        j                  | j                  |   d      S )Nz-infrV   )r  r   r*  r  r  r   r   r  s      r   r   zMutableProbDist.logprob]  sS    !!&)9=  $

tzz!}JA0JJr   c                     | j                   j                  |      }|J | j                  r(|r|nt        j                  |d      | j
                  |<   y|rd|z  n|| j
                  |<   y)a<  
        Update the probability for the given sample. This may cause the object
        to stop being the valid probability distribution - the user must
        ensure that they update the sample probabilities such that all samples
        have probabilities between 0 and 1 and that all probabilities sum to
        one.

        :param sample: the sample for which to update the probability
        :type sample: any
        :param prob: the new probability
        :type prob: float
        :param log: is the probability already logged
        :type log: bool
        NrV   )r  r   r  r   r   r  )r   r=   r   r   r   s        r   r"   zMutableProbDist.updated  s\     !!&)}}::$'DTXXdA->DJJqM+.A$KDDJJqMr   N)T)
r   r   r   r   r   rF   r   r   r   r"   r-   r   r   r  r  /  s(     0FEK9r   r  c                   <    e Zd ZdZd
dZd Zd Zd Zd Zd Z	d	 Z
y)KneserNeyProbDista~  
    Kneser-Ney estimate of a probability distribution. This is a version of
    back-off that counts how likely an n-gram is provided the n-1-gram had
    been seen in training. Extends the ProbDistI interface, requires a trigram
    FreqDist instance to train on. Optionally, a different from default discount
    value can be specified. The default discount is set to 0.75.

    Nc                    |s|j                         | _        n|| _        || _        i | _        t	        t
              | _        || _        t	        t              | _	        t	        t              | _
        t	        t              | _        |D ]n  \  }}}| j                  ||fxx   ||||f   z  cc<   | j                  ||fxx   dz  cc<   | j                  |xx   dz  cc<   | j                  ||fxx   dz  cc<   p y)a  
        :param freqdist: The trigram frequency distribution upon which to base
            the estimation
        :type freqdist: FreqDist
        :param bins: Included for compatibility with nltk.tag.hmm
        :type bins: int or float
        :param discount: The discount applied when retrieving counts of
            trigrams
        :type discount: float (preferred, but can be set to int)
        r,   N)r*   r,  _D_cacher   r7   _bigrams	_trigramsr*  _wordtypes_after_trigrams_contain_wordtypes_before)r   r  r4   r   w0w1w2s          r   r   zKneserNeyProbDist.__init__  s     !DJDJ  $C(! !,E 2!,U!3!,U!3"JBBMM2r(#xR'==#!!2r(+q0+""2&!+&""B8,1,	 #r   c                 <   t        |      dk7  rt        d      t        |      }|\  }}}|| j                  v r| j                  |   S || j                  v r3| j                  |   | j                         z
  | j                  ||f   z  }n||f| j                  v rr||f| j                  v rb| j                  ||f   }| j                  ||f   }|| j                         z  | j                  ||f   z  }|| j                  |   |z
  z  }	||	z  }nd}|| j                  |<   |S )N   z$Expected an iterable with 3 members.r;   )
r)   rD   tupler  r  r   r  r  r  r  )
r   trigramr  r  r  r   aftrbfrleftover_probbetas
             r   r   zKneserNeyProbDist.prob  s7   w<1CDD.
Bdkk!;;w'' $..(w/$--/AT]]HF 
 bT]]*Bx4;Q;Q/Q,,b"X6,,b"X6 "&!74=="b;R R d44R84?@$t+ #'DKK Kr   c                     | j                   S )zq
        Return the value by which counts are discounted. By default set to 0.75.

        :rtype: float
        r  r   s    r   r   zKneserNeyProbDist.discount  s     wwr   c                     || _         y)z
        Set the value by which counts are discounted to the value of discount.

        :param discount: the new value to discount counts by
        :type discount: float (preferred, but int possible)
        :rtype: None
        Nr  )r   r   s     r   set_discountzKneserNeyProbDist.set_discount  s     r   c                 6    | j                   j                         S r1   )r  r   r   s    r   r   zKneserNeyProbDist.samples  r#  r   c                 6    | j                   j                         S r1   )r  rF   r   s    r   rF   zKneserNeyProbDist.max  r   r   c                 >    d| j                   j                          dS )zV
        Return a string representation of this ProbDist

        :rtype: str
        z<KneserNeyProbDist based on z	 trigrams)r  r   r   s    r   r   zKneserNeyProbDist.__repr__  s!     .dnn.>.>.@-AKKr   )Ng      ?)r   r   r   r   r   r   r   r  r   rF   r   r-   r   r   r  r    s-    !2F"H%$Lr   r  c                      t         t              rt        t              st        d      t         fdD              S )Nzexpected a ProbDist.c              3      K   | ];  }j                  |      t        j                  j                  |      d       z   = ywrV   N)r   r   r   )rt   rp   actual_pdist
test_pdists     r   ru   z!log_likelihood.<locals>.<genexpr>  s9      HT1!txx
(:A>>s   AA)r   r   rD   r   )r  r  s   ``r   log_likelihoodr    s<    j),J|Y4W/00 HT  r   c                 \      fd j                         D        }t        d |D               S )Nc              3   @   K   | ]  }j                  |        y wr1   )r   )rt   rp   pdists     r   ru   zentropy.<locals>.<genexpr>   s     4OqUZZ]Os   c              3   N   K   | ]  }|t        j                  |d       z    ywr  )r   r   )rt   r   s     r   ru   zentropy.<locals>.<genexpr>!  s      2EqDHHQN"Es   #%)r   r   )r  probss   ` r   entropyr    s'    4EMMO4E2E2222r   c                       e Zd ZdZddZd Zd Zd Zddddddd	d
Zd Z	d Z
d Zd Zd Zd Zd Zd Zd Zd ZeZd Zy)ConditionalFreqDista  
    A collection of frequency distributions for a single experiment
    run under different conditions.  Conditional frequency
    distributions are used to record the number of times each sample
    occurred, given the condition under which the experiment was run.
    For example, a conditional frequency distribution could be used to
    record the frequency of each word (type) in a document, given its
    length.  Formally, a conditional frequency distribution can be
    defined as a function that maps from each condition to the
    FreqDist for the experiment under that condition.

    Conditional frequency distributions are typically constructed by
    repeatedly running an experiment under a variety of conditions,
    and incrementing the sample outcome counts for the appropriate
    conditions.  For example, the following code will produce a
    conditional frequency distribution that encodes how often each
    word type occurs, given the length of that word type:

        >>> from nltk.probability import ConditionalFreqDist
        >>> from nltk.tokenize import word_tokenize
        >>> sent = "the the the dog dog some other words that we do not care about"
        >>> cfdist = ConditionalFreqDist()
        >>> for word in word_tokenize(sent):
        ...     condition = len(word)
        ...     cfdist[condition][word] += 1

    An equivalent way to do this is with the initializer:

        >>> cfdist = ConditionalFreqDist((len(word), word) for word in word_tokenize(sent))

    The frequency distribution for each condition is accessed using
    the indexing operator:

        >>> cfdist[3]
        FreqDist({'the': 3, 'dog': 2, 'not': 1})
        >>> cfdist[3].freq('the')
        0.5
        >>> cfdist[3]['dog']
        2

    When the indexing operator is used to access the frequency
    distribution for a condition that has not been accessed before,
    ``ConditionalFreqDist`` creates a new empty FreqDist for that
    condition.

    Nc                 r    t        j                  | t               |r|D ]  \  }}| |   |xx   dz  cc<    yy)aZ  
        Construct a new empty conditional frequency distribution.  In
        particular, the count for every sample, under every condition,
        is zero.

        :param cond_samples: The samples to initialize the conditional
            frequency distribution with
        :type cond_samples: Sequence of (condition, sample) tuples
        r,   N)r   r   r
   )r   cond_samplescondr=   s       r   r   zConditionalFreqDist.__init__Y  s>     	T8, ,fT
6"a'" !- r   c                 X      fd j                         D        } j                  dd d |fS )Nc              3   ,   K   | ]  }||   f  y wr1   r-   )rt   r  r   s     r   ru   z1ConditionalFreqDist.__reduce__.<locals>.<genexpr>j  s     E3D4T4:&3Ds   r-   )
conditionsr   )r   kv_pairss   ` r   
__reduce__zConditionalFreqDist.__reduce__i  s)    E4??3DED$99r   c                 4    t        | j                               S )aT  
        Return a list of the conditions that have been accessed for
        this ``ConditionalFreqDist``.  Use the indexing operator to
        access the frequency distribution for a given condition.
        Note that the frequency distributions for some conditions
        may contain zero sample outcomes.

        :rtype: list
        r^   r   r   s    r   r  zConditionalFreqDist.conditionsm  s     DIIK  r   c                 B    t        d | j                         D              S )z
        Return the total number of sample outcomes that have been
        recorded by this ``ConditionalFreqDist``.

        :rtype: int
        c              3   <   K   | ]  }|j                           y wr1   r@   )rt   fdists     r   ru   z(ConditionalFreqDist.N.<locals>.<genexpr>  s     8-5779-s   )r   r   r   s    r   r   zConditionalFreqDist.Ny  s     8$++-888r   rG   F)r   rH   rI   rJ   r  rK   c                >   	 ddl m}	 |s| j	                         }n|D cg c]	  }|| v s| }}|s%t        |D ch c]  }| |   D ]  }|  c}}      }d|vrd|d<   |	j                         }|rbg }|D ]p  }|rt        | |   j                  |            }n|D cg c]
  }| |   |    }}|r&|D cg c]  }|| |   j                         z  dz   }}|j                  |       r |rd}d}nd	}d
}|r|dz  }n|dz  }d}|D ]%  }||   |d<   |dz  } |j                  |g|i | ' |j                  |       |j                  dd       |j                  t        t!        |                   |j#                  |D cg c]  }t%        |       c}d       |r|j'                  |       |j)                  d       |j+                  |       |r|	j-                          |S # t        $ r}
t        d      |
d}
~
ww xY wc c}w c c}}w c c}w c c}w c c}w )aK  
        Plot the given samples from the conditional frequency distribution.
        For a cumulative plot, specify cumulative=True. Additional ``*args`` and
        ``**kwargs`` are passed to matplotlib's plot function.
        (Requires Matplotlib to be installed.)

        :param samples: The samples to plot
        :type samples: list
        :param title: The title for the graph
        :type title: str
        :param cumulative: Whether the plot is cumulative. (default = False)
        :type cumulative: bool
        :param percents: Whether the plot uses percents instead of counts. (default = False)
        :type percents: bool
        :param conditions: The conditions to plot (default is all)
        :type conditions: list
        :param show: Whether to show the plot, or only return the ax.
        :type show: bool
        r   NrM   rU   rV   rO   rN   zlower rightrG   zupper rightrP   rQ   labelr,   )locTrR   rS   rW   rX   rZ   )r[   r\   r]   rD   r  r  r_   r^   r>   r   r   rb   legendr`   rc   rd   r)   re   rf   ra   rg   rh   rK   )r   r   rH   rI   rJ   r  rK   r#   r$   ri   rj   r3  r   ro   rl   	conditionrB   r=   rn   rm   
legend_locr   rp   s                          r   rb   zConditionalFreqDist.plot  sA   <	+ *J%/=Z19!ZJ=EAT!WaWaEFGf$"#F;WWYE'	Y G G PQDBIJ'DOF3'DJCGH4aAY 1 1 33c94DHT" ( &*
*
*$("A",Q-wQ.t.v.  II*I%GGDG)MM%G-.81A82FU#MM)$MM&!HHJ	u  	. 	 >E K I0  9s8   G( 	HHH

H4 HH(	H1G==Hc                    t        |dd      }t        |dt        | j                                     }t        |dt        |D ch c]  }|| v s| |   D ]  }|  c}}            }t        d |D              }t	               }	|D ]]  }|r!t        | |   j                  |            |	|<   n|D 
cg c]
  }
| |   |
    c}
|	|<   t        |t        d |	|   D                    }_ t        d |D              }t        d|z  d	       |D ]  }t        d
||fz  d	        t                |D ]:  }t        d
||fz  d	       |	|   D ]  }t        d||fz  d	        t                < yc c}}w c c}
w )a~  
        Tabulate the given samples from the conditional frequency distribution.

        :param samples: The samples to plot
        :type samples: list
        :param conditions: The conditions to plot (default is all)
        :type conditions: list
        :param cumulative: A flag to specify whether the freqs are cumulative (default = False)
        :type title: bool
        rI   Fr  r   c              3   8   K   | ]  }t        d |z          yw%sNr(   rs   s     r   ru   z/ConditionalFreqDist.tabulate.<locals>.<genexpr>  s     37aCqM7ry   c              3   8   K   | ]  }t        d |z          ywrw   r(   rx   s     r   ru   z/ConditionalFreqDist.tabulate.<locals>.<genexpr>  s     "C(Q3tax=(ry   c              3   8   K   | ]  }t        d |z          ywr	  r(   )rt   r3  s     r   ru   z/ConditionalFreqDist.tabulate.<locals>.<genexpr>  s     ?JqS]Jry   r{   r|   rz   r~   N)r   r  r  rF   dictr^   r>   r   )r   r#   r$   rI   r  r3  r   r   r   rl   r=   condition_sizerp   rn   s                 r   r   zConditionalFreqDist.tabulate  sv     e<
fT__=N6OP
zHz!Q$YQ1AAzHI
 3733AQ ? ? HIa:AB'DGFO'Bas"C%("CCDE  ?J??cN",A%5!*$#. A%>1--371Xeuaj(c2 G	 # I Cs   	E*E*/E0c                     t        |t              st        S | j                         }|j	                         D ]  }||xx   ||   z  cc<    |S )z;
        Add counts from two ConditionalFreqDists.
        r   r  NotImplementedr   r  r   r   resultr  s       r   r   zConditionalFreqDist.__add__  J     %!45!!$$&D4LE$K'L 'r   c                     t        |t              st        S | j                         }|j	                         D ]  }||xx   ||   z  cc<   ||   r||=  |S )zM
        Subtract count, but keep only results with positive counts.
        r  r  s       r   r   zConditionalFreqDist.__sub__  sZ     %!45!!$$&D4LE$K'L$<4L ' r   c                     t        |t              st        S | j                         }|j	                         D ]  }||xx   ||   z  cc<    |S )zP
        Union is the maximum of value in either of the input counters.
        r  r  s       r   r   zConditionalFreqDist.__or__   r  r   c                     t        |t              st        S t               }| j                         D ]  }| |   ||   z  }|s|||<    |S )zF
        Intersection is the minimum of corresponding counts.
        )r   r  r  r  )r   r   r  r  newfreqdists        r   r   zConditionalFreqDist.__and__+  sS     %!45!!$&OO%Dt*uT{2K*t & r   c                      t        t              st        d        t         j	                               j                  j	                               xr# t         fd j	                         D              S )Nr   c              3   4   K   | ]  }|   |   k    y wr1   r-   )rt   r3  r   r   s     r   ru   z-ConditionalFreqDist.__le__.<locals>.<genexpr><  s$      K
):ADGuQx):r   )r   r  r   r   r  r   r   r   s   ``r   r   zConditionalFreqDist.__le__9  se    %!45#D$64??$%..u/?/?/AB 
s K
)-):K
 H
 	
r   c                 T    t        |t              st        d| |       | |k  xr | |k7  S )N<r   r  r   r   s     r   r   zConditionalFreqDist.__lt__@  s,    %!45#Cu5u}..r   c                 F    t        |t              st        d| |       || k  S )Nr   r  r   s     r   r   zConditionalFreqDist.__ge__E  s#    %!45#D$6}r   c                 F    t        |t              st        d| |       || k  S )N>r  r   s     r   r   zConditionalFreqDist.__gt__J  s#    %!45#Cu5t|r   c                     ddl m}  ||       S )Nr   )deepcopy)r   r"  )r   r"  s     r   r"  zConditionalFreqDist.deepcopyO  s    !~r   c                     dt        |       z  S )zf
        Return a string representation of this ``ConditionalFreqDist``.

        :rtype: str
        z(<ConditionalFreqDist with %d conditions>r(   r   s    r   r   zConditionalFreqDist.__repr__V  s     :CIEEr   r1   )r   r   r   r   r   r  r  r   rb   r   r   r   r   r   r   r   r   r   r"  r   r   r-   r   r   r  r  )  sw    -^( :
!9 Zx&T		
/



 DFr   r  c                   ,    e Zd ZdZed        Zd Zd Zy)ConditionalProbDistIao  
    A collection of probability distributions for a single experiment
    run under different conditions.  Conditional probability
    distributions are used to estimate the likelihood of each sample,
    given the condition under which the experiment was run.  For
    example, a conditional probability distribution could be used to
    estimate the probability of each word type in a document, given
    the length of the word type.  Formally, a conditional probability
    distribution can be defined as a function that maps from each
    condition to the ``ProbDist`` for the experiment under that
    condition.
    c                      y)zY
        Classes inheriting from ConditionalProbDistI should implement __init__.
        Nr-   r   s    r   r   zConditionalProbDistI.__init__m  r   r   c                 4    t        | j                               S )z
        Return a list of the conditions that are represented by
        this ``ConditionalProbDist``.  Use the indexing operator to
        access the probability distribution for a given condition.

        :rtype: list
        r  r   s    r   r  zConditionalProbDistI.conditionss  s     DIIK  r   c                 H    dt        |       j                  t        |       fz  S )zf
        Return a string representation of this ``ConditionalProbDist``.

        :rtype: str
        z<%s with %d conditions>)typer   r)   r   s    r   r   zConditionalProbDistI.__repr__}  s"     )DJ,?,?T+KKKr   N)r   r   r   r   r   r   r  r   r-   r   r   r%  r%  _  s&      
!Lr   r%  c                       e Zd ZdZd Zd Zy)ConditionalProbDista  
    A conditional probability distribution modeling the experiments
    that were used to generate a conditional frequency distribution.
    A ConditionalProbDist is constructed from a
    ``ConditionalFreqDist`` and a ``ProbDist`` factory:

    - The ``ConditionalFreqDist`` specifies the frequency
      distribution for each condition.
    - The ``ProbDist`` factory is a function that takes a
      condition's frequency distribution, and returns its
      probability distribution.  A ``ProbDist`` class's name (such as
      ``MLEProbDist`` or ``HeldoutProbDist``) can be used to specify
      that class's constructor.

    The first argument to the ``ProbDist`` factory is the frequency
    distribution that it should model; and the remaining arguments are
    specified by the ``factory_args`` parameter to the
    ``ConditionalProbDist`` constructor.  For example, the following
    code constructs a ``ConditionalProbDist``, where the probability
    distribution for each condition is an ``ELEProbDist`` with 10 bins:

        >>> from nltk.corpus import brown
        >>> from nltk.probability import ConditionalFreqDist
        >>> from nltk.probability import ConditionalProbDist, ELEProbDist
        >>> cfdist = ConditionalFreqDist(brown.tagged_words()[:5000])
        >>> cpdist = ConditionalProbDist(cfdist, ELEProbDist, 10)
        >>> cpdist['passed'].max()
        'VBD'
        >>> cpdist['passed'].prob('VBD') #doctest: +ELLIPSIS
        0.423...

    c                 `    || _         || _        || _        |D ]  } |||   g|i || |<    y)a  
        Construct a new conditional probability distribution, based on
        the given conditional frequency distribution and ``ProbDist``
        factory.

        :type cfdist: ConditionalFreqDist
        :param cfdist: The ``ConditionalFreqDist`` specifying the
            frequency distribution for each condition.
        :type probdist_factory: class or function
        :param probdist_factory: The function or class that maps
            a condition's frequency distribution to its probability
            distribution.  The function is called with the frequency
            distribution as its first argument,
            ``factory_args`` as its remaining arguments, and
            ``factory_kw_args`` as keyword arguments.
        :type factory_args: (any)
        :param factory_args: Extra arguments for ``probdist_factory``.
            These arguments are usually used to specify extra
            properties for the probability distributions of individual
            conditions, such as the number of bins they contain.
        :type factory_kw_args: (any)
        :param factory_kw_args: Extra keyword arguments for ``probdist_factory``.
        N)_probdist_factory_factory_args_factory_kw_args)r   cfdistprobdist_factoryfactory_argsfactory_kw_argsr  s         r   r   zConditionalProbDist.__init__  sL    0 "2) /I.y!$04CDO  r   c                 v     | j                   t               g| j                  i | j                  | |<   | |   S r1   )r-  r
   r.  r/  r   r   s     r   __missing__zConditionalProbDist.__missing__  sE    *D**J
++
/3/D/D
S	 Cyr   Nr   r   r   r   r   r6  r-   r   r   r+  r+    s    BBr   r+  c                       e Zd ZdZd Zd Zy)DictionaryConditionalProbDistz
    An alternative ConditionalProbDist that simply wraps a dictionary of
    ProbDists rather than creating these from FreqDists.
    c                 &    | j                  |       y)z
        :param probdist_dict: a dictionary containing the probdists indexed
            by the conditions
        :type probdist_dict: dict any -> probdist
        N)r"   )r   probdist_dicts     r   r   z&DictionaryConditionalProbDist.__init__  s     	M"r   c                 &    t               | |<   | |   S r1   )r  r5  s     r   r6  z)DictionaryConditionalProbDist.__missing__  s    &(S	Cyr   Nr7  r-   r   r   r9  r9    s    
#r   r9  gKH9rV   c                     | |t         z   k  r|S || t         z   k  r| S t        | |      }|t        j                  d| |z
  z  d||z
  z  z   d      z   S )a  
    Given two numbers ``logx`` = *log(x)* and ``logy`` = *log(y)*, return
    *log(x+y)*.  Conceptually, this is the same as returning
    ``log(2**(logx)+2**(logy))``, but the actual implementation
    avoids overflow errors that could result from direct computation.
    rV   )_ADD_LOGS_MAX_DIFFminr   r   )logxlogybases      r   add_logsrC    sb     d'''d'''tT?D$((1-dTk0BBAFFFr   c                 X    t        |       dk7  rt        t        | dd  | d         S t        S )Nr   r,   )r)   r   rC  r   )logss    r   r  r    s*    25d)q.6(DHd1g.KeKr   c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)ProbabilisticMixIna  
    A mix-in class to associate probabilities with other classes
    (trees, rules, etc.).  To use the ``ProbabilisticMixIn`` class,
    define a new class that derives from an existing class and from
    ProbabilisticMixIn.  You will need to define a new constructor for
    the new class, which explicitly calls the constructors of both its
    parent classes.  For example:

        >>> from nltk.probability import ProbabilisticMixIn
        >>> class A:
        ...     def __init__(self, x, y): self.data = (x,y)
        ...
        >>> class ProbabilisticA(A, ProbabilisticMixIn):
        ...     def __init__(self, x, y, **prob_kwarg):
        ...         A.__init__(self, x, y)
        ...         ProbabilisticMixIn.__init__(self, **prob_kwarg)

    See the documentation for the ProbabilisticMixIn
    ``constructor<__init__>`` for information about the arguments it
    expects.

    You should generally also redefine the string representation
    methods, the comparison methods, and the hashing method.
    c                     d|v r)d|v rt        d      t        j                  | |d          yd|v rt        j                  | |d          ydx| _        | _        y)a  
        Initialize this object's probability.  This initializer should
        be called by subclass constructors.  ``prob`` should generally be
        the first argument for those constructors.

        :param prob: The probability associated with the object.
        :type prob: float
        :param logprob: The log of the probability associated with
            the object.
        :type logprob: float
        r   r   z.Must specify either prob or logprob (not both)N)	TypeErrorrG  set_probset_logprob_ProbabilisticMixIn__prob_ProbabilisticMixIn__logprob)r   r$   s     r   r   zProbabilisticMixIn.__init__	  s_     VF" STT"++D&.A& **4	1BC+//DK$.r   c                      || _         d| _        y)z
        Set the probability associated with this object to ``prob``.

        :param prob: The new probability
        :type prob: float
        NrL  rM  r   r   s     r   rJ  zProbabilisticMixIn.set_prob3	  s     r   c                      || _         d| _        y)z
        Set the log probability associated with this object to
        ``logprob``.  I.e., set the probability associated with this
        object to ``2**(logprob)``.

        :param logprob: The new log probability
        :type logprob: float
        N)rM  rL  )r   r   s     r   rK  zProbabilisticMixIn.set_logprob=	  s     !r   c                 t    | j                   !| j                  yd| j                  z  | _         | j                   S )z\
        Return the probability associated with this object.

        :rtype: float
        NrV   rO  r   s    r   r   zProbabilisticMixIn.probI	  s5     ;;~~%/DK{{r   c                     | j                   2| j                  yt        j                  | j                  d      | _         | j                   S )z
        Return ``log(p)``, where ``p`` is the probability associated
        with this object.

        :rtype: float
        NrV   )rM  rL  r   r   r   s    r   r   zProbabilisticMixIn.logprobU	  s;     >>!{{"!XXdkk15DN~~r   N)	r   r   r   r   r   rJ  rK  r   r   r-   r   r   rG  rG  	  s     20,

r   rG  c                       e Zd Zd Zd Zy)ImmutableProbabilisticMixInc                 F    t        d| j                  j                  z        Nz%s is immutablerD   r   r   rP  s     r   rJ  z$ImmutableProbabilisticMixIn.set_probd	      *T^^-D-DDEEr   c                 F    t        d| j                  j                  z        rW  rX  rP  s     r   rK  z'ImmutableProbabilisticMixIn.set_logprobg	  rY  r   N)r   r   r   rJ  rK  r-   r   r   rU  rU  c	  s    FFr   rU  c                 &    || v r
| |   }| |= |S |}|S r1   r-   )r$   r   defaultargs       r   r   r   n	  s,    
f}Sk3K J Jr   c                     t               }t        |      D ]E  }t        j                  dd| z   dz        t        j                  d| dz        z   }||xx   dz  cc<   G |S )z
    Create a new frequency distribution, with random samples.  The
    samples are numbers from 1 to ``numsamples``, and are generated by
    summing two numbers, each of which has a uniform distribution.
    r,   rV   r   )r
   rd   r   randint)
numsamplesnumoutcomesr   r   r  s        r   _create_rand_fdistrb  |	  sb     JE;NN1q:~!34v~~zQ8
 
 	aA	  
 Lr   c                     t               }t        dd| z   dz  dz         D ])  }t        d| dz  dz         D ]  }|||z   xx   dz  cc<    + t        |      S )zp
    Return the true probability distribution for the experiment
    ``_create_rand_fdist(numsamples, x)``.
    r,   rV   r   )r
   rd   r  )r`  r   r   r  s       r   _create_sum_pdistrd  	  sc    
 JE1q:~!+a/0q*/A-.A!a%LAL / 1 ur      c                    t        | |      }t        | |      }t        | |      }t        |      t        |d|       t        |||       t        |||       t	        |||g|       t        |      t        |d      t        |       g}g }t        d| dz         D ]M  }|j                  t        ||j                  |      g|D cg c]  }|j                  |       c}z                O t        d| | |fz         t        dt        |      dz   z         ddt        |      dz
  z  z   d	z   }	t        |	t        d
 |dd D              z         t        dt        |      dz   z         ddt        |      dz
  z  z   dz   }	|D ]  }
t        |	|
z          t        t        |       }|dd D 
cg c]  }
t!        |
       }}
t        dt        |      dz   z         ddt        |      z  z   dz   }	t        |	t        |      z         t        dt        |      dz   z         t        d|z        dk  r*t        d|z         t        d|z         t        d|z         t                t        d       |D ]W  t#        fdt        d      D              }t        dj%                  j&                  j(                  dd d|z  dd              Y t                yc c}w c c}
w )aK  
    A demonstration of frequency distributions and probability
    distributions.  This demonstration creates three frequency
    distributions with, and uses them to sample a random process with
    ``numsamples`` samples.  Each frequency distribution is sampled
    ``numoutcomes`` times.  These three frequency distributions are
    then used to build six probability distributions.  Finally, the
    probability estimates of these distributions are compared to the
    actual probability of each sample.

    :type numsamples: int
    :param numsamples: The number of samples to use in each demo
        frequency distributions.
    :type numoutcomes: int
    :param numoutcomes: The total number of outcomes for each
        demo frequency distribution.  These outcomes are divided into
        ``numsamples`` bins.
    :rtype: None
    rC     r,   z=%d samples (1-%d); %d outcomes were sampled for each FreqDistz	=========rV   z      FreqDist z%8s z	|  Actualc              3   8   K   | ]  }t        |      d d   yw)r,   	   N)repr)rt   r  s     r   ru   zdemo.<locals>.<genexpr>	  s     F+DK!,+ry   Nr   z	---------z%3d   %8.6f z%8.6f z| %8.6fzTotal r
  F   z  fdist1: %sz  fdist2: %sz  fdist3: %szGenerating:c              3   >   K   | ]  }j                           y wr1   )r   )rt   r   r  s     r   ru   zdemo.<locals>.<genexpr>	  s     ?;a);s     z	{:>20} {}   7   )rb  r  r(  rF  r_  r}  rd  rd   r   r  rB   r   r   r)   r^   r  r   r
   r   r   r   )r`  ra  rd  re  fdist3pdistsvalsrA   r  	FORMATSTRr   zvalssumsr   s           `     r   demorv  	  s   ,  
K8F
K8F
K8F 	Fj1
3
3 8*E ( +*%	F D1j1n%E1fkk!n-F0SF5AF0SSTU & 
Gz;
/	0 
'S[1_
%&!Fc&kAo$>>LI	)eF&"+FF
FG	'S[1_
%&S[1_!==	IIi#o  dE %ab	*	CH	D*	'S[1_
%&8s6{33i?I	)eDk
!"	'S[1_
%& 4&=Bnv%&nv%&nv%&	G	-?5;??k  !9!9#2!>sPR@STU  
GE 1T" +s   =K%Kc            	      F   ddl m}  | j                  j                  d      }t	        |      }t        |      }t        dj                  ddd             d t        |j                         d	 d
      D        }|D ]%  }t        d|||   |j                  |      fz         ' y )Nr   )corpuszausten-emma.txtz{:>18} {:>8}  {:>14}word	frequencySimpleGoodTuringc              3   &   K   | ]	  \  }}|  y wr1   r-   )rt   r   values      r   ru   zgt_demo.<locals>.<genexpr>	  s      X
UXs   c                     | d   S )Nr,   r-   )r.   s    r   r   zgt_demo.<locals>.<lambda>	  s    $q'r   T)r   reversez%18s %8d  %14e)nltkrx  	gutenbergwordsr
   r}  r   r   r  r   r   )rx  
emma_wordsrj  sgtfd_keys_sortedr   s         r   gt_demor  	  s    !!''(9:J	*	B
"2
&C	
 
'
'=O
PQ$RXXZ5ISWXN #r#w!>>? r   __main__r      rm  )r  r+  r%  r_  r9  r  rA  r
   r}  rF  rU  r;  r(  r  r  r  r   rG  r   rp  rC  r  r  r  )re  i  )4r   r  r   r   r   abcr   r   collectionsr   r   	functoolsr   nltk.internalsr   r*  r   r
   r   r   r   r  r  r(  r;  rA  rF  r_  rp  r}  r  r  r  r  r  r  r%  r+  r9  r   r>  rC  r  rG  rU  r   rb  rd  rv  r  r   __all__r-   r   r   <module>r     s  2     ' ,  2hlw lhd3' d3N#Ji #JL1LY 1LhKC KC\+H) +H\aMy aMH!L& !LH"H" "HJaCi aCHCJi CJLQO QO^\Uy \U~I9i I9`oL	 oLn3sF+ sFl	$L47 $LNG. GT$8 0 TXXeQ' GL] ]@F"4 F 	K\@ zBKDMIr   