
    /hM                     x   S r SSKrSSKJr  SSKJrJr  SSKJr  SSK	J
r
JrJrJr  SSKJrJ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 jr\S:X  a  \" 5         gg)!a  
Classes and interfaces for associating probabilities with tree
structures that represent the internal organization of a text.  The
probabilistic parser module defines ``BottomUpProbabilisticChartParser``.

``BottomUpProbabilisticChartParser`` is an abstract class that implements
a bottom-up chart parser for ``PCFG`` grammars.  It maintains a queue of edges,
and adds them to the chart one at a time.  The ordering of this queue
is based on the probabilities associated with the edges, allowing the
parser to expand more likely edges before less likely ones.  Each
subclass implements a different queue ordering, producing different
search strategies.  Currently the following subclasses are defined:

  - ``InsideChartParser`` searches edges in decreasing order of
    their trees' inside probabilities.
  - ``RandomChartParser`` searches edges in random order.
  - ``LongestChartParser`` searches edges in decreasing order of their
    location's length.

The ``BottomUpProbabilisticChartParser`` constructor has an optional
argument beam_size.  If non-zero, this controls the size of the beam
(aka the edge queue).  This option is most useful with InsideChartParser.
    N)reduce)PCFGNonterminal)ParserI)AbstractChartRuleChartLeafEdgeTreeEdge)ProbabilisticTreeTreec                       \ rS rSrS rSrg)ProbabilisticLeafEdge2   c                     g)Ng      ? selfs    I/var/www/auris/envauris/lib/python3.13/site-packages/nltk/parse/pchart.pyprobProbabilisticLeafEdge.prob3   s        r   N)__name__
__module____qualname____firstlineno__r   __static_attributes__r   r   r   r   r   2   s    r   r   c                   0    \ rS rSrS rS r\S 5       rSrg)ProbabilisticTreeEdge7   c                 j    [         R                  " U /UQ70 UD6  Xl        U R                  U4U l        g N)r
   __init___prob_comparison_key)r   r   argskwargss       r   r"   ProbabilisticTreeEdge.__init__8   s2    $000
 $ 4 4d;r   c                     U R                   $ r!   )r#   r   s    r   r   ProbabilisticTreeEdge.prob>   s    zzr   c                 Z    [        X!U4U R                  5       U R                  5       S5      $ )Nr   )r   lhsrhs)
productionindexps      r   from_production%ProbabilisticTreeEdge.from_productionA   s*    $u~z~~/1A1
 	
r   )r$   r#   N)	r   r   r   r   r"   r   staticmethodr0   r   r   r   r   r   r   7   s     < 
 
r   r   c                       \ rS rSrSrS rSrg)ProbabilisticBottomUpInitRuleI   r   c              #      #    [        UR                  5       5       H;  n[        UR                  U5      U5      nUR	                  US5      (       d  M7  Uv   M=     g 7f)Nr   )range
num_leavesr   leafinsert)r   chartgrammarr.   new_edges        r   apply#ProbabilisticBottomUpInitRule.applyL   sH     5++-.E,UZZ->FH||Hb)) /s   AA	Ar   Nr   r   r   r   	NUM_EDGESr>   r   r   r   r   r4   r4   I   s    Ir   r4   c                       \ rS rSrSrS rSrg) ProbabilisticBottomUpPredictRuleS      c              #   R  #    UR                  5       (       a  g UR                  5        Hy  nUR                  5       UR                  5       S   :X  d  M*  [        R                  XCR                  5       UR                  5       5      nUR                  US5      (       d  Mu  Uv   M{     g 7f)Nr   r   )	is_incompleteproductionsr+   r,   r   r0   startr   r:   )r   r;   r<   edgeprodr=   s         r   r>   &ProbabilisticBottomUpPredictRule.applyV   s{     '')DxxzTXXZ]*0@@**,		 <<"--"N *s   AB'AB'	B'r   Nr@   r   r   r   rC   rC   S   s    I	#r   rC   c                       \ rS rSrSrS rSrg)ProbabilisticFundamentalRuleb      c              #   d  #    UR                  5       UR                  5       :X  aL  UR                  5       UR                  5       :X  a*  UR	                  5       (       a  UR                  5       (       d  g UR                  5       UR                  5       -  n[        UUR                  5       UR                  5       4UR                  5       UR                  5       UR                  5       S-   S9nSnUR                  U5       H!  nUR                  XhU4-   5      (       d  M  SnM#     U(       a  Uv   g g 7f)NrE   )spanr+   r,   dotFT)endrI   nextsymr+   rG   is_completer   r   r,   rS   child_pointer_listsr:   )	r   r;   r<   	left_edge
right_edger/   r=   changed_chartcpl1s	            r   r>   "ProbabilisticFundamentalRule.applye   s      MMOz//11!!#z~~'77''))&&(( NNz00(//#Z^^%56!#
 --i8D||Hj]&:;; $ 9
 N s   DD0D0r   Nr@   r   r   r   rN   rN   b   s    Ir   rN   c                   2    \ rS rSrSr\" 5       rS rS rSr	g)&SingleEdgeProbabilisticFundamentalRule   rE   c              #     #    U R                   nUR                  5       (       aO  UR                  UR                  5       SUR	                  5       S9 H  nUR                  XX55       S h  vN   M     g UR                  UR                  5       SUR                  5       S9 H  nUR                  XXS5       S h  vN   M     g  NX N7f)NT)rI   rV   r+   F)rT   rV   rU   )_fundamental_rulerG   selectrT   rU   r>   rI   r+   )r   r;   r<   edge1fredge2s         r   r>   ,SingleEdgeProbabilisticFundamentalRule.apply   s     ##  iikt &  88EEAAA KKMueiik &  88EEAAA B Bs%   A'C)C*AC8C9
CCc                     g)NzFundamental Ruler   r   s    r   __str__.SingleEdgeProbabilisticFundamentalRule.__str__   s    !r   r   N)
r   r   r   r   rA   rN   ra   r>   rh   r   r   r   r   r^   r^      s    I46B"r   r^   c                   J    \ rS rSrSrSS jrS rSS jrS rS r	S r
S	 rS
rg) BottomUpProbabilisticChartParser   a  
An abstract bottom-up parser for ``PCFG`` grammars that uses a ``Chart`` to
record partial results.  ``BottomUpProbabilisticChartParser`` maintains
a queue of edges that can be added to the chart.  This queue is
initialized with edges for each token in the text that is being
parsed.  ``BottomUpProbabilisticChartParser`` inserts these edges into
the chart one at a time, starting with the most likely edges, and
proceeding to less likely edges.  For each edge that is added to
the chart, it may become possible to insert additional edges into
the chart; these are added to the queue.  This process continues
until enough complete parses have been generated, or until the
queue is empty.

The sorting order for the queue is not specified by
``BottomUpProbabilisticChartParser``.  Different sorting orders will
result in different search strategies.  The sorting order for the
queue is defined by the method ``sort_queue``; subclasses are required
to provide a definition for this method.

:type _grammar: PCFG
:ivar _grammar: The grammar used to parse sentences.
:type _trace: int
:ivar _trace: The level of tracing output that should be generated
    when parsing a text.
c                 h    [        U[        5      (       d  [        S5      eXl        X l        X0l        g)a  
Create a new ``BottomUpProbabilisticChartParser``, that uses
``grammar`` to parse texts.

:type grammar: PCFG
:param grammar: The grammar used to parse texts.
:type beam_size: int
:param beam_size: The maximum length for the parser's edge queue.
:type trace: int
:param trace: The level of tracing that should be used when
    parsing a text.  ``0`` will generate no tracing output;
    and higher numbers will produce more verbose tracing
    output.
z&The grammar must be probabilistic PCFGN)
isinstancer   
ValueError_grammar	beam_size_trace)r   r<   rq   traces       r   r"   )BottomUpProbabilisticChartParser.__init__   s,     '4((EFF"r   c                     U R                   $ r!   )rp   r   s    r   r<   (BottomUpProbabilisticChartParser.grammar   s    }}r   c                     Xl         g)a  
Set the level of tracing output that should be generated when
parsing a text.

:type trace: int
:param trace: The trace level.  A trace level of ``0`` will
    generate no tracing output; and higher trace levels will
    produce more verbose tracing output.
:rtype: None
N)rr   )r   rs   s     r   rs   &BottomUpProbabilisticChartParser.trace   s	     r   c           	         U R                   R                  U5        [        [        U5      5      nU R                   n[	        5       n[        5       n[        5       n/ nUR                  X#5       HU  nU R                  S:  a1  [        SUR                  USS9<S SUR                  5       < S35        UR                  U5        MW     [        U5      S:  a  U R                  Xr5        U R                  (       a  U R!                  Xr5        UR#                  5       nU R                  S:  a1  [        SUR                  USS9<S SUR                  5       < S35        UR%                  UR                  X#U5      5        UR%                  UR                  X#U5      5        [        U5      S:  a  M  [        UR'                  UR)                  5       [*        5      5      n	0 n
UR-                  5        H3  nUR                  5       XR/                  5       UR1                  5       4'   M5     U	 H  nU R3                  X5        M     U	R5                  S	S
 S9  [7        U	5      $ )NrE   z  rP   )width50z []r   Tc                 "    U R                  5       $ r!   r   )trees    r   <lambda>8BottomUpProbabilisticChartParser.parse.<locals>.<lambda>  s
    499;r   )reversekey)rp   check_coverager   listr4   rC   r^   r>   rr   printpretty_format_edger   appendlen
sort_queuerq   _prunepopextendparsesrI   r   rH   r+   r,   _setprobsortiter)r   tokensr;   r<   bu_initburd   queuerJ   r   
prod_probsrK   parses                r   r   &BottomUpProbabilisticChartParser.parse   s   $$V,d6l#-- 01-/35  MM%1D{{Q//A/>		M LL 2 %j1nOOE) ~~E) 99;D{{Q//A/>		M LL%$78LL%$78% %j1n* ell7==?4EFG 
'')D15Jxxz488:-. *EMM%,  	D&>?F|r   c                    UR                  5       b  g [        UR                  5       5      n/ nU HS  n[        U[        5      (       a*  UR                  [        UR                  5       5      5        MB  UR                  U5        MU     X#[        U5      4   nU H=  n[        U[        5      (       d  M  U R                  XR5        XeR                  5       -  nM?     UR                  U5        g r!   )	r   r   labelrn   r   r   tupler   set_prob)r   r   r   r+   r,   childr   s          r   r   )BottomUpProbabilisticChartParser._setprob  s    99;" $**,'E%&&

;u{{}56

5!	 
 uSz/* E%&&e0

$ 
 	dr   c                     [        5       e)a<  
Sort the given queue of ``Edge`` objects, placing the edge that should
be tried first at the beginning of the queue.  This method
will be called after each ``Edge`` is added to the queue.

:param queue: The queue of ``Edge`` objects to sort.  Each edge in
    this queue is an edge that could be added to the chart by
    the fundamental rule; but that has not yet been added.
:type queue: list(Edge)
:param chart: The chart being used to parse the text.  This
    chart can be used to provide extra information for sorting
    the queue.
:type chart: Chart
:rtype: None
)NotImplementedErrorr   r   r;   s      r   r   +BottomUpProbabilisticChartParser.sort_queue,  s      "##r   c                     [        U5      U R                  :  aX  [        U5      U R                  -
  nU R                  S:  a*  USU  H!  n[        SUR	                  US5      -  5        M#     USU2	 gg)z@Discard items in the queue if the queue is longer than the beam.rP   Nz  %-50s [DISCARDED])r   rq   rr   r   r   )r   r   r;   splitrJ   s        r   r   'BottomUpProbabilisticChartParser._prune>  sk    u:&J/E{{Q!&5MD/%2J2J4QR2SST *fuf 'r   )rp   rr   rq   N)r   r   )rP   )r   r   r   r   __doc__r"   r<   rs   r   r   r   r   r   r   r   r   rk   rk      s+    4*7r,$$r   rk   c                       \ rS rSrSrS rSrg)InsideChartParseriH  a%  
A bottom-up parser for ``PCFG`` grammars that tries edges in descending
order of the inside probabilities of their trees.  The "inside
probability" of a tree is simply the
probability of the entire tree, ignoring its context.  In
particular, the inside probability of a tree generated by
production *p* with children *c[1], c[2], ..., c[n]* is
*P(p)P(c[1])P(c[2])...P(c[n])*; and the inside
probability of a token is 1 if it is present in the text, and 0 if
it is absent.

This sorting order results in a type of lowest-cost-first search
strategy.
c                 $    UR                  S S9  g)a  
Sort the given queue of edges, in descending order of the
inside probabilities of the edges' trees.

:param queue: The queue of ``Edge`` objects to sort.  Each edge in
    this queue is an edge that could be added to the chart by
    the fundamental rule; but that has not yet been added.
:type queue: list(Edge)
:param chart: The chart being used to parse the text.  This
    chart can be used to provide extra information for sorting
    the queue.
:type chart: Chart
:rtype: None
c                 "    U R                  5       $ r!   r~   rJ   s    r   r   .InsideChartParser.sort_queue.<locals>.<lambda>h  s
    DIIKr   r   Nr   r   s      r   r   InsideChartParser.sort_queueY  s     	

/
0r   r   Nr   r   r   r   r   r   r   r   r   r   r   r   H  s     1r   r   c                       \ rS rSrSrS rSrg)RandomChartParseri  z
A bottom-up parser for ``PCFG`` grammars that tries edges in random order.
This sorting order results in a random search strategy.
c                 h    [         R                  " S[        U5      S-
  5      nX   US   sUS'   X'   g )Nr   rE   )randomrandintr   )r   r   r;   is       r   r   RandomChartParser.sort_queue  s2    NN1c%j1n-!&59rEHr   r   Nr   r   r   r   r   r     s    6r   r   c                       \ rS rSrSrS rSrg)UnsortedChartParseri  zN
A bottom-up parser for ``PCFG`` grammars that tries edges in whatever order.
c                     g r!   r   r   s      r   r   UnsortedChartParser.sort_queue  s    r   r   Nr   r   r   r   r   r     s    
r   r   c                       \ rS rSrSrS rSrg)LongestChartParseri  z
A bottom-up parser for ``PCFG`` grammars that tries longer edges before
shorter ones.  This sorting order results in a type of best-first
search strategy.
c                 $    UR                  S S9  g )Nc                 "    U R                  5       $ r!   )lengthr   s    r   r   /LongestChartParser.sort_queue.<locals>.<lambda>  s
    DKKMr   r   r   r   s      r   r   LongestChartParser.sort_queue  s    

1
2r   r   Nr   r   r   r   r   r     s    3r   r   c           
      R   SSK nSSKnSSKJn  SSKJn  [        R                  " S5      n[        R                  " S5      nSU4SU4/n	U c  [        5         [        [        U	5      5       H9  n
[        U
S	-   S
 SX   S    35        [        SX   S	   -  5        [        5         M;     [        SS	[        U	5      4-  SS9  [        UR                  R                  5       R                  5       5      S	-
  n  X   u  pUR                  5       nUR!                  U5      UR#                  U5      UR%                  U5      UR'                  U5      UR!                  U[        U5      S	-   S9/n/ n/ n/ n0 nU H  n[        SU SU SU 35        UR)                  S5        UR                  5       n[+        UR-                  U5      5      nUR/                  UR                  5       U-
  5        U(       a  [1        S US5      [        U5      -  OSnUR/                  U5        UR/                  [        U5      5        U H  nS	UUR3                  5       '   M     M     [        5         [        S5        [        S5        [        [        U5      5       H@  n
[        SX   R4                  R6                  X   R8                  X   UU
   UU
   4-  5        MB     UR;                  5       nU(       a  [1        S US5      [        U5      -  nOSn[        S5        [        SSS[        U5      U4-  5        UcY  [        5         [        SSS9  UR                  R                  5       R                  5       R=                  5       R?                  S5      nU(       a  SS K J!n  [        S!5        U" U6   UcY  [        5         [        S"SS9  UR                  R                  5       R                  5       R=                  5       R?                  S5      nU(       a  U H  n[        U5        M     gg!   [        S5         g= f)#z
A demonstration of the probabilistic parsers.  The user is
prompted to select which demo to run, and how many parses should
be found; and then each parser is run on the same demo, and a
summary of the results are displayed.
r   N)tokenize)pcharta7  
    S -> NP VP [1.0]
    NP -> Det N [0.5] | NP PP [0.25] | 'John' [0.1] | 'I' [0.15]
    Det -> 'the' [0.8] | 'my' [0.2]
    N -> 'man' [0.5] | 'telescope' [0.5]
    VP -> VP PP [0.1] | V NP [0.7] | V [0.2]
    V -> 'ate' [0.35] | 'saw' [0.65]
    PP -> P NP [1.0]
    P -> 'with' [0.61] | 'under' [0.39]
    a  
    S    -> NP VP         [1.0]
    VP   -> V NP          [.59]
    VP   -> V             [.40]
    VP   -> VP PP         [.01]
    NP   -> Det N         [.41]
    NP   -> Name          [.28]
    NP   -> NP PP         [.31]
    PP   -> P NP          [1.0]
    V    -> 'saw'         [.21]
    V    -> 'ate'         [.51]
    V    -> 'ran'         [.28]
    N    -> 'boy'         [.11]
    N    -> 'cookie'      [.12]
    N    -> 'table'       [.13]
    N    -> 'telescope'   [.14]
    N    -> 'hill'        [.5]
    Name -> 'Jack'        [.52]
    Name -> 'Bob'         [.48]
    P    -> 'with'        [.61]
    P    -> 'under'       [.39]
    Det  -> 'the'         [.41]
    Det  -> 'a'           [.31]
    Det  -> 'my'          [.28]
    zI saw John with my telescopez:the boy saw Jack with Bob under the table with a telescoperE   z>3z: z     %rzWhich demo (%d-%d)?  )rT   zBad sentence number)rq   z
s: z	
parser: z

grammar:    c                 &    XR                  5       -   $ r!   r~   abs     r   r   demo.<locals>.<lambda>      FFHr   zC       Parser      Beam | Time (secs)   # Parses   Average P(parse)zC------------------------+------------------------------------------z%18s %4d |%11.4f%11d%19.14fc                 &    XR                  5       -   $ r!   r~   r   s     r   r   r   '  r   r   z%18s      |%11s%11d%19.14fz(All Parses)zn/azDraw parses (y/n)? y)
draw_treesz  please wait...zPrint parses (y/n)? )"systimenltkr   
nltk.parser   r   
fromstringr   r7   r   intstdinreadlinestripr   r   r   r   r   rs   r   r   r   r   freeze	__class__r   rq   keyslower
startswithnltk.draw.treer   )choicedraw_parsesprint_parsesr   r   r   r   	toy_pcfg1	toy_pcfg2demosr   sentr<   r   parserstimes	average_p
num_parses
all_parsesparsertr   r/   r   r   s                            r   demor     s    ! 		I 	I: 
(3	EyQE
 ~s5z"AQU2Jb!./)ehqk)*G # 	$3u:6C@SYY'')//12Q6 ZZ\F 	  )  )""7+!!'*  CK!O DG EIJJdV:fX[	BCQIIKfll6*+TYY[1_%JPF,fa83v;FVW#f+&A%&Jqxxz"   
G	
OP	
OP3w< )
$$--
$$1!		
 ! __F,fa83v;F	
OP	
&.%Va)P
PQ#-ii((*00288:EEcJ- !F$#.yy))+11399;FFsKE%L  Q#$s   4P P&__main__)NNN)r   r   	functoolsr   nltk.grammarr   r   nltk.parse.apir   nltk.parse.chartr   r   r	   r
   	nltk.treer   r   r   r   r4   rC   rN   r^   rk   r   r   r   r   r   r   r   r   r   <module>r      s   >   * " I I -H 

H 
$$5 #'8 ##4 D"-> "0iw iX 18  1~	68 	6: 	39 	3"Qh zF r   