JL iedZddlZddlmZddlmZddlmZmZddl m Z ddl m Z m Z mZmZmZmZmZmZmZmZmZGdd eZGd d eZGd d eZGddeZdZdZd&dZdZ dZ!dZ"dZ#GddZ$d'dZ%dZ&GddeZ'GddeZ(Gdd Z)d!Z*d"Z+d#Z,d$Z-e.d%k(re-yy)(z; Module for a resolution-based First Order theorem prover. N) defaultdict)reduce)BaseProverCommandProver) skolemize) AndExpressionApplicationExpressionEqualityExpression ExpressionIndividualVariableExpressionNegatedExpression OrExpressionVariableVariableExpression is_indvarunique_variablec eZdZy)ProverParseErrorN)__name__ __module__ __qualname___/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/inference/resolution.pyrr"srrc"eZdZdZdZddZdZy)ResolutionProverANSWERTNc|sg}d} g}|r|jt| |D]}|jt||j|\}}|rttj |||fS#t $rH}|jrt|jdrd}g}n|r t|n|Yd}~|fSd}~wwxYw)z :param goal: Input expression to prove :type goal: sem.Expression :param assumptions: Input expressions to use as assumptions in the proof :type assumptions: list(sem.Expression) Nz maximum recursion depth exceededF) extendclausify_attempt_proofprintResolutionProverCommand_decorate_clauses RuntimeError _assume_falsestr startswith)selfgoal assumptionsverboseresultclausesaes r_provezResolutionProver._prove*sK Gx/  ,x{+ ,"11':OFG-??HI   !!c!f&7&72'!HG   sA4B C ;C  Cc tt}d}|t|kr||js||r ||ddz}n|dz}|t|kr||k7r}|r{||jsh||j |||j ||}|r;|D]3}|dz|dzf|_|j |t|r/d|fcSd}n|dz }|t|kr|dz }|t|krd|fS)NrTF)rlistlen is_tautologyappendunify_parents)r)r.triedij newclauses newclauses rr!zResolutionProver._attempt_proofKs)D! #g,1:**,8a q(AAA#g,&Av!GAJ,C,C,Ea*%,QZ%5%5gaj%A %-7; 67!eQU^ 2 'y 9'*9~,0'?$: ; !#A!FA#g,& FA1#g,2wr)NNF)rrr ANSWER_KEYr&r1r!rrrrr&sJM!B rrc4eZdZddZddZddZedZy)r#Nc~|t|ts Jt}tj||||d|_y)z :param goal: Input expression to prove :type goal: sem.Expression :param assumptions: Input expressions to use as assumptions in the proof. :type assumptions: list(sem.Expression) N) isinstancerr__init___clauses)r)r*r+provers rrDz ResolutionProverCommand.__init__ms>  f&67 77%'F""4{C rc|jb|jj|j|j |\|_}||_t j||_|jS)zh Perform the actual proof. Store the result to prevent unnecessary re-proving. ) _result_proverr1r*r+rEr#r$_proof)r)r,r.s rprovezResolutionProverCommand.prove}sd << $(LL$7$7 T--/% !DL'$DM1CCGLDK||rc|j|t}tttj }|j D]t}t|dk(st|dts&|dj|k(s9t|djtrW|j|djv|S)Nr4r)rKsetrrrr@rEr6rCr functionargumentr add)r)r,answers answer_exclauses r find_answersz$ResolutionProverCommand.find_answerss 7%&x0@0K0K'LM mm 0FF q vay*?@1I&&)3"6!9#5#57ST F1I../ 0rc d}td|D}ttt|}tt|D]}d}d}||j rd}||j rt||j }d|tt||z dzz|z}d|tt|dzz zt|dzz}|d|d||d|d|d z }|S) z, Decorate the proof output. c3DK|]}tt|ywN)r6r').0rSs r z.sD&SV-Ds A Tautology r4[z]  )maxr6r'ranger7r:)r.outmax_clause_len max_seq_lenr<parentstautseqs rr$z)ResolutionProverCommand._decorate_clausess DGDD#c'l+, s7|$ >AGDqz&&("qz""gaj112^c#gaj/.BBQFG'QGs3q1u:67#a!e*DC Qse2gaj\7)1TF"= =C > r)NNN)F)rrrrDrKrT staticmethodr$rrrr#r#ls%  rr#c\eZdZdZddZdZdZdZdZdZ d Z d Z d Z d Z d ZdZy)ClausecLtj||d|_d|_yrX)r5rD _is_tautologyr:)r)datas rrDzClause.__init__s dD!! rNc | t}|ggf}|ggf}t|tr t|}t |||||t |}g}t |D]K\}} ||vs t |D]3\} } || k7s | |vs| j| s#|j| 5Mg} tt|D]}||vs| j||| S)a Attempt to unify this Clause with the other, returning a list of resulting, unified, Clauses. :param other: ``Clause`` with which to unify :param bindings: ``BindingDict`` containing bindings that should be used during the unification :param used: tuple of two lists of atoms. The first lists the atoms from 'self' that were successfully unified with atoms from 'other'. The second lists the atoms from 'other' that were successfully unified with atoms from 'self'. :param skipped: tuple of two ``Clause`` objects. The first is a list of all the atoms from the 'self' Clause that have not been unified with anything on the path. The second is same thing for the 'other' Clause. :param debug: bool indicating whether debug statements should print :return: list containing all the resulting ``Clause`` objects that could be obtained by unification ) BindingDictrCbool DebugObject_iterate_first_complete_unify_path enumeratesubsumesr8rar6) r)otherbindingsusedskippeddebugr>subsumedr<c1r=c2r-s rr9z Clause.unifys&  "}H <8D ?2hG eT "&E# %42F z* +EAr &z2+EArAv!8"3 B *+ + s:' -A  jm, - rc|D]}||vsyy)z Return True iff every term in 'self' is a term in 'other'. :param other: ``Clause`` :return: bool FTrr)rvr/s r isSubsetOfzClause.isSubsetOfs" A~ rc "g}|D]@}t|tr|j|j/|j| Bt |}t }ggf}ggf}t d}tt|||||t|dkDS)z Return True iff 'self' subsumes 'other', this is, if there is a substitution such that every term in 'self' can be unified with a term in 'other'. :param other: ``Clause`` :return: bool Fr) rCr r8termrjrorqr6rr_subsumes_finalize) r)rv negatedotheratomnegatedotherClauserwrxryrzs rruzClause.subsumess  +D$ 12##DII.##TE*  + $L1=Bxr(E" &&   rcBttj|||SrX)rjr5 __getslice__)r)startends rrzClause.__getslice__sd''eS9::rcHt|Dcgc] }||vs| c}Scc}wrX)rjrs r__sub__zClause.__sub__s!$9Q!5.q9::9s c@ttj||SrX)rjr5__add__)r)rvs rrzClause.__add__sdll4/00rcr|j |jSt|D]\}}t|trt |dz }||kDs+||}t|t r|j |k(r1d|_yt|t r||j k(r d|_y|dz}||kDr`d|_y)z Self is a tautology if it contains ground terms P and -P. The ground term, P, must be an exact match, ie, not using unification. r4TF)rlrtrCr r6r r)r)r<r/r=bs rr7zClause.is_tautologys    )%% %dO DAqa!34IM!eQA!!%6766Q;15D.#'#A'89;15D.#'FA!e #rcDttjd|DS)Nc3^K|]%}|j|jz'ywrX)free constants)rYrs rrZzClause.free..7s"$W$diikDNN4D&D$Ws+-)roperatoror_r)s rrz Clause.free6shll$WRV$WXXrc ^t|Dcgc]}|j||c}Scc}w)z Replace every instance of variable with expression across every atom in the clause :param variable: ``Variable`` :param expression: ``Expression`` )rjreplace)r)variable expressionrs rrzClause.replace9s(dKdt||Hj9KLLKs*c\t|Dcgc]}|j|c}Scc}w)z Replace every binding :param bindings: A list of tuples mapping Variable Expressions to the Expressions to which they are bound. :return: ``Clause`` )rjsubstitute_bindings)r)rwrs rrzClause.substitute_bindingsCs(dKdt//9KLLKs)c>ddjd|DzdzS)N{, c3&K|] }d|z yw)%sNr)rYitems rrZz!Clause.__str__..NsAC C C c |jd|d|d|t|r t|s |||||||S|d|d|dgzf}t||dd|||||dz} t|d|d||\} } } |dd|dz| dz} |dd|dz| dz} |t| | | | ggf||dzz }|S#t$rY|SwxYw)zG This method facilitates movement through the terms of 'other' rrrrr4N)rr6rrr)rrrwrxryrrzrr-rrrrrs rrrs9 JJwaxr(45 u:S[ufhguMMaj'!*q {":;  6!":xz?ETUI  +7a&)Xt, (K& QRy71:-q 9Hqr WQZ/&);I oR  F      s'AB<< C C c t|tsJt|tsJ| t}|ggf}t|tr>t|tr.t |j ||}|d|gz|d|gzf}ggf}nt|tr>t|tr.t ||j |}|d|gz|d|gzf}ggf}nt|tr@t|jj|jfg}|d|gz|df}g|gf}n]t|tr@t|jj|jfg}|d|d|gzf}|ggf}n t||f|||fS)a This method attempts to unify two terms. Two expressions are unifiable if there exists a substitution function S such that S(a) == S(-b). :param a: ``Expression`` :param b: ``Expression`` :param bindings: ``BindingDict`` a starting set of bindings with which the unification must be consistent :return: ``BindingDict`` A dictionary of the bindings required to unify :raise ``BindingException``: If the terms cannot be unified rr4) rCr ror r most_general_unificationrr rrrr)r/rrwrxrrrs rrrs a $$ $ a $$ $= |Bx!&'Jq:O,P.qvvq(C 7aS=$q'QC-0b A, -*Q@Q2R.q!&&(C 7aS=$q'QC-0b A) *!AGG$4$4ahh#?"@A 7aS=$q'*qc A) *!AGG$4$4ahh#?"@A 7DGqcM*#r1v&&  ''rc|ds|dr@t|d|dz|z|z}|jd|z|j|gS|jdgS)Nrr4z -> New Clause: %sz -> End)rjrr)rrrwrxryrzr?s rrsrssg Aw$q'71: 2U:VCD  (945--h788 : rc>t|dst|sdgSgS)NrT)r6)rrrwrxryrzs rrrs! wqz?3u: v  rcg}tt|D]c}|jD]=}t|jst t }|j||}?|j|e|S)zC Skolemize, clausify, and standardize the variables apart. ) _clausifyrrrnamerrrr8)r clause_listrSrnewvars rr r sxKIj12#KKM 6D#+O,=>f5 6 6" # rct|tr+t|jt|jzSt|t rVt|j}t|j}t |dk(sJt |dk(sJ|d|dzgSt|tr t|ggSt|tr t|ggSt|trNt|jtr t|ggSt|jtr t|ggSt)z; :param expression: a skolemized expression in CNF r4r) rCrrrrrr6r rjr r rr)rrrs rrrs*m,))*Yz7H7H-III J -***+:,,-5zQ6{aa6!9$%% J 2 3 |$%% J 5 6 |$%% J 1 2 joo'< =J<() )  ); <J<() )  rc>eZdZd dZdZdZdZdZdZdZ d Z y) roNc6i|_|r|D] \}}|||< yy)z :param binding_list: list of (``AbstractVariableExpression``, ``AtomicExpression``) to initialize the dictionary Nd)r) binding_listvrs rrDzBindingDict.__init__s/ $ 1Q  rct|tsJt|tsJ ||}|r||k(r||j|<yt|t rJ ||j }t|}|r||k(r||j|j <ytd|ztd|z#t$rd}YwxYw#t$rd}YfwxYw)a A binding is consistent with the dict if its variable is not already bound, OR if its variable is already bound to its argument. :param variable: ``Variable`` The variable to bind :param binding: ``Expression`` The atomic to which 'variable' should be bound :raise BindingException: If the variable cannot be bound in this dictionary Nz*Variable %s already bound to another value) rCrr KeyErrorrr rrr)r)rbindingexistingbinding2s r __setitem__zBindingDict.__setitem__s(H---':... H~H7h.&DFF8  != >  0 01*(3Hx83+3w''(&CxP#?8L + H   s#B*B;* B87B8; C C ct|tsJ|j|}|r |j|}|ryy#t$r|cYSwxYw)zD Return the expression to which 'variable' is bound N)rCrrr)r)r intermediates r __getitem__zBindingDict.__getitem__CsT(H---vvh'  $#vvl3  $## $s9 AAc||jvSrXr)r)rs r __contains__zBindingDict.__contains__Pstvv~rc t}|jD]}|j|||<|jD]}|j|||<|S#t$r}td|d|d|d}~wwxYw)a :param other: ``BindingDict`` The dict with which to combine self :return: ``BindingDict`` A new dict containing all the elements of both parameters :raise BindingException: If the parameter dictionaries are not consistent with each other z3Attempting to add two contradicting BindingDicts: 'z' and ''N)rorr)r)rvcombinedrr0s rrzBindingDict.__add__Ss "}HVV ("ffQi  (WW )#ggaj  )O "15u>  sAA A5A00A5c,t|jSrX)r6rrs r__len__zBindingDict.__len__fs466{rcdjfdtjjD}d|zdzS)Nrc3FK|]}|dj|yw): Nr)rYrr)s rrZz&BindingDict.__str__..js$PQs"TVVAYK0Ps!rr)rsortedrkeys)r)data_strs` rrzBindingDict.__str__is599P&:OPPX~##rc d|zSrrrs rrzBindingDict.__repr__mrrrX) rrrrDrrrrrrrrrrroros+%N $&$rroc|| t}||k(r|St|tr t|||St|tr t|||St|trSt|trCt |j |j |t |j|j|zSt||f)ah Find the most general unification of the two given expressions :param a: ``Expression`` :param b: ``Expression`` :param bindings: ``BindingDict`` a starting set of bindings with which the unification must be consistent :return: a list of bindings :raise BindingException: if the Expressions cannot be unified ) rorCr _mgu_varr rrNrOr)r/rrws rrrqs=Av A3 41h'' A3 41h'' A, -*Q@U2V' JJ H $QZZX FG G Aq6 ""rc|j|j|jzvr t||ft |j|fg|zSrX)rrrrro)varrrws rrrsO ||z(:+?+?+AAAZ011S\\:6788CCrceZdZdZy)rct|trtj|d|zytj||y)Nz'%s' cannot be bound to '%s')rCtuple ExceptionrD)r)args rrDzBindingException.__init__s2 c5 !   t%Cc%I J   tS )rNrrrrDrrrrrs*rrceZdZdZy)UnificationExceptionc>tj|d|d|dy)Nrz' cannot unify with ')rrD)r)r/rs rrDzUnificationException.__init__s"41QC' man(x))z(man(x) -> --man(x))z-(man(x) and -man(x))z(man(x) or -man(x))z(man(x) iff man(x))z-(man(x) iff -man(x))z all x.man(x)z--all x.some y.F(x,y) & some x.all y.(-F(x,y))zsome x.all y.sees(x,y)zall x.(man(x) -> mortal(x))z man(Socrates)zmortal(Socrates)rz |- rzall x.(man(x) -> walks(x))z man(John)zsome y.walks(y)z5some e1.some e2.(believe(e1,john,e2) & walk(e2,mary))zsome e0.walk(e0,mary))resolution_testr fromstringr"rrK)p1p2cps rtestResolutionProverrsI)*+,,-*+)*,-*+)**+,-N#CD,-   = >B   / 0B12A RD2$d1#R 0 2 8 8RH EF GH   < =B   | ,B01A RD2$d1#R 0 2 8 8RH EF GHVWA67A QCtA3b)+11!aS9: ; Q(x)z-(P(x) <-> Q(x))z -(all x.P(x))z-(some x.P(x))z some x.P(x)zsome x.all y.P(x,y)zall y.some x.P(x,y)zall z.all y.some x.P(x,y,z)z1all x.(all y.P(x,y) -> -all y.(Q(x,y) -> R(x,y))))r rr"r )lexprs r test_clausifyrsL  ! !E (5' () (5/0 12 (5/0 12 (589 :; (5-. /0 (567 89 (5/0 12 (5*+ ,- (5) *+ (5+, -. (5) *+ (5)* +, (5' () (5./ 01 (5./ 01 (567 89 (5LM NOrctttttjd}tt ||gj y)Nr)rr"rr rr#rK)rs rdemorsBO G Gh'A !!aS ) / / 12r__main__)NNrX)/__doc__r collectionsr functoolsrnltk.inference.apirrnltk.semrnltk.sem.logicrr r r r r rrrrrrrrr#r5rjrrrrrsrr rrorrrrrqrrrrrrrrrs#8     y C vC L?/?DcTcL)X$N+(\  0]]@#6D*y*C9C / /=> P43 zFr