JL i5 dZddlmZddlmZddlmZmZmZm Z m Z m Z m Z m Z mZddlmZGddZGdd ZGd d Zdd Zedk(r2edD] Zee eedD] Zee y y )a An implementation of the Hole Semantics model, following Blackburn and Bos, Representation and Inference for Natural Language (CSLI, 2005). The semantic representations are built by the grammar hole.fcfg. This module contains driver code to read in sentences and parse them according to a hole semantics grammar. After parsing, the semantic representation is in the form of an underspecified representation that is not easy to read. We use a "plugging" algorithm to convert that representation into first-order logic formulas. )reduce) load_parser) AllExpression AndExpressionApplicationExpressionExistsExpression IffExpression ImpExpressionLambdaExpressionNegatedExpression OrExpression) skolemizec`eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z ed ed eeeeeeeee ee eiZy) ConstantsALLEXISTSNOTANDORIMPIFFPREDLEQHOLELABELc.t|j|SN)rvariableves S/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/sem/hole.pyzConstants.>s- A6c.t|j|Sr)rrrs r"r#zConstants.?s-ajj!<r$N)__name__ __module__ __qualname__rrrrrrrrrrrr rr r r rMAPr$r"rr0sn C F C C B C C D C D E 6<  ] L ] ] # Cr$rc^eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZy) HoleSemanticsar This class holds the broken-down components of a hole semantics, i.e. it extracts the holes, labels, logic formula fragments and constraints out of a big conjunction of such as produced by the hole semantics grammar. It then provides some operations on the semantics dealing with holes, labels and finding legal ways to plug holes with labels. ct|_t|_i|_t|_|j ||j |_|j|_ y)aB Constructor. `usr' is a ``sem.Expression`` representing an Underspecified Representation Structure (USR). A USR has the following special predicates: ALL(l,v,n), EXISTS(l,v,n), AND(l,n,n), OR(l,n,n), IMP(l,n,n), IFF(l,n,n), PRED(l,v,n,v[,v]*) where the brackets and star indicate zero or more repetitions, LEQ(n,n), HOLE(n), LABEL(n) where l is the label of the node described by the predicate, n is either a label or a hole, and v is a variable. N) setholeslabels fragments constraints _break_down_find_top_most_labelstop_most_labels_find_top_holetop_hole)selfusrs r"__init__zHoleSemantics.__init__RsV$U e 5 #99;++- r$c8||j|jzvS)ze Return true if x is a node (label or hole) in this semantic representation. )r0r/)r8xs r"is_nodezHoleSemantics.is_nodels T[[4::-..r$ct|tr7|j|j|j|jyt|t r|j \}}|jjtjk(r,|jjt|d|dy|jjtjk(r|jj|dy|jjtj k(r|j"j|dy|d}||j$vsJ||ddf|j$|<yt'|j))z Extract holes, labels, formula fragments and constraints from the hole semantics underspecified representation (USR). rN) isinstancerr3firstsecondruncurryrnamerrr2add Constraintrr/rr0r1 ValueErrorlabel)r8r9funcargsrHs r"r3zHoleSemantics._break_downss c= )   SYY '   SZZ ( 2 3JD$}}!!Y]]2  $$ZQa%AB##y~~5 tAw'##y6 Q(QDNN222)-tABx(8u%SYY[) )r$c|j}|jjD]$}|d}|D]}||vs|j|&|S)Nr?)copyr1valuesdiscard)r8 node_list top_nodesfrJargs r"_find_top_nodeszHoleSemantics._find_top_nodess`NN$ &&( +AQ4D +)#%%c* + + r$c8|j|jS)z Return the set of labels which are not referenced directly as part of another formula fragment. These will be the top-most labels for the subtree that they are part of. )rSr0r8s r"r4z#HoleSemantics._find_top_most_labelss ##DKK00r$cx|j|j}t|dk(sJ|jS)zK Return the hole that will be the top of the formula tree. r?)rSr/lenpop)r8 top_holess r"r6zHoleSemantics._find_top_holes6((4 9~"""}}r$c`g}|j|jgfg|ji||S)z Calculate and return all the legal pluggings (mappings of labels to holes) of this semantics given the constraints. ) _plug_nodesr7r5)r8records r" pluggingszHoleSemantics.pluggingss4  4=="-.0D0Db&Q r$cL|gk7r|d\}}||jvr|j|||dd|||y||jvsJ|j|d}|Dcgc]}|j |s||f} }|j | |ddz|||yt dcc}w)ac Plug the nodes in `queue' with the labels in `potential_labels'. Each element of `queue' is a tuple of the node to plug and the list of ancestor holes from the root of the graph to that node. `potential_labels' is a set of the labels which are still available for plugging. `plug_acc' is the incomplete mapping of holes to labels made on the current branch of the search tree so far. `record' is a list of all the complete pluggings that we have found in total so far. It is the only parameter that is destructively updated. rr?Nz queue empty)r/ _plug_holer0r1r=r[ Exception) r8queuepotential_labelsplug_accr\node ancestorsrJaheads r"r[zHoleSemantics._plug_nodess B; %a T9tzz!)U12Y0@(Ft{{***~~d+A.04H1 QIHH  ab !13CXvVM* *Is B!3B!cj||vsJ|g|z}|D]}|j||r|j} || |<|j} | j|t| dk(r/|j | |j g|j | |j|||fgz| | |y)z~ Try all possible ways of plugging a single hole. See _plug_nodes for the meanings of the parameters. rN)_violates_constraintsrLremoverW_sanity_check_pluggingr7appendr[) r8hole ancestors0rapotential_labels0 plug_acc0r\relrcrbs r"r_zHoleSemantics._plug_holes :%%%FZ' # A))!Y7 ~~'HHTN0557   # #A &#$)++HdmmRH h'  a^,,.>&; r$cf|jD]"}|j|k(s|j|vs"yy)z Return True if the `label' cannot be placed underneath the holes given by the set `ancestors' because it would violate the constraints imposed on it. TF)r2lhsrhs)r8rHrecs r"riz#HoleSemantics._violates_constraintss8 !! Auu~55 ) r$cB||jvr |g|z}||}n|}||jvsJ|jD]"}|j|k(s|j|vr"J|j |d}|D]+}|j |s|j|||g|z-y)z Make sure that a given plugging is legal. We recursively go through each node and make sure that no constraints are violated. We also check that all holes have been filled. r?N)r/r0r2rsrtr1r=rk)r8pluggingrdrerHrurJrRs r"rkz$HoleSemantics._sanity_check_pluggings 4:: *ITNEE ###!! *Auu~uu ))) *~~e$Q' PC||C ++HcE7Y;NO Pr$c:|j||jS)z Return the first-order logic formula tree for this underspecified representation using the plugging given. ) _formula_treer7)r8rws r" formula_treezHoleSemantics.formula_trees !!(DMM::r$c"||vr|j|||S||jvrb|j|\}}|Dcgc]}|j||}}ttj|j j |S|Scc}wr)ryr1rrr)rrD)r8rwrdpredrJrRchildrens r"ryzHoleSemantics._formula_tree s 8 %%h? ? T^^ #-JD$EIJc**8S9JHJ)-- (:(:;XF FKKsB N)r&r'r(__doc__r:r=r3rSr4r6r]r[r_rirkrzryr*r$r"r,r,IsK.4/*.1+B)V P(;r$r,c.eZdZdZdZdZdZdZdZy)rFz~ This class represents a constraint of the form (L =< N), where L is a label and N is a node (a label or a hole). c ||_||_yrrsrt)r8rsrts r"r:zConstraint.__init__1sr$c|j|jk(r4|j|jk(xr|j|jk(SyNF) __class__rsrtr8others r"__eq__zConstraint.__eq__5s: >>U__ ,88uyy(BTXX-B Br$c||k( Srr*rs r"__ne__zConstraint.__ne__;sEM""r$c*tt|Sr)hashreprrUs r"__hash__zConstraint.__hash__>sDJr$c<d|jd|jdS)N(z < )rrUs r"__repr__zConstraint.__repr__As488*Cz++r$N) r&r'r(r~r:rrrrr*r$r"rFrF+s   # ,r$rFNc*|sd}|r td|t|}|j}t|j |}|rtdt |zg}|D]}|j dj}|r td|t|tr|j}t|trt|} |r td| t| } |rtd| jtd| jtd | jtd | j td | j"td | j$j'D]\} } td | d| | j)} tt+| j,| }|r7t/|D]\}}ttd||fz!t|j1||S)Nz"grammars/sample_grammars/hole.fcfgzReading grammar filezGot %d different parsesSEMz Raw: z Skolemized:z Holes: z Labels: z Constraints: z Top hole: z Top labels: z Fragments: z: z%d. %s)printrsplitlistparserWrHsimplifyr@r termrr,r/r0r2r7r5r1itemsr]maprz enumerateextend)sentencegrammar_filenameverboseparsertokenstrees all_readingstreesem skolemizedhole_semrqrQr]readingsirs r" hole_readingsrEs ? $&67 ) *F^^ F f% &E '#e*45L,&jjl5!**,  - %./((C./s^  - ,!,  /8>> 2 /8?? 3 /8#7#7 8 /8#4#4 5 /8#;#; < ,  **002 %11#Rsm$ %&&( H119=> !(+ )1h!Q'( ) GH%Y,&\ r$__main__z a dog barkszevery girl chases a dogr)r~ functoolsr nltk.parsernltk.sem.logicrrrrr r r r r nltk.sem.skolemizerrr,rFrr&rrr*r$r"rs "   )2__D,,4>B z = ) a G 4 5 a r$