
    /h`                       S r SSKrSSKrSSKrSSKrSSKJrJr  SSKJ	r	J
r
  SSKJr  SSKJr  \" S5      r " S S	\	5      r " S
 S\S9r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S \5      r " S! S"\5      r " S# S$\5      r " S% S&\5      rS' r S( r! " S) S*\
5      r" " S+ S,\#\S9r$ " S- S.\$5      r% " S/ S0\$5      r&\RN                  " S1S25      r(S3 r)S4 r* " S5 S65      r+ " S7 S8\+5      r,S9 r-S: r.S; r/SDS= jr0S> r1\2S?:X  a  \0" S<S@5        \0" SASB5        \1" 5         / SCQr3g)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                      ^  \ rS rSrSrS$S jrS rU 4S jrU 4S jrU 4S jr	U 4S jr
S	 rS
 rS$S jrS$S jrS rS rS rSSSSS.S jrS rS rU 4S jrU 4S jrU 4S jrU 4S jrS rS rS rS rS rS%S jrS&S  jrS! r S" r!S#r"U =r#$ )'FreqDist9   a=  
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                 >    [         R                  " X5        SU l        g)a  
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     H/var/www/auris/envauris/lib/python3.13/site-packages/nltk/probability.pyr   FreqDist.__init__V   s      	'     c                 p    U R                   c  [        U R                  5       5      U l         U R                   $ )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   N
FreqDist.Nk   s(     77?$++-(DGwwr   c                 2   > SU l         [        TU ]	  X5        g)z?
Override ``Counter.__setitem__()`` to invalidate the cached N
N)r   super__setitem__r   keyval	__class__s      r   r   FreqDist.__setitem__y   s     C%r   c                 2   > SU l         [        TU ]	  U5        g)z?
Override ``Counter.__delitem__()`` to invalidate the cached N
N)r   r   __delitem__)r   r   r!   s     r   r$   FreqDist.__delitem__   s     C r   c                 4   > SU l         [        TU ]  " U0 UD6  g)z:
Override ``Counter.update()`` to invalidate the cached N
N)r   r   update)r   argskwargsr!   s      r   r'   FreqDist.update   s     ''r   c                 2   > SU l         [        TU ]	  X5        g)z>
Override ``Counter.setdefault()`` to invalidate the cached N
N)r   r   
setdefaultr   s      r   r,   FreqDist.setdefault   s     3$r   c                     [        U 5      $ )z
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   B
FreqDist.B   s     4yr   c                 F    U  Vs/ s H  oU   S:X  d  M  UPM     sn$ s  snf )zM
Return a list of all samples that occur once (hapax legomena)

:rtype: list
    )r   items     r   hapaxesFreqDist.hapaxes   s$     "&9dq999s   c                 *    U R                  U5      U   $ N)r_Nr)r   rbinss      r   NrFreqDist.Nr   s    yyq!!r   c                     [        [        5      nU R                  5        H  nX#==   S-  ss'   M     Ub  XR                  5       -
  OSUS'   U$ )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
r4   r   )r   intr   r1   )r   r=   _r_Nrcounts       r   r;   FreqDist.r_Nr   sI     C [[]ELAL # '+&64&&(?Aar   c              #   8   #    SnU H  nX U   -  nUv   M     g7f)z
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)
        Nr5   )r   r   cfsamples       r   _cumulative_frequencies FreqDist._cumulative_frequencies   s'      Fv,BH    c                 >    U R                  5       nUS:X  a  gX   U-  $ )a  
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   rH   ns      r   freqFreqDist.freq   s&     FFH6|ar   c                 d    [        U 5      S:X  a  [        S5      eU R                  S5      S   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.r4   )r0   
ValueErrormost_commonr   s    r   maxFreqDist.max   s<     t9>Q  "1%a((r    F)title
cumulativepercentsshowc                    SSK Jn  [	        U5      S:X  a  [	        U 5      /nU R
                  " U6  V	V
s/ s H  u  pU	PM	     nn	n
U(       a  [        U R                  U5      5      nSnOU Vs/ s H  oU   PM	     nnSnU(       a+  U Vs/ s H  oU R                  5       -  S-  PM     nnUS-  nOUS-  nUR                  5       nUR                  S	S
S9  SU;  a  SUS'   U(       a  UR                  U5        UR                  " U40 UD6  UR                  [        [	        U5      5      5        UR                  U Vs/ s H  n[!        U5      PM     snSS9  UR#                  S5        UR%                  U5        U(       a  UR'                  5         U$ ! [         a  n[        S5      UeSnAff = fs  sn
n	f s  snf s  snf s  snf )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 rV   d   PercentsCountsTsilvercolor	linewidth   Z   rotationSamples)matplotlib.pyplotpyplotImportErrorrR   r0   rS   listrI   r   gcagrid	set_titleplot
set_xticksrangeset_xticklabelsstr
set_xlabel
set_ylabelrZ   )r   rW   rX   rY   rZ   r(   r)   plter6   _r   freqsylabelrH   faxss                     r   rq   FreqDist.plot   s   (	+ t9>I;D'+'7'7'>?'>GD4'>?55g>?E"F078f&\E8F167A\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.   F F3.F9F>?G
F0F++F0c           
      h   [        U5      S:X  a  [        U 5      /n[        USU R                  " U6  VVs/ s H  u  p4UPM	     snn5      n[        USS5      nU(       a  [        U R	                  U5      5      nOU Vs/ s H  oU   PM	     nn[        S U 5       5      n	[        U	[        S U 5       5      5      n	[        [        U5      5       H  n
[        SXU
   4-  SS	9  M     [        5         [        [        U5      5       H  n
[        S
XU
   4-  SS	9  M     [        5         gs  snnf s  snf )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   rX   Fc              3   :   #    U  H  n[        U 5      v   M     g 7fr:   r/   .0r   s     r   	<genexpr>$FreqDist.tabulate.<locals>.<genexpr>P  s     1AC1#KKs   c              3   >   #    U  H  n[        S U-  5      v   M     g7fz%dNr/   r   r}   s     r   r   r   Q  s     <es4!8}}e   %*s end%*dN)r0   
_get_kwargrS   rm   rI   rT   rs   print)r   r(   r)   r6   rz   r   rX   r{   rH   widthis              r   tabulateFreqDist.tabulate7  s    t9>I;DID4D4Dd4KL4K4KL
  e<
55g>?E078f&\E8 111E3<e<<=s7|$A%5!*--37 %s7|$A%5(++5 %%  M 9s   D)>D/c                 $    U R                  U 5      $ )zA
Create a copy of this frequency distribution.

:rtype: FreqDist
r!   r   s    r   copyFreqDist.copyZ  s     ~~d##r   c                 @   > U R                  [        TU ]	  U5      5      $ )zk
Add counts from two counters.

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

)r!   r   __add__r   otherr!   s     r   r   FreqDist.__add__d       ~~egoe455r   c                 @   > U R                  [        TU ]	  U5      5      $ )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   FreqDist.__sub__n  r   r   c                 @   > U R                  [        TU ]	  U5      5      $ )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   FreqDist.__or__x  s     ~~egnU344r   c                 @   > U R                  [        TU ]	  U5      5      $ )zr
Intersection is the minimum of corresponding counts.

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

)r!   r   __and__r   s     r   r   FreqDist.__and__  r   r   c                    ^ ^ [        T[        5      (       d  [        ST T5        [        T 5      R	                  T5      =(       a    [        UU 4S jT  5       5      $ )a  
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   :   >#    U  H  nTU   TU   :*  v   M     g 7fr:   r5   r   r   r   r   s     r   r   "FreqDist.__le__.<locals>.<genexpr>  s!      1
/3DIs#t   )
isinstancer
   r   setissubsetallr   r   s   ``r   __le__FreqDist.__le__  sN    6 %**#D$64y!!%( 
S 1
/31
 .
 	
r   c                    ^ ^ [        T[        5      (       d  [        ST T5        [        T 5      R	                  T5      =(       a    [        UU 4S jT 5       5      $ )N>=c              3   :   >#    U  H  nTU   TU   :  v   M     g 7fr:   r5   r   s     r   r   "FreqDist.__ge__.<locals>.<genexpr>  s!      3
/4DIs#ur   )r   r
   r   r   
issupersetr   r   s   ``r   __ge__FreqDist.__ge__  sL    %**#D$64y##E* 
s 3
/43
 0
 	
r   c                 "    X:*  =(       a    X:X  + $ r:   r5   r   s     r   <lambda>FreqDist.<lambda>      !Dt3D!Dr   c                 "    X:  =(       a    X:X  + $ r:   r5   r   s     r   r   r     r   r   c                 "    U R                  5       $ )B
Return a string representation of this FreqDist.

:rtype: string
)pformatr   s    r   __repr__FreqDist.__repr__  s     ||~r   c                 2    [        U R                  US9US9  g)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   pprintFreqDist.pprint  s     	dll&l)7r   c                     U R                  U5       Vs/ s H  nSR                  " U6 PM     nn[        U 5      U:  a  UR                  S5        SR                  SR	                  U5      5      $ s  snf )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, )rS   formatr0   appendjoin)r   r   r6   itemss       r   r   FreqDist.pformat  sh     9=8H8H8PQ8P$$d+8PQt9vLL"))$))E*:;; Rs   A/c                 >    S[        U 5      U R                  5       4-  $ )r   z*<FreqDist with %d samples and %d outcomes>)r0   r   r   s    r   __str__FreqDist.__str__  s     <s4y$&&(>SSSr   c              #   d   #    U R                  U R                  5       5       H	  u  pUv   M     g7f)zP
Return an iterator which yields tokens ordered by frequency.

:rtype: iterator
N)rS   r1   )r   tokenrz   s      r   __iter__FreqDist.__iter__  s)      ((2HEK 3s   .0)r   r:   )
   N)r   )$__name__
__module____qualname____firstlineno____doc__r   r   r   r$   r'   r,   r1   r7   r>   r;   rI   rO   rT   rq   r   r   r   r   r   r   r   r   __lt____gt__r   r   r   r   r   __static_attributes____classcell__r   s   @r   r
   r
   9   s    8*&!(%	:"*" ()& %%e>@!F$6656
B
 EFDF8<T r   r
   c                   p    \ rS rSrSrSr \S 5       r\S 5       rS r	\S 5       r
\S 5       rS	 rS
 rSrg)	ProbDistIi  ac  
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                     g)z>
Classes inheriting from ProbDistI should implement __init__.
Nr5   r   s    r   r   ProbDistI.__init__      r   c                     g)z
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
Nr5   r   rH   s     r   probProbDistI.prob  r   r   c                 j    U R                  U5      nUS:w  a  [        R                  " US5      $ [        $ )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   re   )r   mathlog_NINF)r   rH   ps      r   logprobProbDistI.logprob  s-     IIf!"atxx1~2U2r   c                     g)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
Nr5   r   s    r   rT   ProbDistI.max  r   r   c                     g)z
Return a list of all samples that have nonzero probabilities.
Use ``prob`` to find the probability of each sample.

:rtype: list
Nr5   r   s    r   r   ProbDistI.samples(  r   r   c                     g)zQ
Return the ratio by which counts are discounted on average: c*/c

:rtype: float
rF   r5   r   s    r   discountProbDistI.discount2  s     r   c                 f   [         R                   " 5       nUnU R                  5        H   nXR                  U5      -  nUS::  d  M  Us  $    US:  a  W$ U R                  (       a!  [        R
                  " SU < SX!-
  < S35        [         R                  " [        U R                  5       5      5      $ )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choicerm   )r   r   p_initrH   s       r   generateProbDistI.generate<  s     MMOllnF6""AAv %
 v:M??MM8<fjJ }}T$,,.122r   r5   N)r   r   r   r   r   r   r   r   r   r   rT   r   r   r  r   r5   r   r   r   r     sr     J/  
 	 	3    3r   r   )	metaclassc                   6    \ rS rSrSrS rS rS rS rS r	Sr
g	)
UniformProbDistiT  z
A probability distribution that assigns equal probability to each
sample in a given set; and a zero probability to all other
samples.
c                     [        U5      S:X  a  [        S5      e[        U5      U l        S[        U R                  5      -  U l        [        U R                  5      U l        g)z
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)r0   rR   r   
_sampleset_probrm   _samplesr   s     r   r   UniformProbDist.__init__[  sR     w<1X  g,3t//
T__-r   c                 <    XR                   ;   a  U R                  $ S$ Nr   )r	  r
  r   s     r   r   UniformProbDist.probm  s    #6tzz=A=r   c                      U R                   S   $ r  r  r   s    r   rT   UniformProbDist.maxp  s    }}Qr   c                     U R                   $ r:   r  r   s    r   r   UniformProbDist.sampless      }}r   c                 2    S[        U R                  5      -  $ )Nz!<UniformProbDist with %d samples>)r0   r	  r   s    r   r   UniformProbDist.__repr__v  s    2S5IIIr   )r
  r  r	  N)r   r   r   r   r   r   r   rT   r   r   r   r5   r   r   r  r  T  s!    .$> Jr   r  c                   F    \ rS rSrSrS r\S 5       rS rS r	S r
S rS	rg
)RandomProbDistiz  z
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                     [        U5      S:X  a  [        S5      eU R                  U5      U l        [	        U R                  R                  5       5      U l        g )Nr   z9A probability distribution must have at least one sample.)r0   rR   unirand_probsrm   keysr  r   s     r   r   RandomProbDist.__init__  sI    w<1P  ll7+T[[--/0r   c                 n   [        U5      n[        [        U5      5       Vs/ s H  n[        R                  " 5       PM     nn[	        U5      n[        U5       H  u  p%XT-  X2'   M     [	        U5      nUS:w  a  US==   US-
  -  ss'   [        U5       VVs0 s H
  u  p&XcU   _M     snn$ s  snf s  snnf )z
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
r4   )r   rs   r0   r   r   	enumerate)clsr   r   randrowtotalxr   s          r   r  RandomProbDist.unirand  s     g,,1#g,,?@,?q6==?,?@Gg&DAGJ ' GA: BK519$K*3G*<=*<$!1:*<== A >s   B,B1c                     [        U S5      (       d2  [        S U R                  R                  5        5       5      S   U l        U R                  $ )N_maxc              3   ,   #    U  H
  u  pX!4v   M     g 7fr:   r5   r   vr   s      r   r   %RandomProbDist.max.<locals>.<genexpr>  s     E1DvQF1D   r4   )hasattrrT   r  r   r(  r   s    r   rT   RandomProbDist.max  s=    tV$$E1B1B1DEEaHDIyyr   c                 :    U R                   R                  US5      $ r  )r  getr   s     r   r   RandomProbDist.prob  s    {{vq))r   c                     U R                   $ r:   r  r   s    r   r   RandomProbDist.samples  r  r   c                 2    S[        U R                  5      -  $ )Nz'<RandomUniformProbDist with %d samples>)r0   r  r   s    r   r   RandomProbDist.__repr__  s    83t{{;KKKr   )r(  r  r  N)r   r   r   r   r   r   classmethodr  rT   r   r   r   r   r5   r   r   r  r  z  s5    1 > >*
*Lr   r  c                   @    \ rS rSrSrSS jrS rS rS rS r	S	 r
S
rg)DictionaryProbDisti  z
A probability distribution whose probabilities are directly
specified by a given dictionary.  The given dictionary maps
samples to probabilities.
Nc                    Ub  UR                  5       O0 U l        X l        U(       Ga\  [        U5      S:X  a  [	        S5      eU(       a  [        [        U R                  R                  5       5      5      nU[        ::  a;  [        R                  " S[        U5      -  S5      nU H  nXPR                  U'   M     gU R                  R                  5        H  u  pgU R                  U==   U-  ss'   M     g[        U R                  R                  5       5      nUS:X  a&  S[        U5      -  nU H  nXpR                  U'   M     gSU-  nU R                  R                  5        H  u  pgU R                  U==   U-  ss'   M     gg)at  
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  re   )r   
_prob_dict_logr0   rR   sum_logsrm   r   r   r   r   r   r   )	r   	prob_dictr   	normalize	value_sumlogpr%  r   norm_factors	            r   r   DictionaryProbDist.__init__  sI    /8.C)..*	 9~" 5  $T$//*@*@*B%CD	%88C#i.$8!<D&-1* ' !% 5 5 7*i7* !8   6 6 89	>c)n,A&-.* ' #&	/K $ 5 5 7*k9* !8/ r   c                     U R                   (       a#  XR                  ;   a  SU R                  U   -  $ S$ U R                  R                  US5      $ )Nre   r   )r<  r;  r1  r   s     r   r   DictionaryProbDist.prob  sC    995;5N101UTUU??&&vq11r   c                    U R                   (       a   U R                  R                  U[        5      $ XR                  ;  a  [        $ U R                  U   S:X  a  [        $ [        R
                  " U R                  U   S5      $ )Nr   re   )r<  r;  r1  r   r   r   r   s     r   r   DictionaryProbDist.logprob  s_    99??&&vu55__,(A-xx 7;;r   c                     [        U S5      (       d2  [        S U R                  R                  5        5       5      S   U l        U R                  $ )Nr(  c              3   ,   #    U  H
  u  pX!4v   M     g 7fr:   r5   r*  s      r   r   )DictionaryProbDist.max.<locals>.<genexpr>  s     I1HvQF1Hr-  r4   )r.  rT   r;  r   r(  r   s    r   rT   DictionaryProbDist.max  s=    tV$$I1F1F1HII!LDIyyr   c                 6    U R                   R                  5       $ r:   )r;  r  r   s    r   r   DictionaryProbDist.samples  s    ##%%r   c                 2    S[        U R                  5      -  $ )Nz<ProbDist with %d samples>)r0   r;  r   s    r   r   DictionaryProbDist.__repr__  s    +c$//.BBBr   )r<  r(  r;  )NFF)r   r   r   r   r   r   r   r   rT   r   r   r   r5   r   r   r9  r9    s'    (:T2	<
&Cr   r9  c                   @    \ rS rSrSrSS jrS rS rS rS r	S	 r
S
rg)MLEProbDisti  a  
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                     Xl         g)z
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   freqdistr=   s      r   r   MLEProbDist.__init__  s	     "r   c                     U R                   $ ze
Return the frequency distribution that this probability
distribution is based on.

:rtype: FreqDist
rS  r   s    r   rV  MLEProbDist.freqdist       ~~r   c                 8    U R                   R                  U5      $ r:   )rT  rO   r   s     r   r   MLEProbDist.prob  s    ~~""6**r   c                 6    U R                   R                  5       $ r:   rT  rT   r   s    r   rT   MLEProbDist.max      ~~!!##r   c                 6    U R                   R                  5       $ r:   rT  r  r   s    r   r   MLEProbDist.samples      ~~""$$r   c                 <    SU R                   R                  5       -  $ )D
:rtype: str
:return: A string representation of this ``ProbDist``.
z!<MLEProbDist based on %d samples>rT  r   r   s    r   r   MLEProbDist.__repr__"  s    
 3T^^5E5E5GGGr   rS  r:   )r   r   r   r   r   r   rV  r   rT   r   r   r   r5   r   r   rQ  rQ    s&    	"+$%Hr   rQ  c                   J    \ rS rSrSrSrSS jrS rS rS r	S	 r
S
 rS rSrg)LidstoneProbDisti*  a  
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                 L   US:X  d  Uc>  UR                  5       S:X  a*  U R                  R                  SS n[        SU-  S-   5      eUbW  X1R	                  5       :  aD  U R                  R                  SS n[        SU-  SU-  -   S-   S	UR	                  5       -  -   5      eXl        [        U5      U l        U R
                  R                  5       U l        Uc  UR	                  5       nX0l	        U R                  X2-  -   U l
        U R                  S
:X  a  SU l        SU l
        gg)a7  
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).rF   r4   )r   r!   r   rR   r1   rT  float_gammar   _bins_divisor)r   rV  gammar=   names        r   r   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                     U R                   $ rY  rS  r   s    r   rV  LidstoneProbDist.freqdistk  r[  r   c                 V    U R                   U   nX R                  -   U R                  -  $ r:   )rT  rn  rp  r   rH   cs      r   r   LidstoneProbDist.probt  s%    NN6"KK4==00r   c                 6    U R                   R                  5       $ r:   r_  r   s    r   rT   LidstoneProbDist.maxx  s     ~~!!##r   c                 6    U R                   R                  5       $ r:   rc  r   s    r   r   LidstoneProbDist.samples~  re  r   c                 V    U R                   U R                  -  nXR                  U-   -  $ r:   )rn  ro  r   )r   gbs     r   r   LidstoneProbDist.discount  s%    [[4::%WWr\""r   c                 <    SU R                   R                  5       -  $ )C
Return a string representation of this ``ProbDist``.

:rtype: str
z&<LidstoneProbDist based on %d samples>rh  r   s    r   r   LidstoneProbDist.__repr__  s     8$..:J:J:LLLr   )r   ro  rp  rT  rn  r:   )r   r   r   r   r   r   r   rV  r   rT   r   r   r   r   r5   r   r   rk  rk  *  s3    
 J0d1$%#Mr   rk  c                   (    \ rS rSrSrSS jrS rSrg)LaplaceProbDisti  a  
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                 2    [         R                  XSU5        g)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()``.
r4   Nrk  r   rU  s      r   r   LaplaceProbDist.__init__  s     	!!$!T:r   c                 <    SU R                   R                  5       -  $ )rg  z%<LaplaceProbDist based on %d samples>rh  r   s    r   r   LaplaceProbDist.__repr__  s    
 79I9I9KKKr   r5   r:   r   r   r   r   r   r   r   r   r5   r   r   r  r    s    ;"Lr   r  c                   (    \ rS rSrSrSS jrS rSrg)ELEProbDisti  a  
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                 2    [         R                  XSU5        g)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  rU  s      r   r   ELEProbDist.__init__  s     	!!$#t<r   c                 <    SU R                   R                  5       -  $ )r  z!<ELEProbDist based on %d samples>rh  r   s    r   r   ELEProbDist.__repr__  s     3T^^5E5E5GGGr   r5   r:   r  r5   r   r   r  r    s    ="Hr   r  c                   \    \ rS rSrSrSrSS jrS rS rS r	S	 r
S
 rS rS rS rS rSrg)HeldoutProbDisti  a  
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                 8   Xl         X l        XR                  5          U l        U R	                  5       nUR                  U5      n[        U R                  S-   5       Vs/ s H  oeU   PM	     nnUR                  5       nU R                  XGU5      U l	        gs  snf )aq  
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()``.
r4   N)
_base_fdist_heldout_fdistrT   _max_r_calculate_Trr;   rs   r   _calculate_estimate	_estimate)	r   
base_fdistheldout_fdistr=   Trr;   r<   r>   r   s	            r   r   HeldoutProbDist.__init__  s    $ &+ !!12 !t$$T[[1_565!1g56OO 11"!< 7s   Bc                     S/U R                   S-   -  nU R                   H+  nU R                  U   nX==   U R                  U   -  ss'   M-     U$ )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)
rF   r4   )r  r  r  )r   r  rH   r<   s       r   r  HeldoutProbDist._calculate_Tr%  sV     UdkkAo&))F  (AET((00E * 	r   c                     / n[        U R                  S-   5       H9  nX%   S:X  a  UR                  S5        M  UR                  X   X%   U-  -  5        M;     U$ )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.
r4   r   N)rs   r  r   )r   r  r>   r   estimater<   s         r   r  #HeldoutProbDist._calculate_estimate3  sU    ( t{{Q'Auz% 34	 (
 r   c                     U R                   $ )zj
Return the base frequency distribution that this probability
distribution is based on.

:rtype: FreqDist
)r  r   s    r   r  HeldoutProbDist.base_fdistO  s     r   c                     U R                   $ )zm
Return the heldout frequency distribution that this
probability distribution is based on.

:rtype: FreqDist
)r  r   s    r   r  HeldoutProbDist.heldout_fdistX  s     """r   c                 6    U R                   R                  5       $ r:   )r  r  r   s    r   r   HeldoutProbDist.samplesa  s    $$&&r   c                 >    U R                   U   nU R                  U   $ r:   )r  r  )r   rH   r<   s      r   r   HeldoutProbDist.probd  s!    V$~~a  r   c                 6    U R                   R                  5       $ r:   )r  rT   r   s    r   rT   HeldoutProbDist.maxi  s     ##%%r   c                     [        5       er:   NotImplementedErrorr   s    r   r   HeldoutProbDist.discounto      !##r   c                 r    SnXR                   R                  5       U R                  R                  5       4-  $ )rg  z6<HeldoutProbDist: %d base samples; %d heldout samples>)r  r   r  )r   r   s     r   r   HeldoutProbDist.__repr__r  s6    
 E$$&&($*=*=*?*?*ABBBr   )r  r  r  r  r:   )r   r   r   r   r   r   r   r  r  r  r  r   r   rT   r   r   r   r5   r   r   r  r    sC    'R J =D8 #'!
&$Cr   r  c                   @    \ rS rSrSrSrS rS rS rS r	S r
S	 rS
rg)CrossValidationProbDisti{  a)  
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                     Xl         / U l        U H9  nU H0  nX4Ld  M	  [        X4U5      nU R                  R                  U5        M2     M;     g)a5  
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_probdistsr  r   )r   	freqdistsr=   fdist1fdist2probdists         r   r    CrossValidationProbDist.__init__  sM      $ #%F#'.vtDH++228< $  r   c                     U R                   $ )zh
Return the list of frequency distributions that this ``ProbDist`` is based on.

:rtype: list(FreqDist)
)r  r   s    r   r  !CrossValidationProbDist.freqdists  s     r   c                 N    [        [        S U R                   5       / 5      5      $ )Nc              3   8   #    U  H  n[        U5      v   M     g 7fr:   )rm   )r   fds     r   r   2CrossValidationProbDist.samples.<locals>.<genexpr>  s     ;?RR?rK   )r   r   r  r   s    r   r   CrossValidationProbDist.samples  s    3;4??;R@AAr   c                     SnU R                    H  nX#R                  U5      -  nM     U[        U R                   5      -  $ )NrF   )r  r   r0   )r   rH   r   heldout_probdists       r   r   CrossValidationProbDist.prob  sC      $ 7 7))&11D !8c$11222r   c                     [        5       er:   r  r   s    r   r    CrossValidationProbDist.discount  r  r   c                 2    S[        U R                  5      -  $ )r  z!<CrossValidationProbDist: %d-way>)r0   r  r   s    r   r    CrossValidationProbDist.__repr__  s     3S5IIIr   )r  r  N)r   r   r   r   r   r   r   r  r   r   r   r   r   r5   r   r   r  r  {  s.     J=6B3$Jr   r  c                   F    \ rS rSrSrSS jrS rS rS rS r	S	 r
S
 rSrg)WittenBellProbDisti  ao  
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                 
   Ub+  X!R                  5       :  d   SUR                  5       -  5       eUc  UR                  5       nXl        U R                  R                  5       U l        X R                  R                  5       -
  U l        U R                  R	                  5       U l        U R
                  S:X  a  SU R                  -  U l        gU R                  U R                  U R
                  U R                  -   -  -  U l        g)ay  
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  )r1   rT  _T_Zr   r   _P0rU  s      r   r   WittenBellProbDist.__init__  s    6 |tzz|3 	
BXZZ\Q	
3 <::<D!..""$))++..""$77a<TWW}DHww$''TWWtww->"?@DHr   c                 z    U R                   U   nUS:w  a  X R                  U R                  -   -  $ U R                  $ r  )rT  r   r  r  rw  s      r   r   WittenBellProbDist.prob  s5    NN6"*+q&qGGdgg%&>dhh>r   c                 6    U R                   R                  5       $ r:   r_  r   s    r   rT   WittenBellProbDist.max   ra  r   c                 6    U R                   R                  5       $ r:   rc  r   s    r   r   WittenBellProbDist.samples  re  r   c                     U R                   $ r:   rS  r   s    r   rV  WittenBellProbDist.freqdist      ~~r   c                     [        5       er:   r  r   s    r   r   WittenBellProbDist.discount	  r  r   c                 <    SU R                   R                  5       -  $ )r  z(<WittenBellProbDist based on %d samples>rh  r   s    r   r   WittenBellProbDist.__repr__  s     :DNN<L<L<NNNr   )r   r  r  r  rT  r:   )r   r   r   r   r   r   r   rT   r   rV  r   r   r   r5   r   r   r  r    s-    )AV?
$%$Or   r  c                       \ rS rSrSrSrSS jrS rS rS r	S	 r
S
 rS rS rS rS rS rS rS rS rS rS rSrg)SimpleGoodTuringProbDistiP  a  
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                 4   Ub.  X!R                  5       :  d   SUR                  5       S-   -  5       eUc  UR                  5       S-   nXl        X l        U R                  5       u  p4U R	                  X45        U R                  X45        U R                  X45        g)a0  
: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()+1r4   )r1   rT  ro  rB   find_best_fit_switch_renormalize)r   rV  r=   r<   nrs        r   r   !SimpleGoodTuringProbDist.__init__f  s     LD::</	YCxzz|VWGWX	Y/<::<!#D!


1!Q! r   c                 @    U R                   R                  5       nUS	 U$ r  )rT  r;   )r   r;   s     r   _r_Nr_non_zero'SimpleGoodTuringProbDist._r_Nr_non_zero|  s     ~~""$Gr   c                 v    U R                  5       nU(       d  / / 4$ [        [        UR                  5       5      6 $ )zG
Split the frequency distribution in two list (r, Nr), where Nr(r) > 0
)r  zipsortedr   )r   nonzeros     r   rB   SimpleGoodTuringProbDist._r_Nr  s4     %%'r6MF7==?+,,r   c                    U(       a  U(       d  g/ n[        [        U5      5       HR  nUS:  a  XS-
     OSnU[        U5      S-
  :X  a
  SX   -  U-
  OXS-      nSX$   -  Xe-
  -  nUR                  U5        MT     U Vs/ s H  n[        R                  " U5      PM     nnU Vs/ s H  n[        R                  " U5      PM     n	nS=p[        U5      [        U5      -  n[        U	5      [        U	5      -  n[        X5       H  u  pXU-
  X-
  -  -  n
XU-
  S-  -  nM     US:w  a  X-  OSU l        U R                  S:  a  [        R                  " S5        XR                  U-  -
  U l
        gs  snf s  snf )	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   r4   re   g       @rF   r   zSimpleGoodTuring did not find a proper best fit line for smoothing probabilities of occurrences. The probability estimates are likely to be unreliable.)rs   r0   r   r   r   r   r  _sloper   r   
_intercept)r   r<   r  zrjr   kzr_log_rlog_zrxy_covx_varx_meany_meanr%  ys                   r   r  &SimpleGoodTuringProbDist.find_best_fit  s`    s1vAEa%qA !SVaZAD1Q1uXA+'CIIcN	  '((a!a(')*r!$((1+r*Uc%j(Vs6{*&DA6zaj11F&jQ&&E ' ).
fn;;"MM !;;#77# )*s     E1& E6c           
         [        U5       H  u  p4[        U5      US-   :X  d  XS-      US-   :w  a  X@l          gU R                  nUS-   U" US-   5      -  U" U5      -  nUS-   X#S-      -  X#   -  n[        R
                  " U R                  XBU   X#S-      5      5      n[        Xv-
  5      SU-  ::  d  M  X@l          g   g)zT
Calculate the r frontier where we must switch from Nr to Sr
when estimating E[Nr].
r4   g\(\?N)r!  r0   
_switch_at
smoothedNrr   sqrt	_varianceabs)	r   r<   r  r   r_Srsmooth_r_starunsmooth_r_starstds	            r   r   SimpleGoodTuringProbDist._switch  s    
 q\EA1vQ!E(b1f"4"$B!Vr"q&z1BrF:M!AvE2RU:O))DNN2!ubQi@AC?23tczA"$ "r   c                 t    [        U5      n[        U5      n[        U5      nUS-   S-  X2S-  -  -  SX2-  -   -  $ )Nr  re   )rm  )r   r<   r  nr_1s       r   r  "SimpleGoodTuringProbDist._variance  sA    !H2YT{CA~A.#	/BBr   c                     Sn[        X5       H  u  pEX5U R                  U5      -  -  nM     U(       a  SU R                  S5      -
  U-  U l        gg)aI  
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)
rF   r4   r   N)r  _prob_measure	_renormal)r   r<   r  prob_covr  nr_s         r   r  %SimpleGoodTuringProbDist._renormalize  sU     1zGBd00444H "$"4"4Q"778CDN r   c                     [         R                  " U R                  U R                  [         R                  " U5      -  -   5      $ )zk
Return the number of samples with count r.

:param r: The amount of frequency.
:type r: int
:rtype: float
)r   expr  r  r   )r   r<   s     r   r  #SimpleGoodTuringProbDist.smoothedNr  s-     xx$++*CCDDr   c                    U R                   U   nU R                  U5      nUS:X  aX  U R                  U R                   R                  5       :X  a  SnU$ X0R                  U R                   R                  5       -
  -  n U$ X0R                  -  nU$ )zf
Return the sample's probability.

:param sample: sample of the event
:type sample: str
:rtype: float
r   rF   )rT  r  ro  r1   r  )r   rH   rC   r   s       r   r   SimpleGoodTuringProbDist.prob  s     v&u%A:zzT^^--//
  dnn&6&6&889  NN"Ar   c                 ,   US:X  a  U R                   R                  5       S:X  a  gUS:X  aT  U R                   R                  5       S:w  a6  U R                   R                  S5      U R                   R                  5       -  $ U R                  U:  a:  U R                   R                  US-   5      nU R                   R                  U5      nO%U R	                  US-   5      nU R	                  U5      nUS-   U-  U-  nX@R                   R                  5       -  $ )Nr   r  r4   )rT  r   r>   r  r  )r   rC   Er_1Err_stars        r   r  &SimpleGoodTuringProbDist._prob_measure  s    A:$..**,1aZDNN,,.!3>>$$Q'$..*:*:*<<<??U">>$$UQY/D""5)B??519-D'B!)t#b(((***r   c                     Sn[        S[        U R                  5      5       H3  nXR                  U   U R                  U5      -  U R                  -  -  nM5     [        SU5        g )NrF   r   zProbability Sum:)rs   r0   _Nrr  r  r   )r   prob_sumr   s      r   checkSimpleGoodTuringProbDist.check  sT    q#dhh-(Ad&8&8&;;dnnLLH ) (+r   c                 Z    U R                  S5      U R                  R                  5       -  $ )zl
This function returns the total mass of probability transfers from the
seen samples to the unseen samples.
r4   )r  rT  r   r   s    r   r   !SimpleGoodTuringProbDist.discount  s%    
 q!DNN$4$4$666r   c                 6    U R                   R                  5       $ r:   r_  r   s    r   rT   SimpleGoodTuringProbDist.max  ra  r   c                 6    U R                   R                  5       $ r:   rc  r   s    r   r    SimpleGoodTuringProbDist.samples   re  r   c                     U R                   $ r:   rS  r   s    r   rV  !SimpleGoodTuringProbDist.freqdist#  r  r   c                 <    SU R                   R                  5       -  $ )r  z.<SimpleGoodTuringProbDist based on %d samples>rh  r   s    r   r   !SimpleGoodTuringProbDist.__repr__&  s     @$..BRBRBTTTr   )ro  rT  r  r  r  r  r:   )r   r   r   r   r   r   r   r  rB   r  r  r  r  r  r   r  r#  r   rT   r   rV  r   r   r5   r   r   r  r  P  sc    & J!,
-'8R(CDE &+ ,7$%Ur   r  c                   D    \ rS rSrSrSS jrS rS rS rS r	SS jr
S	rg
)MutableProbDisti/  z
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                    X l         [        [        U5      5       Vs0 s H  oBU   U_M
     snU l        [        R                  " SS/5      [        U5      -  U l        [        [        U5      5       HL  nU(       a"  UR                  X$   5      U R
                  U'   M,  UR                  X$   5      U R
                  U'   MN     X0l        gs  snf )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
drF   N)	r  rs   r0   _sample_dictarray_datar   r   _logs)r   	prob_distr   
store_logsr   s        r   r   MutableProbDist.__init__6  s      49#g,4GH4GqQZ]4GH[[se,s7|;
s7|$A ) 1 1'* =

1 )wz :

1	 %
  
 Is   Cc                 \    [        S U R                  R                  5        5       5      S   $ )Nc              3   ,   #    U  H
  u  pX!4v   M     g 7fr:   r5   r*  s      r   r   &MutableProbDist.max.<locals>.<genexpr>P  s     B(AfqA6(Ar-  r4   )rT   r3  r   r   s    r   rT   MutableProbDist.maxN  s'    B(9(9(?(?(ABB1EEr   c                     U R                   $ r:   r  r   s    r   r   MutableProbDist.samplesR  s    }}r   c                     U R                   R                  U5      nUc  gU R                  (       a  SU R                  U   -  $ U R                  U   $ )NrF   re   )r3  r1  r6  r5  r   rH   r   s      r   r   MutableProbDist.probV  sF    !!&)9'+zzqTZZ]#Dtzz!}Dr   c                     U R                   R                  U5      nUc  [        S5      $ U R                  (       a  U R                  U   $ [
        R                  " U R                  U   S5      $ )Nz-infre   )r3  r1  rm  r6  r5  r   r   rA  s      r   r   MutableProbDist.logprob]  sS    !!&)9=  $

tzz!}JA0JJr   c                     U R                   R                  U5      nUc   eU R                  (       a.  U(       a  UO[        R                  " US5      U R
                  U'   gU(       a  SU-  OUU R
                  U'   g)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
Nre   )r3  r1  r6  r   r   r5  )r   rH   r   r   r   s        r   r'   MutableProbDist.updated  s\     !!&)}}::$'DTXXdA->DJJqM+.A$KDDJJqMr   )r5  r6  r3  r  N)T)r   r   r   r   r   r   rT   r   r   r   r'   r   r5   r   r   r0  r0  /  s(     0FEK9r   r0  c                   F    \ rS rSrSrSS jrS rS rS rS r	S	 r
S
 rSrg)KneserNeyProbDisti  af  
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                    U(       d  UR                  5       U l        OX l        X0l        0 U l        [	        [
        5      U l        Xl        [	        [        5      U l	        [	        [        5      U l
        [	        [        5      U l        U Hi  u  pEnU R                  XE4==   XXV4   -  ss'   U R                  XE4==   S-  ss'   U R                  U==   S-  ss'   U R                  XV4==   S-  ss'   Mk     g)aM  
: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)
r4   N)r1   ro  _D_cacher   rA   _bigrams	_trigramsrm  _wordtypes_after_trigrams_contain_wordtypes_before)r   rV  r=   r   w0w1w2s          r   r   KneserNeyProbDist.__init__  s     !DJJ  $C(! !,E 2!,U!3!,U!3"JBBMM2(#xR'==#!!2(+q0+""2&!+&""B8,1,	 #r   c                 4   [        U5      S:w  a  [        S5      e[        U5      nUu  p#nXR                  ;   a  U R                  U   $ XR                  ;   a2  U R                  U   U R                  5       -
  U R                  X#4   -  nOX#4U R                  ;   am  X44U R                  ;   a\  U R                  X#4   nU R                  X44   nX`R                  5       -  U R                  X#4   -  nXpR                  U   U-
  -  n	X-  nOSnXPR                  U'   U$ )N   z$Expected an iterable with 3 members.rF   )
r0   rR   tuplerK  rM  r   rL  rP  rN  rO  )
r   trigramrQ  rR  rS  r   aftrbfrleftover_probbetas
             r   r   KneserNeyProbDist.prob  s   w<1CDD.
kk!;;w'' ..(w/$--/AT]]HF 
 T]]*x4;Q;Q/Q,,bX6,,bX6 "&!74==";R R 44R84?@$+ #'KK Kr   c                     U R                   $ )zY
Return the value by which counts are discounted. By default set to 0.75.

:rtype: float
rJ  r   s    r   r   KneserNeyProbDist.discount  s     wwr   c                     Xl         g)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_discountKneserNeyProbDist.set_discount  s	     r   c                 6    U R                   R                  5       $ r:   )rM  r  r   s    r   r   KneserNeyProbDist.samples  re  r   c                 6    U R                   R                  5       $ r:   )rM  rT   r   s    r   rT   KneserNeyProbDist.max  ra  r   c                 >    SU R                   R                  5        S3$ )z>
Return a string representation of this ProbDist

:rtype: str
z<KneserNeyProbDist based on z	 trigrams)rM  r   r   s    r   r   KneserNeyProbDist.__repr__  s!     .dnn.>.>.@-AKKr   )rJ  rL  ro  rK  rM  rO  rN  rP  )Ng      ?)r   r   r   r   r   r   r   r   rb  r   rT   r   r   r5   r   r   rH  rH    s-    !2F"H%$Lr   rH  c                    ^ ^ [        T [        5      (       a  [        T[        5      (       d  [        S5      e[        UU 4S jT 5       5      $ )Nzexpected a ProbDist.c              3      >#    U  H=  nTR                  U5      [        R                  " TR                  U5      S 5      -  v   M?     g7fre   N)r   r   r   )r   r   actual_pdist
test_pdists     r   r   !log_likelihood.<locals>.<genexpr>  s8      HT1!txx
(:A>>s   AA)r   r   rR   r   )rn  rm  s   ``r   log_likelihoodrp    sB    j),,J|Y4W4W/00 HT  r   c                 ^   ^  U 4S jT R                  5        5       n[        S U 5       5      * $ )Nc              3   F   >#    U  H  nTR                  U5      v   M     g 7fr:   )r   )r   r   pdists     r   r   entropy.<locals>.<genexpr>   s     4OqUZZ]]Os   !c              3   T   #    U  H  o[         R                  " US 5      -  v   M      g7frl  )r   r   )r   r   s     r   r   rt  !  s     2EqDHHQN"Es   &()r   r   )rs  probss   ` r   entropyrw    s'    4EMMO4E2E2222r   c                       \ rS rSrSrSS jrS rS rS rSSS	S	SS	S
.S jr	S r
S rS rS rS rS rS rS rS rS r\rS rSrg)ConditionalFreqDisti)  a&  
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                  " U [        5        U(       a  U H  u  p#X   U==   S-  ss'   M     gg)a"  
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
r4   N)r   r   r
   )r   cond_samplescondrH   s       r   r   ConditionalFreqDist.__init__Y  s:     	T8, ,
6"a'" !- r   c                 Z   ^  U 4S jT R                  5        5       nT R                  SS S U4$ )Nc              3   0   >#    U  H  oTU   4v   M     g 7fr:   r5   )r   r|  r   s     r   r   1ConditionalFreqDist.__reduce__.<locals>.<genexpr>j  s     E3D44:&3Ds   r5   )
conditionsr!   )r   kv_pairss   ` r   
__reduce__ConditionalFreqDist.__reduce__i  s)    E4??3DED$99r   c                 4    [        U R                  5       5      $ )a  
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
rm   r  r   s    r   r  ConditionalFreqDist.conditionsm  s     DIIK  r   c                 B    [        S U R                  5        5       5      $ )zr
Return the total number of sample outcomes that have been
recorded by this ``ConditionalFreqDist``.

:rtype: int
c              3   @   #    U  H  oR                  5       v   M     g 7fr:   rM   )r   fdists     r   r   (ConditionalFreqDist.N.<locals>.<genexpr>  s     8-7799-s   )r   r   r   s    r   r   ConditionalFreqDist.Ny  s     8$++-888r   rV   F)r   rW   rX   rY   r  rZ   c                    SSK Jn	  U(       d  U R	                  5       nOU Vs/ s H  oU ;   d  M
  UPM     nnU(       d)  [        U VVs1 s H  oU     H  oiM     M     snn5      nSU;  a  SUS'   U	R                  5       nU(       Ga|  / nU H~  nU(       a  [        X   R                  U5      5      nOU Vs/ s H
  nX   U   PM     nnU(       a(  U Vs/ s H  nUX   R                  5       -  S-  PM     nnUR                  U5        M     U(       a  SnSnOS	nS
nU(       a  US-  nOUS-  nSnU H&  nUU   US'   US-  nUR                  " U/UQ70 UD6  M(     UR                  US9  UR                  SSS9  UR                  [        [!        U5      5      5        UR#                  U Vs/ s H  n[%        U5      PM     snSS9  U(       a  UR'                  U5        UR)                  S5        UR+                  U5        U(       a  U	R-                  5         U$ ! [         a  n
[        S5      U
eSn
A
ff = fs  snf s  snnf s  snf s  snf s  snf )a  
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   Nr\   rd   re   r^   r]   zlower rightrV   zupper rightr_   r`   labelr4   )locTra   rb   rf   rg   ri   )rj   rk   rl   rR   r  r  rn   rm   rI   r   r   rq   legendro   rr   rs   r0   rt   ru   rp   rv   rw   rZ   )r   r   rW   rX   rY   r  rZ   r(   r)   rx   ry   rx  r+  r~   r{   	conditionrO   rH   r}   r|   
legend_locr   r   s                          r   rq   ConditionalFreqDist.plot  s5   <	+ *J%/=Z9!ZJ=EA!WaWaEFGf$"#F;WWYE'	 G G PQDBIJ'DOF3'DJCGH4aA 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  9s9   H! 	H?H?
I
;I
"I3I!
H<+H77H<c                    [        USS5      n[        US[        U R                  5       5      5      n[        US[        U VVs1 s H  oUU ;   d  M
  X     H  ofiM     M     snn5      5      n[        S U 5       5      n[	        5       n	U Ha  nU(       a  [        X   R                  U5      5      X'   OU V
s/ s H
  oU   U
   PM     sn
X'   [        U[        S X    5       5      5      nMc     [        S U 5       5      n[        SU-  SS	9  U H  n[        S
X4-  SS	9  M     [        5         U H4  n[        S
X4-  SS	9  X    H  n[        SX4-  SS	9  M     [        5         M6     gs  snnf s  sn
f )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
rX   Fr  r   c              3   >   #    U  H  n[        S U-  5      v   M     g7f%sNr/   r   s     r   r   /ConditionalFreqDist.tabulate.<locals>.<genexpr>  s     37aCqMM7r   c              3   >   #    U  H  n[        S U-  5      v   M     g7fr   r/   r   s     r   r   r    s     "C(Q3tax==(r   c              3   >   #    U  H  n[        S U-  5      v   M     g7fr  r/   )r   rx  s     r   r   r    s     ?JqS]]Jr   r   r   r   r   N)r   r  r  rT   dictrm   rI   r   )r   r(   r)   rX   r  rx  r+  r   r   r{   rH   condition_sizer   r}   s                 r   r   ConditionalFreqDist.tabulate  sb     e<
fT__=N6OP
zHz!$YA1AAzHI
 3733A ? ? HI:AB'GFO'Bs"C%("CCDE  ?J??cN",A%5*$#. A%>--37Xeuj(c2 G	 # I Cs   	E+E+8E1c                     [        U[        5      (       d  [        $ U R                  5       nUR	                  5        H  nX#==   X   -  ss'   M     U$ )z+
Add counts from two ConditionalFreqDists.
r   ry  NotImplementedr   r  r   r   resultr|  s       r   r   ConditionalFreqDist.__add__  I     %!455!!$$&DLEK'L 'r   c                     [        U[        5      (       d  [        $ U R                  5       nUR	                  5        H  nX#==   X   -  ss'   X#   (       a  M  X#	 M      U$ )z=
Subtract count, but keep only results with positive counts.
r  r  s       r   r   ConditionalFreqDist.__sub__  sW     %!455!!$$&DLEK'L<<L ' r   c                     [        U[        5      (       d  [        $ U R                  5       nUR	                  5        H  nX#==   X   -  ss'   M     U$ )z@
Union is the maximum of value in either of the input counters.
r  r  s       r   r   ConditionalFreqDist.__or__   r  r   c                     [        U[        5      (       d  [        $ [        5       nU R                  5        H  nX   X   -  nU(       d  M  XBU'   M     U$ )z6
Intersection is the minimum of corresponding counts.
)r   ry  r  r  )r   r   r  r|  newfreqdists        r   r   ConditionalFreqDist.__and__+  sR     %!455!!$&OO%D*u{2K{*t & r   c                   ^ ^ [        T[        5      (       d  [        ST T5        [        T R	                  5       5      R                  TR	                  5       5      =(       a$    [        UU 4S jT R	                  5        5       5      $ )Nr   c              3   :   >#    U  H  nTU   TU   :*  v   M     g 7fr:   r5   )r   rx  r   r   s     r   r   -ConditionalFreqDist.__le__.<locals>.<genexpr><  s#      K
):ADGuQx):r   )r   ry  r   r   r  r   r   r   s   ``r   r   ConditionalFreqDist.__le__9  sh    %!455#D$64??$%..u/?/?/AB 
s K
)-):K
 H
 	
r   c                 b    [        U[        5      (       d  [        SX5        X:*  =(       a    X:g  $ )N<r   ry  r   r   s     r   r   ConditionalFreqDist.__lt__@  s)    %!455#C5}..r   c                 L    [        U[        5      (       d  [        SX5        X:*  $ )Nr   r  r   s     r   r   ConditionalFreqDist.__ge__E  s"    %!455#D$6}r   c                 L    [        U[        5      (       d  [        SX5        X:  $ )N>r  r   s     r   r   ConditionalFreqDist.__gt__J  s"    %!455#C5|r   c                     SSK Jn  U" U 5      $ )Nr   )deepcopy)r   r  )r   r  s     r   r  ConditionalFreqDist.deepcopyO  s    !~r   c                     S[        U 5      -  $ )zN
Return a string representation of this ``ConditionalFreqDist``.

:rtype: str
z(<ConditionalFreqDist with %d conditions>r/   r   s    r   r   ConditionalFreqDist.__repr__V  s     :CIEEr   r5   r:   )r   r   r   r   r   r   r  r  r   rq   r   r   r   r   r   r   r   r   r   r  r   r   r   r5   r   r   ry  ry  )  sw    -^( :
!9 Zx&T		
/



 DFr   ry  c                   4    \ rS rSrSr\S 5       rS rS rSr	g)ConditionalProbDistIi_  aC  
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                     g)zI
Classes inheriting from ConditionalProbDistI should implement __init__.
Nr5   r   s    r   r   ConditionalProbDistI.__init__m  r   r   c                 4    [        U R                  5       5      $ )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  ConditionalProbDistI.conditionss  s     DIIK  r   c                 H    S[        U 5      R                  [        U 5      4-  $ )zN
Return a string representation of this ``ConditionalProbDist``.

:rtype: str
z<%s with %d conditions>)typer   r0   r   s    r   r   ConditionalProbDistI.__repr__}  s"     )DJ,?,?T+KKKr   r5   N)
r   r   r   r   r   r   r   r  r   r   r5   r   r   r  r  _  s&      
!Lr   r  c                   $    \ rS rSrSrS rS rSrg)ConditionalProbDisti  aZ  
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                 Z    X l         X0l        X@l        U H  nU" X   /UQ70 UD6X'   M     g)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   ConditionalProbDist.__init__  sB    0 "2) /I.!$04CDO  r   c                 r    U R                   " [        5       /U R                  Q70 U R                  D6X'   X   $ r:   )r  r
   r  r  r   r   s     r   __missing__ConditionalProbDist.__missing__  s?    **J
++
/3/D/D
	 yr   )r  r  r  Nr   r   r   r   r   r   r  r   r5   r   r   r  r    s    BBr   r  c                   $    \ rS rSrSrS rS rSrg)DictionaryConditionalProbDisti  z{
An alternative ConditionalProbDist that simply wraps a dictionary of
ProbDists rather than creating these from FreqDists.
c                 &    U R                  U5        g)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   &DictionaryConditionalProbDist.__init__  s     	M"r   c                 "    [        5       X'   X   $ r:   )r9  r  s     r   r  )DictionaryConditionalProbDist.__missing__  s    &(	yr   r5   Nr  r5   r   r   r  r    s    
#r   r  gKH9re   c                     X[         -   :  a  U$ X[         -   :  a  U $ [        X5      nU[        R                  " SX-
  -  SX-
  -  -   S5      -   $ )z
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.
re   )_ADD_LOGS_MAX_DIFFminr   r   )logxlogybases      r   add_logsr    sX     ''''''t?D$((1-dk0BBAFFFr   c                 Z    [        U 5      S:w  a  [        [        U SS  U S   5      $ [        $ )Nr   r4   )r0   r   r  r   )logss    r   r=  r=    s*    25d)q.6(DHd1g.KeKr   c                   6    \ rS rSrSrS rS rS rS rS r	Sr
g	)
ProbabilisticMixIni	  a  
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                     SU;   a*  SU;   a  [        S5      e[        R                  XS   5        gSU;   a  [        R                  XS   5        gS=U l        U l        g)aY  
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)	TypeErrorr  set_probset_logprob_ProbabilisticMixIn__prob_ProbabilisticMixIn__logprob)r   r)   s     r   r   ProbabilisticMixIn.__init__	  s[     VF" STT"++D.A& **4	1BC+//DK$.r   c                     Xl         SU l        g)zr
Set the probability associated with this object to ``prob``.

:param prob: The new probability
:type prob: float
Nr  r  r   r   s     r   r  ProbabilisticMixIn.set_prob3	  s     r   c                     Xl         SU l        g)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)r  r  )r   r   s     r   r  ProbabilisticMixIn.set_logprob=	  s     !r   c                 x    U R                   c"  U R                  c  gSU R                  -  U l         U R                   $ )zD
Return the probability associated with this object.

:rtype: float
Nre   r  r   s    r   r   ProbabilisticMixIn.probI	  s5     ;;~~%/DK{{r   c                     U R                   c4  U R                  c  g[        R                  " U R                  S5      U l         U R                   $ )z_
Return ``log(p)``, where ``p`` is the probability associated
with this object.

:rtype: float
Nre   )r  r  r   r   r   s    r   r   ProbabilisticMixIn.logprobU	  s;     >>!{{"!XXdkk15DN~~r   )	__logprob__probN)r   r   r   r   r   r   r  r  r   r   r   r5   r   r   r  r  	  s     20,

r   r  c                        \ rS rSrS rS rSrg)ImmutableProbabilisticMixInic	  c                 F    [        SU R                  R                  -  5      eNz%s is immutablerR   r!   r   r  s     r   r  $ImmutableProbabilisticMixIn.set_probd	      *T^^-D-DDEEr   c                 F    [        SU R                  R                  -  5      er  r   r  s     r   r  'ImmutableProbabilisticMixIn.set_logprobg	  r  r   r5   N)r   r   r   r   r  r  r   r5   r   r   r  r  c	  s    FFr   r  c                 $    X;   a  X   nX	 U$ UnU$ r:   r5   )r)   r   defaultargs       r   r   r   n	  s&    
}kK J Jr   c                     [        5       n[        U5       HG  n[        R                  " SSU -   S-  5      [        R                  " SU S-  5      -   nX$==   S-  ss'   MI     U$ )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.
r4   re   r   )r
   rs   r   randint)
numsamplesnumoutcomesr  r%  r  s        r   _create_rand_fdistr  |	  s`     JE;NN1q:~!34v~~zQ8
 
 	A	  
 Lr   c                     [        5       n[        SSU -   S-  S-   5       H+  n[        SU S-  S-   5       H  nXU-   ==   S-  ss'   M     M-     [        U5      $ )zd
Return the true probability distribution for the experiment
``_create_rand_fdist(numsamples, x)``.
r4   re   r   )r
   rs   rQ  )r
  r  r%  r  s       r   _create_sum_pdistr  	  sa    
 JE1q:~!+a/0q*/A-.Aa%LAL / 1 ur      c                   ^ [        X5      n[        X5      n[        X5      n[        U5      [        USU 5      [        X#U 5      [        X2U 5      [	        X#U/U 5      [        U5      [        US5      [        U 5      /n/ n[        SU S-   5       HO  nUR                  [        XrR                  U5      /U Vs/ s H  oR                  U5      PM     sn-   5      5        MQ     [        SX U4-  5        [        S[        U5      S-   -  5        SS[        U5      S-
  -  -   S	-   n	[        U	[        S
 USS  5       5      -  5        [        S[        U5      S-   -  5        SS[        U5      S-
  -  -   S-   n	U H  n
[        X-  5        M     [        [        U6 5      nUSS  V
s/ s H  n
[!        U
5      PM     nn
[        S[        U5      S-   -  5        SS[        U5      -  -   S-   n	[        U	[        U5      -  5        [        S[        U5      S-   -  5        [        SU-  5      S:  a*  [        SU-  5        [        SU-  5        [        SU-  5        [        5         [        S5        U HY  m[#        U4S j[        S5       5       5      n[        SR%                  TR&                  R(                  SS SU-  SS 5      5        M[     [        5         gs  snf s  sn
f )a  
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
r     r4   z=%d samples (1-%d); %d outcomes were sampled for each FreqDistz	=========re   z      FreqDist z%8s z	|  Actualc              3   >   #    U  H  n[        U5      S S v   M     g7f)r4   	   N)repr)r   rs  s     r   r   demo.<locals>.<genexpr>	  s     F+DK!,+r   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   D   >#    U  H  nTR                  5       v   M     g 7fr:   )r  )r   r   rs  s     r   r   r  	  s     ?;a));s      z	{:>20} {}   7   )r  rQ  rk  r  r  r  r  rs   r   rW  rO   r   r   r0   rm   r  r   r
   r   r!   r   )r
  r  r  r  fdist3pdistsvalsrN   rs  	FORMATSTRr    zvalssumsr  s           `     r   demor!  	  s   ,  
8F
8F
8F 	Fj1
3
3 8*E ( +*%	F D1j1n%E1kk!n-F0SF5AF0SSTU & 
G;
/	0 
'S[1_
%&!Fc&kAo$>>LI	)eF&"+FF
FG	'S[1_
%&S[1_!==	IIio  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   6K"Kc            	      B   SSK Jn   U R                  R                  S5      n[	        U5      n[        U5      n[        SR                  SSS5      5        S [        UR                  5       S	 S
S9 5       nU H%  n[        SXRU   UR                  U5      4-  5        M'     g )Nr   )corpuszausten-emma.txtz{:>18} {:>8}  {:>14}word	frequencySimpleGoodTuringc              3   *   #    U  H	  u  pUv   M     g 7fr:   r5   )r   r   values      r   r   gt_demo.<locals>.<genexpr>	  s      X
Xs   c                     U S   $ )Nr4   r5   )r6   s    r   r   gt_demo.<locals>.<lambda>	  s    $q'r   T)r   reversez%18s %8d  %14e)nltkr#  	gutenbergwordsr
   r  r   r   r  r   r   )r#  
emma_wordsr  sgtfd_keys_sortedr   s         r   gt_demor3  	  s    !!''(9:J	*	B
"2
&C	
 
'
'=O
PQ$RXXZ5ISWXN ##w!>>? r   __main__r      r  )ry  r  r  r  r  r9  r  r
   r  r  r  r  rk  rQ  r0  rH  r   r  r  r  r  rp  r=  rw  )r  i  )4r   r4  r   r   r   abcr   r   collectionsr   r   	functoolsr   nltk.internalsr   rm  r   r
   r   r  r  r9  rQ  rk  r  r  r  r  r  r  r0  rH  rp  rw  ry  r  r  r  r  r   r  r  r=  r  r  r   r  r  r!  r3  r   __all__r5   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 XXeQ' GL] ]@F"4 F 	K\@ zBKDMIr   