
    /hk                         S SK Jr  S SKJr  S SKJr  S SKJrJrJ	r	  S SK
Jr  S SKJr  \ " S S5      5       r " S	 S
5      r " S S5      r " S S5      rS rS rS rS r\S:X  a  \" 5         gg)    )defaultdict)total_ordering)chain)DependencyGrammarDependencyProductionProbabilisticDependencyGrammar)raise_unorderable_types)DependencyGraphc                   H    \ 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)DependencySpan   a0  
A contiguous span over some part of the input string representing
dependency (head -> modifier) relationships amongst words.  An atomic
span corresponds to only one word so it isn't a 'span' in the conventional
sense, as its _start_index = _end_index = _head_index for concatenation
purposes.  All other spans are assumed to have arcs between all nodes
within the start and end indexes of the span, and one head index corresponding
to the head word for the entire span.  This is the same as the root node if
the dependency structure were depicted as a graph.
c                     Xl         X l        X0l        X@l        XPl        XU[        U5      4U l        [        U R                  5      U l        g N)	_start_index
_end_index_head_index_arcs_tagstuple_comparison_keyhash_hash)selfstart_index	end_index
head_indexarcstagss         ]/var/www/auris/envauris/lib/python3.13/site-packages/nltk/parse/projectivedependencyparser.py__init__DependencySpan.__init__(   sB    '#%

 +
E$KP$../
    c                     U R                   $ )zS
:return: An value indexing the head of the entire ``DependencySpan``.
:rtype: int
)r   r   s    r   r   DependencySpan.head_index1   s    
 r"   c                 N    SU R                   U R                  U R                  4-  $ )zR
:return: A concise string representatino of the ``DependencySpan``.
:rtype: str.
Span %d-%d; Head Index: %d)r   r   r   r$   s    r   __repr__DependencySpan.__repr__8   s/    
 ,OO/
 
 	
r"   c                     SU R                   U R                  U R                  4-  n[        [	        U R
                  5      5       H'  nUSX R
                  U   U R                  U   4-  -  nM)     U$ )zQ
:return: A verbose string representation of the ``DependencySpan``.
:rtype: str
r'   z
%d <- %d, %s)r   r   r   rangelenr   r   )r   stris      r   __str__DependencySpan.__str__C   so    
 +OO.
 

 s4::'A#q**Q-A&GGGC (
r"   c                 p    [        U 5      [        U5      :H  =(       a    U R                  UR                  :H  $ r   )typer   r   others     r   __eq__DependencySpan.__eq__Q   s-    J$u+%W$*>*>%BWBW*W	
r"   c                     X:X  + $ r    r3   s     r   __ne__DependencySpan.__ne__V   s      r"   c                 v    [        U[        5      (       d  [        SX5        U R                  UR                  :  $ )N<)
isinstancer   r	   r   r3   s     r   __lt__DependencySpan.__lt__Y   s0    %00#C5##e&;&;;;r"   c                     U R                   $ )z5
:return: The hash value of this ``DependencySpan``.
)r   r$   s    r   __hash__DependencySpan.__hash__^   s     zzr"   )r   r   r   r   r   r   r   N)__name__
__module____qualname____firstlineno____doc__r    r   r(   r/   r5   r9   r>   rA   __static_attributes__r8   r"   r   r   r      s/    	0 	


!<
r"   r   c                   0    \ rS rSrSrS rS rS rS rSr	g)		ChartCellj   z
A cell from the parse chart formed when performing the CYK algorithm.
Each cell keeps track of its x and y coordinates (though this will probably
be discarded), and a list of spans serving as the cell's entries.
c                 :    Xl         X l        [        5       U l        g)ze
:param x: This cell's x coordinate.
:type x: int.
:param y: This cell's y coordinate.
:type y: int.
N)_x_yset_entries)r   xys      r   r    ChartCell.__init__q   s     r"   c                 :    U R                   R                  U5        g)z
Appends the given span to the list of spans
representing the chart cell's entries.

:param span: The span to add.
:type span: DependencySpan
N)rP   add)r   spans     r   rU   ChartCell.add|   s     	$r"   c                 N    SU R                   U R                  U R                  4-  $ )zN
:return: A verbose string representation of this ``ChartCell``.
:rtype: str.
zCC[%d,%d]: %s)rM   rN   rP   r$   s    r   r/   ChartCell.__str__   s"    
 $''477DMM!BBBr"   c                     SU -  $ )zN
:return: A concise string representation of this ``ChartCell``.
:rtype: str.
z%sr8   r$   s    r   r(   ChartCell.__repr__   s    
 d{r"   )rP   rM   rN   N)
rC   rD   rE   rF   rG   r    rU   r/   r(   rH   r8   r"   r   rJ   rJ   j   s    	 Cr"   rJ   c                   *    \ rS rSrSrS rS rS rSrg)ProjectiveDependencyParser   a~  
A projective, rule-based, dependency parser.  A ProjectiveDependencyParser
is created with a DependencyGrammar, a set of productions specifying
word-to-word dependency relations.  The parse() method will then
return the set of all parses, in tree representation, for a given input
sequence of tokens.  Each parse must meet the requirements of the both
the grammar and the projectivity constraint which specifies that the
branches of the dependency tree are not allowed to cross.  Alternatively,
this can be understood as stating that each parent node and its children
in the parse tree form a continuous substring of the input sequence.
c                     Xl         g)z
Create a new ProjectiveDependencyParser, from a word-to-word
dependency grammar ``DependencyGrammar``.

:param dependency_grammar: A word-to-word relation dependencygrammar.
:type dependency_grammar: DependencyGrammar
N)_grammar)r   dependency_grammars     r   r    #ProjectiveDependencyParser.__init__   s	     +r"   c              #     #    [        U5      U l        / n[        S[        U R                  5      S-   5       H  nUR	                  / 5        [        S[        U R                  5      S-   5       HS  nX#   R	                  [        X45      5        X4S-   :X  d  M)  X#   U   R                  [        US-
  X3S-
  S/S/5      5        MU     M     [        S[        U R                  5      S-   5       H  n[        US-
  SS5       Hx  n[        US-
  US5       Ha  nX%   U   R                   HI  nX#   U   R                   H1  nU R                  Xg5       H  nX#   U   R                  U5        M     M3     MK     Mc     Mz     M     U[        U R                  5         S   R                   Hf  n	Sn
[        [        U5      5       H,  nU
SUS-   X   X   SSSU	R                  U   S-   SS	S	4
-  -  n
M.     [        U
5      nUR                  5       v   Mh     g
7f)a  
Performs a projective dependency parse on the list of tokens using
a chart-based, span-concatenation algorithm similar to Eisner (1996).

:param tokens: The list of input tokens.
:type tokens: list(str)
:return: An iterator over parse trees.
:rtype: iter(Tree)
r      null    	%d	%s	%s	%s	%s	%s	%d	%s	%s	%s
ROOT-N)list_tokensr+   r,   appendrJ   rU   r   rP   concatenater   r
   tree)r   tokenschartr.   jkspan1span2newspanparseconll_formatdgs               r   rx    ProjectiveDependencyParser.parse   s     F|q#dll+a/0ALL1c$,,/!34	!0A:HQKOON1q5!URD6($ST 5 1 q#dll+a/0A1q5"b)q1ua,A!&!!5!5%*Xa[%9%9E+/+;+;E+I % 8 ,J &: "6 - * 1 3t||,-a099EL3v;'  LEIIKKNQ&P ! 	 (  !.B'')O+ :s   BHE7Hc           	         / nUR                   UR                   :X  a  [        S5        UR                   UR                   :  a  UnUnUnUR                  UR                  -   nUR                  UR                  -   nU R                  R                  U R                  UR                     U R                  UR                     5      (       aa  UR                  XRR                  UR                   -
  '   UR                  [        UR                   UR                  UR                  UU5      5        UR                  UR                  -   nU R                  R                  U R                  UR                     U R                  UR                     5      (       aa  UR                  XQR                  UR                   -
  '   UR                  [        UR                   UR                  UR                  UU5      5        U$ a  
Concatenates the two spans in whichever way possible.  This
includes rightward concatenation (from the leftmost word of the
leftmost span to the rightmost word of the rightmost span) and
leftward concatenation (vice-versa) between adjacent spans.  Unlike
Eisner's presentation of span concatenation, these spans do not
share or pivot on a particular word/word-index.

:return: A list of new spans formed through concatenation.
:rtype: list(DependencySpan)
z8Error: Mismatched spans - replace this with thrown errorr   printr   r   r`   containsrm   r   rn   r   r   r   ru   rv   spans	temp_spannew_arcsnew_tagss          r   ro   &ProjectiveDependencyParser.concatenate   s    !3!33LM 2 22IEE;;,;;,==!!LL**+T\\%:K:K-L
 
 @E?P?PH&&););;<LL&&$$%% ;;,==!!LL**+T\\%:K:K-L
 
 @E?P?PH&&););;<LL&&$$%% r"   r`   rm   N)	rC   rD   rE   rF   rG   r    rx   ro   rH   r8   r"   r   r]   r]      s    
+0d4r"   r]   c                   6    \ rS rSrSrS rS rS rS rS r	Sr
g	)
'ProbabilisticProjectiveDependencyParseri  ag  A probabilistic, projective dependency parser.

This parser returns the most probable projective parse derived from the
probabilistic dependency grammar derived from the train() method.  The
probabilistic model is an implementation of Eisner's (1996) Model C, which
conditions on head-word, head-tag, child-word, and child-tag.  The decoding
uses a bottom-up chart-based span concatenation algorithm that's identical
to the one utilized by the rule-based projective parser.

Usage example

>>> from nltk.parse.dependencygraph import conll_data2

>>> graphs = [
... DependencyGraph(entry) for entry in conll_data2.split('\n\n') if entry
... ]

>>> ppdp = ProbabilisticProjectiveDependencyParser()
>>> ppdp.train(graphs)

>>> sent = ['Cathy', 'zag', 'hen', 'wild', 'zwaaien', '.']
>>> list(ppdp.parse(sent))
[Tree('zag', ['Cathy', 'hen', Tree('zwaaien', ['wild', '.'])])]

c                     g)zX
Create a new probabilistic dependency parser.  No additional
operations are necessary.
Nr8   r$   s    r   r    0ProbabilisticProjectiveDependencyParser.__init__:  s    r"   c                    [        U5      U l        / n[        S[        U R                  5      S-   5       H  nUR	                  / 5        [        S[        U R                  5      S-   5       H  nX#   R	                  [        X45      5        X4S-   :X  d  M)  XS-
     U R                  R                  ;   aQ  U R                  R                  XS-
         H-  nX#   U   R                  [        US-
  X3S-
  S/U/5      5        M/     M  [        SXS-
     -  5        / s  s  $    M     [        S[        U R                  5      S-   5       H  n[        US-
  SS5       Hx  n[        US-
  US5       Ha  nX&   U   R                   HI  nX#   U   R                   H1  nU R                  Xx5       H  n	X#   U   R                  U	5        M     M3     MK     Mc     Mz     M     / n
SnSnU[        U R                  5         S   R                   H  nSnSn[        [        U5      5       Hd  nUSX   S	UR                  U   S-   S	4-  -  nUS
US-   X   X   UR                  U   UR                  U   S	UR                  U   S-   SSS4
-  -  nMf     [        U5      nU R                  U5      nU
R	                  UUR!                  5       45        M     U
R#                  5         S U
 5       $ )a(  
Parses the list of tokens subject to the projectivity constraint
and the productions in the parser's grammar.  This uses a method
similar to the span-concatenation algorithm defined in Eisner (1996).
It returns the most probable parse derived from the parser's
probabilistic dependency grammar.
r   rd   re   z7No tag found for input token '%s', parse is impossible.rg   Nrh   z%s	%s	%d	%s
rf   ri   rj   rk   c              3   *   #    U  H	  u  pUv   M     g 7fr   r8   ).0scorerp   s      r   	<genexpr>@ProbabilisticProjectiveDependencyParser.parse.<locals>.<genexpr>  s     0%%%s   )rl   rm   r+   r,   rn   rJ   r`   r   rU   r   r   rP   ro   r   r
   compute_probrp   sort)r   rq   rr   r.   rs   tagrt   ru   rv   rw   trees	max_parse	max_scorerx   ry   malt_formatrz   r   s                     r   rx   -ProbabilisticProjectiveDependencyParser.parse@  s    F|q#dll+a/0ALL1c$,,/!34	!0A:!e}(;(;;#'==#6#6v!e}#EC!HQKOO .q1uaQse L $F
 U$Um,  "	 5 1  q#dll+a/0A1q5"b)q1ua,A!&!!5!5%*Xa[%9%9E+/+;+;E+I % 8 ,J &: "6 - * 1 		3t||,-a099ELK3v;'1IKKNQ&	5     LEIIKKNKKNKKNQ&P !  (* !.B%%b)ELL%+,5 :6 	

0%00r"   c           	         / nUR                   UR                   :X  a  [        S5        UR                   UR                   :  a  UnUnUnUR                  UR                  -   nUR                  UR                  -   nU R                  R                  U R                  UR                     U R                  UR                     5      (       aa  UR                  XRR                  UR                   -
  '   UR                  [        UR                   UR                  UR                  UU5      5        UR                  UR                  -   nUR                  UR                  -   nU R                  R                  U R                  UR                     U R                  UR                     5      (       aa  UR                  XQR                  UR                   -
  '   UR                  [        UR                   UR                  UR                  UU5      5        U$ r}   r~   r   s          r   ro   3ProbabilisticProjectiveDependencyParser.concatenate  s    !3!33LM 2 22IEE;;,;;,==!!LL**+T\\%:K:K-L
 
 @E?P?PH&&););;<LL&&$$%% ;;,;;,==!!LL**+T\\%:K:K-L
 
 @E?P?PH&&););;<LL&&$$%% r"   c           
         / n[        [        5      n0 nU GH  n[        S[        UR                  5      5       GH~  n[        [        R                  " UR                  U   S   R                  5       5      5      nUR                  U5      nUR                  U5      n	X-   n
[        SUS-   -
  U	S-   5       GH  nUR                  U   S   nUR                  U   S   nX;   a  XL   R                  U5        OU1XL'   SnSnSnSnUS:  a  X-   nUS:  a*  UR                  UU      S   nUR                  UU      S   nUS	:w  a0  UR                  UUS-         S   nUR                  UUS-         S   nUS:w  a  UR                  [        X/5      5        S
R                  UUUUU5      nSR                  UUU5      nUU==   S-  ss'   UU==   S-  ss'   GM$  US:  d  GM-  X-   S-
  nUU
:  a*  UR                  UU      S   nUR                  UU      S   nUS:w  a0  UR                  UUS-
        S   nUR                  UUS-
        S   nUS:w  a  UR                  [        X/5      5        SR                  UUUUU5      nSR                  UUU5      nUU==   S-  ss'   UU==   S-  ss'   GM      GM     GM     [        X#U5      U l        g)aK  
Trains a ProbabilisticDependencyGrammar based on the list of input
DependencyGraphs.  This model is an implementation of Eisner's (1996)
Model C, which derives its statistics from head-word, head-tag,
child-word, and child-tag relationships.

:param graphs: A list of dependency graphs to train from.
:type: list(DependencyGraph)
rd   depsr   rg   wordr   STOPSTARTre   '(head ({} {}) (mods ({}, {}, {}) left))(mods ({}, {}, {}) left))((head ({} {}) (mods ({}, {}, {}) right))(mods ({}, {}, {}) right))N)r   intr+   r,   nodesrl   r   from_iterablevaluesleft_childrenright_childrenrU   rn   r   formatr   r`   )r   graphsproductionseventsr   rz   
node_indexchildrennr_left_childrennr_right_childrennr_childrenchild_index	head_wordhead_tagchild	child_tag	prev_wordprev_tagarray_index
head_event	mod_events                        r   train-ProbabilisticProjectiveDependencyParser.train  s/    S!B#As288}5
''(<V(D(K(K(MN $&#3#3J#? $&$5$5j$A!.B#()A-.0AA0E$K !# 4V <I!xx
3E:H (++H5+3*"E &I 'I&H"Q&1&D&!+$&HHXk-B$CF$KE(*+1F(G(NI&",(*+/1J(KF(SI')xxq0I'J5'QH F?'../CIw/WX%N%U%U!%$%$&
 %@$F$F$%$%	
 z*a/*y)Q.)$q&1&Dq&H&4$&HHXk-B$CF$KE(*+1F(G(NI&!+(*+/1J(KF(SI')xxq0I'J5'QH F?'../CIw/WX%O%V%V!%$%$&
 %A$G$G$%$%	
 z*a/*y)Q.)y$ 6 N 7{DQr"   c           	      (   Sn[        S[        UR                  5      5       GHk  n[        [        R
                  " UR                  U   S   R                  5       5      5      nUR                  U5      nUR                  U5      nXV-   n[        SUS-   -
  US-   5       GH  nUR                  U   S   n	UR                  U   S   n
SnSnS	nS	nUS:  a  X-   nUS:  a(  UR                  XO      S   nUR                  XO      S   nUS
:w  a.  UR                  XOS-         S   nUR                  XOS-         S   nSR                  UUUU	U
5      nSR                  UU	U
5      nU R                  R                  U   nU R                  R                  U   nUS:w  a  UUU-  -  nGM  SnGM  US:  d  GM  X-   S-
  nX:  a(  UR                  XO      S   nUR                  XO      S   nUS:w  a.  UR                  XOS-
        S   nUR                  XOS-
        S   nSR                  UUUU	U
5      nSR                  UU	U
5      nU R                  R                  U   nU R                  R                  U   nUS:w  a  UUU-  -  nGM  SnGM     GMn     U$ )a  
Computes the probability of a dependency graph based
on the parser's probability model (defined by the parser's
statistical dependency grammar).

:param dg: A dependency graph to score.
:type dg: DependencyGraph
:return: The probability of the dependency graph.
:rtype: int
g      ?rd   r   r   rg   r   r   r   r   re   r   r   g:0yE>r   r   )r+   r,   r   rl   r   r   r   r   r   r   r`   _events)r   rz   probr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   h_countm_counts                       r   r   4ProbabilisticProjectiveDependencyParser.compute_prob  s    3rxx=1JE//0DV0L0S0S0UVWH!//
; " 1 1* =*>K$Q*:Q*>%?ARUVAVWHHZ08	88J/6"	#	"?"-"@K"a' ")> ? G$&HHX-B$CE$J	"b($&HHXAo-F$G$O	#%88H1_,E#Fu#M!J!Q!Q! ! "J !< B B ! !I
 #mm33J?G"mm33I>G !|' 11) 1_"-"@1"DK"0 ")> ? G$&HHX-B$CE$J	"a'$&HHXAo-F$G$O	#%88H1_,E#Fu#M!K!R!R! ! "J != C C ! !I
 #mm33J?G"mm33I>G!|' 11)}  X 2N r"   r   N)rC   rD   rE   rF   rG   r    rx   ro   r   r   rH   r8   r"   r   r   r     s'    4@1D3jTRlSr"   r   c                  ,    [        5         [        5         g r   )projective_rule_parse_demoprojective_prob_parse_demor8   r"   r   demor   h  s      r"   c                      [         R                  " S5      n [        U 5        [        U 5      nUR	                  / SQ5      nU H  n[        U5        M     g)zs
A demonstration showing the creation and use of a
``DependencyGrammar`` to perform a projective dependency
parse.
zP
    'scratch' -> 'cats' | 'walls'
    'walls' -> 'the'
    'cats' -> 'the'
    )thecatsscratchr   wallsN)r   
fromstringr   r]   rx   grammarpdpr   rp   s       r   r   r   n  sL      **	G 
'N
$W
-CII@AEd r"   c                  |   [        5         [        S5        [        S5        [        S5        [        R                  " S5      n [        U 5        [        5         [        S5        [        S5        [        U 5      nUR	                  / SQ5      nU H  n[        U5        M     [        5         [        S5        [        S	5        [        S
5        [        S5        [        R                  " S5      n [        U 5        [        5         [        S5        [        U 5      nUR	                  / SQ5      nU H  n[        U5        M     g)z
A demonstration showing the creation of a ``DependencyGrammar``
in which a specific number of modifiers is listed for a given
head.  This can further constrain the number of possible parses
created by a ``ProjectiveDependencyParser``.
z>A grammar with no arity constraints. Each DependencyProductionz;specifies a relationship between one head word and only onezmodifier word.zj
    'fell' -> 'price' | 'stock'
    'price' -> 'of' | 'the'
    'of' -> 'stock'
    'stock' -> 'the'
    z<For the sentence 'The price of the stock fell', this grammarz(will produce the following three parses:)r   priceofr   stockfellz.By contrast, the following grammar contains a z2DependencyProduction that specifies a relationshipz5between a single head word, 'price', and two modifierzwords, 'of' and 'the'.zh
    'fell' -> 'price' | 'stock'
    'price' -> 'of' 'the'
    'of' -> 'stock'
    'stock' -> 'the'
    z:This constrains the number of possible parses to just one:N)r   r   r   r]   rx   r   s       r   arity_parse_demor     s    
G	
JK	
GH	
**	G 
'N	G	
HI	
45
$W
-CIIDEEd  
G	
:;	
>?	
AB	
"#**	G 
'N	G	D %W
-CIIDEEd r"   c                  f   SSK Jn   U R                  S5       Vs/ s H  o(       d  M  [        U5      PM     nn[	        5       n[        S5        UR                  U5        / SQn[        SSR                  U5      S5        [        S	5        UR                  U5       H  n[        U5        M     g
s  snf )zH
A demo showing the training and use of a projective
dependency parser.
r   )conll_data2z

z6Training Probabilistic Projective Dependency Parser...)Cathyzaghenwildzwaaien.z	Parsing ' z'...zParse:N)	nltk.parse.dependencygraphr   splitr
   r   r   r   joinrx   )r   entryr   ppdpsentrp   s         r   r   r     s    
 72=2C2CF2KU2Ku$oe$2KFU24D	
BCJJv:D	+sxx~v.	(O

4 d ! Vs
   
B.B.__main__N)collectionsr   	functoolsr   	itertoolsr   nltk.grammarr   r   r   nltk.internalsr	   r   r
   r   rJ   r]   r   r   r   r   r   rC   r8   r"   r   <module>r      s    $ $  
 3 6 F F F\( (`} }JA AR
!(3l& zF r"   